Issue displaying question for answer in views.py - python-3.x

I ran into a problem I have questions that are related to items_buy_id , there are also choices that are related to question_id questions
Questions items_buy_id It turns out to connect
And with the choice you will not contact as it should
My models.py
from django.db import models
from datetime import datetime
from phonenumber_field.modelfields import PhoneNumberField
from django_resized import ResizedImageField
from email.policy import default
from django.utils.translation import gettext_lazy
class Items_buy(models.Model):
class Meta:
db_table = 'items_buy'
verbose_name = 'Телефон который покупаем'
verbose_name_plural = 'Телефоны которые покупаем'
image_phone = ResizedImageField(size=[100,100], upload_to='for_sell/',verbose_name='Фотография модели телефона')
model_produkt = models.TextField(max_length=80, verbose_name='Модель продукта ')
text = models.TextField(max_length=500, verbose_name='Текст')
max_prise_iphone = models.FloatField(verbose_name='Максимальная цена telefoha')
image_phone_for_buy_bord = ResizedImageField(size=[100,100],upload_to='for_sell/',verbose_name='Фотография модели телефона ha prodazy')
def __str__(self):
return self.model_produkt
class Question(models.Model):
class Meta:
db_table = 'question'
verbose_name = 'Вопрос к телефону'
verbose_name_plural = 'Вопросы к телефону'
items_buy_id = models.ForeignKey(Items_buy, on_delete=models.RESTRICT)
title = models.CharField(max_length=150,verbose_name='Заголовок вопросa')
question_text =models.TextField(max_length=100, verbose_name='Заголовок вопросa text')
max_prise_qustion = models.FloatField(verbose_name='Максимальная цена')
def __str__(self):
return self.title
class Choice(models.Model):
class Meta:
db_table = 'choice'
verbose_name = 'Выбор ответа'
verbose_name_plural = 'Выбор ответов'
#items_buy_id = models.ForeignKey(Items_buy, on_delete=models.RESTRICT)
question_id = models.ForeignKey(Question, on_delete=models.RESTRICT)
title = models.CharField(max_length=1000, verbose_name='Заголовок выбора')
points = models.FloatField(verbose_name='Цена ответа')
#lock_other = models.BooleanField(default=False, verbose_name='Смотреть другой вариант ответа')
def __str__(self):
return self.title
My urls.py
from django.urls import path, re_path
from . import views
urlpatterns = [
path('',views.home, name ='home'),
path('sell_iphone/', views.sell_iphone, name = 'sell_iphone'),
path('sell_iphone_page/<int:pk>/', views.sell_iphone_page, name= 'sell_iphone_page'),
path("getqestion/<int:pk>/", views.getqestion, name = 'getqestion'),
]
My html
{% load static %}
{% block content %}
<head>
<link rel="stylesheet" href="{% static 'css/qestion.css' %}" type="text/css">
</head>
<body>
{% include 'navbar.html' %}
<div class="bar">
{% for question in test %}
<div class="bar_infor_bar">
<div class="bar_infor_bar_title">{{question.title}} </div>
<div class="wraper_sell_in_line_img_class2_qestion_text">{{question.question_text}}</div>
{% for choiceses in choice %}
<div class="bar_infor_button_nav">
<button class="bar_infor_button">{{choiceses.title}}</button>
</div>
{% endfor %}
</div>
{% endfor %}
</div>
</body>
{% endblock %}
My views.py
from django.shortcuts import render, redirect
from .models import Items_buy, Question, Choice, Answer, Orders
from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage
def home(request):
return render(request, 'home.html')
def sell_iphone(request):
limit = request.GET.get('limit')
if limit == None:
limit = 40
limit = int(limit)
iphone = Items_buy.objects.filter()
count = iphone.count()
page = request.GET.get('page')
paginator = Paginator(iphone, 1)
try:
iphone = paginator.page(page)
except PageNotAnInteger:
page = 1
iphone = paginator.page(page)
except EmptyPage:
page = paginator.num_pages
iphone = paginator.page(page)
#pages = list(range(1, (paginator.num_pages + 1)))
iphone = Items_buy.objects.all()
#iphone = iphone[0:limit]
context = {'iphone':iphone, 'count':count, 'paginator':paginator, }
return render(request, 'sell_iphone.html', context)
def sell_iphone_page(request,pk ):
iphones = Items_buy.objects.filter(id=pk)
#question = Question.objects.all()
context = {'iphones':iphones, }
return render(request, 'sell_iphone_page.html', context)
`def getqestion( request, pk):
test = Question.objects.filter(items_buy_id = pk)
choice = Choice.objects.filter(question_id = pk)
context = {'test':test,'choice':choice}
return render(request, 'getqestion.html', context)`
I'm having a problem with the def getqestion function. I linked the question to the product, but the answer to the question didn't work at all
When using select choice = Choice.objects.filter(question_id = pk)
enter image description here
When using select choice = Choice.objects.all()
enter image description here
When using select choice = Choice.objects.filter(id = pk)
enter image description here
And you need 1.test1 to include: da, net, HY TAKOE
And 1.test2 included: 2,1,3
Thanks in advance to anyone who can suggest how to do this!!!

In my case it helped
views.py
class getqestion(generic.DetailView):
model = Items_buy
template_name = 'getqestion.html'
context_object_name = 'testing'
html
<div>
{% for testings in testing.question_set.all %}
<h1>{{testings.titles}}</h1>
<h3>{{testings.question_text}}</h3>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
{% csrf_token %}
<form action="{% url 'vote' testings.id%}" method="post">
{% for choice in testings.choice_set.all %}
<input type="checkbox" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
<label for="choice{{ forloop.counter }}">{{choice.title}}</label>
{% endfor %}
{% endfor %}
</div>
<input type="submit" value="vote">
</form>

Related

How to access a post author's profile picture in Django?

I am trying to display a username's profile picture in a blog/social media app when some user clicks on some other user's username but it is currently not working.
In my template: (I think my issue is I don't have access to post?)
{% extends "blog/base.html" %}
{% block content %}
<article class="media content-section">
<img class="img-thumbnail account-img mt-3 " src="{{ username.profile.image.url }}">
</article>
<h1 class="mb-3">Posts by {{ view.kwargs.username }} ({{ page_obj.paginator.count }})</h1>
<div class="infinite-container">
{% for post in posts %}
<div class="infinite-item">
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
<!-- profile (model in user ).image (attribute) -->
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a>
<small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
</div>
<h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2>
<p class="article-content">{{ post.content }}</p>
</div>
</article>
</div>
{% endfor %}
</div>
My users\models.py:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
def save(self, *args, **kwargs):
super(Profile, self).save(*args, **kwargs)
img = Image.open(self.image.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.image.path)
In my blog/models.py:
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
I can retrieve some user's username by {{ view.kwargs.username }}, how can I do this with profile pictures?
my blog\views.py:
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.models import User
from django.db.models import Q
from .models import Post #from the model file in the current package import the Post class
from django.views.generic import (
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView
)
def home(request):
context = {
'posts': Post.objects.all(), # querying the database
}
return render(request, 'blog/home.html', context)
class PostListView(ListView):
model = Post
template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 5
class UserPostListView(ListView):
model = Post
template_name = 'blog/user_posts.html' # <app>/<model>_<viewtype>.html
context_object_name = 'posts'
paginate_by = 5
def get_queryset(self):
# it will get that user form that database if it exist, if user doesn't exist return 404,
# we are also using the User model, so need to import it
# 2nd parameter means that we are getting the username from the url
user = get_object_or_404(User, username=self.kwargs.get('username'))
# showing the posts by that specific user only
return Post.objects.filter(author=user).order_by('-date_posted')
# Looking at individual post
class PostDetailView(DetailView):
model = Post
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
fields = ['title', 'content']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Post
fields = ['title', 'content']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Post
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
def about(request):
return render(request, 'blog/about.html', {'title': 'About'})
def search(request):
if request.method == "POST":
searched = request.POST['searched']
posts = Post.objects.filter(
Q(title__icontains=searched) |
Q(author__username__icontains=searched))
usernames = []
for post in posts:
usernames.append(post.author)
# remove duplicates of username
usernames = list(set(usernames))
context = {'searched': searched, 'posts': posts, 'usernames': usernames}
return render(request, 'blog/search.html', context)
else:
return render(request, 'blog/search.html', {})
Use ForeignKey instead of OneToOneField. Add a related_name:
class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="profile")
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
in html:
<img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
You can write a custom method also.
e.g:
class Post(models.Model):
...
author = models.ForeignKey(User, on_delete=models.CASCADE)
...
def get_owner_pp(self):
return self.author.profile.image.url
in html:
<img class="rounded-circle article-img" src="{{ post.get_owner_pp }}">

Display ManytoMany Django

trying to display all the ingredients that are associated to a recipe, however:
my models:
class IngredientList(models.Model):
name = models.CharField(max_length=100)
class RecipeList(models.Model):
name = models.CharField(max_length=100)
ingredients = models.ManyToManyField('IngredientList')
instructions = models.TextField(max_length=400)
amount = models.IntegerField()
my views:
from django.shortcuts import render
from .models import IngredientList, RecipeList
def index(request):
ing = RecipeList.objects.all()
context = {'ing': ing}
return render(request, 'myrecipes/home.html', context)
my template:
<div class="card-body">
<h4>{{ details.name}} <span class="badge badge-info">{{details.cuisine}}</span></h4>
<p class="card-text">Ingredients: {{details.ingredients}}</p>
<p class="card-text">Instructions: {{details.instructions}}</p>
<p class="card-text">This makes {{ details.amount}} meals</p>
</div>
my output is "myrecipes.IngredientList.None"
You need to access the queryset of the ingredients, so details.ingredients.all, furthermore you need to iterate over these ingredients, so you work with:
{% for ingredient in details.ingredients.all %}
{{ ingredient }}
{% endfor %}
In the view you can load all the related Ingredients with one extra query with:
def index(request):
ing = RecipeList.objects.prefetch_related('ingredients')
return render(request, 'myrecipes/home.html', {'ing': ing})
This will avoid making an extra query per RecipeList.

django-filter not filtering the query

I applied django-filter library in my project if it's not filtering the items.
if i visit the url http://127.0.0.1:8000/products/?q=&category=electronics it should gives the only electronics products but its giving the all available products. What i am doing wrong? it should filter categories wise or product title wiase and price wise.
class ProductFilter(FilterSet): # by using django-filters
title = CharFilter(field_name='title', lookup_expr='icontains', distinct=True)
category = CharFilter(field_name='categories__title', lookup_expr='icontains', distinct=True)
category_id = CharFilter(field_name='categories__id', lookup_expr='icontains', distinct=True)
min_price = NumberFilter(field_name='price', lookup_expr='gte', distinct=True)
max_price = NumberFilter(field_name='price', lookup_expr='lte', distinct=True)
class Meta:
model = Product
fields = ['category', 'title', 'description', 'min_price', 'max_price']
class FilterMixin(object):
filter_class = ProductFilter
search_ordering_param = 'ordering'
def get_queryset(self, *args, **kwargs):
try:
qs = super(FilterMixin, self).get_queryset(*args, **kwargs)
return qs
except:
raise ImproperlyConfigured("You must have a queryset in order to use the FilterMixin")
def get_context_data(self, *args, **kwargs):
context = super(FilterMixin, self).get_context_data(*args, **kwargs)
qs = self.get_queryset()
ordering = self.request.GET.get(self.search_ordering_param)
if ordering:
qs = qs.order_by(ordering)
filter_class = self.filter_class
print(filter_class)
if filter_class:
f = filter_class(self.request.GET, queryset=qs)
context['object_list'] = f
return context
class ProductListView(FilterMixin, ListView):
queryset = Product.objects.all()
filter_class = ProductFilter
def get_context_data(self, *args, **kwargs):
context = super(ProductListView, self).get_context_data(*args, **kwargs)
context['filter_form'] = ProductFilterForm(data=self.request.GET or None)
return context
Template File-
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% load static %}
{% block content %}
<div class='col-sm-2'>
<form method="GET" action="{% url 'products:product-list' %}">
{{ filter_form|crispy }}
<input type='hidden' name='q' value='{{ request.GET.q }}' />
<input type='submit' value='Apply Filter' class='btn btn-default'>
</form>
Clear Filters
</div>
<div class='col-sm-12'>
<h3>All Products <small>*Categories*</small></h3>
{% if product_list %}
<div class="row">
{% for product in product_list %}
<div class="col">
{% include 'products/snippets/card.html' with instance=product %}
</div>
{% endfor %}
{% else %}
<p>No product found!!</p>
{% endif %}
</div>
</div>
{% endblock %}
Your FilterMixin never exports something like a product_list, so that will be the original queryset, not the one that you filter with the FilterSet.
You can easily update this with:
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
qs = context['object_list']
if self.filter_class:
qs = self.filter_class(self.request.GET, queryset=qs).qs
ordering = self.request.GET.get(self.search_ordering_param)
if ordering:
qs = qs.order_by(ordering)
context['object_list'] = qs
context_object_name = self.get_context_object_name(qs)
if context_object_name is not None:
context[context_object_name] = qs
return context

Django: get user related field value in HTML to

I am trying to show the related field of the user on the webpage using Django.
I have models:
Models.py
class Companies(models.Model):
company_name = models.TextField()
company_email = models.EmailField()
company_owner = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.company_name
class Cars(models.Model):
company = models.ForeignKey('Companies', on_delete=models.CASCADE)
car_model = models.TextField()
views.py:
class UserCompanyCars(ListView):
model = Cars
template_name = 'home/company_cars.html'
context_object_name = 'cars'
slug_field ="username"
paginate_by = 100
def get_queryset(self):
company_n = get_object_or_404(Companies, company_owner=self.request.user)
return Cars.objects.filter(company=company_n)
and my html is:
{% extends 'home/base.html' %}
{% block content %}
<h1 class="mb-3"> Cars of {{user.Companies.company_name}}</h1>
{% for car in cars %}
<div class="media-body">
<div class = "article-metadata">
<p class="article-content">{{car.company}}</p>
{{car.car_model}}
<p class="article-content">{{car.car_carry }}</p>
</div>
</div>
{% endfor %}
{% endblock content %}
What I am trying to achieve is to write out "Cars of TestCompany (26)" on the webpage, but I cannot figure out how to get the Company_Name which is owned by the user. I have been trying all those Companies.objects... variations but none of them seem to work.
Try this (sample code taken from my project):
category = get_object_or_404(Category, pk=self.kwargs['pk'])
context['allcategories'] = MyPosts.objects.filter(category=category)
return context
This will filter all posts in the database based on certain categories. You can apply the same solution to your code.
If this solution does not work, please try to give more details about the problem.

Django Viewflow using class based views but getting error : Reverse for 'index' not found. 'index' is not a valid view function or pattern name

I am using class based views for my Django viewflow project. However I am getting the below error:
Reverse for 'index' not found. 'index' is not a valid view function or pattern name
Here are my classes:
rules/flows.py
class MyFlow(Flow):
"""
My App Flow
"""
process_class = models.MyProcess
start = flow.Start(
views.MyDetailView,
fields=["rule"],
task_title="New Task"
).Permission(
auto_create=True
).Next(this.end)
end = flow.End()
rules/urls.py
rule_urls = FlowViewSet(MyFlow).urls
urlpatterns = [
url(r'^rule/', include(rule_urls, namespace='rule')),
url(r'^(?P<pk>\d+)/mydetail/', MyDetailView.as_view(), {'flow_class': MyFlow, 'flow_task': MyFlow.start}, name='mydetail')
]
rules/models.py
class SubRules(models.Model):
rule_id = models.AutoField(primary_key=True)
src_id = models.IntegerField()
src_description = models.CharField(max_length=160, blank=True)
class Meta:
db_table = 'sub_rules'
class EntRules(models.Model):
rule = models.OneToOneField(SubRules, primary_key=True, on_delete=models.CASCADE)
entitlement_code = models.IntegerField()
rule_approved = models.SmallIntegerField()
rule_approved_datetime = models.DateTimeField(null=True)
class Meta:
db_table = 'ent_rules'
class MyProcess(Process):
entrule = models.ForeignKey(EntRules, blank=True, null=True, on_delete=models.CASCADE)
class Meta:
permissions = (
('approve_ent_rules','Can approve ent_rules')
)
rules/forms.py
class MyDetailForm(forms.ModelForm):
class Meta:
model = EntRules
fields = [
'rule',
'entitlement_code',
]
def __init__(self, *args, **kwargs):
pk = kwargs.pop('rule_id', None)
super(MyDetailForm, self).__init__(*args, **kwargs)
sub_rule = SubRules.objects.get(rule_id=pk)
self.fields['rule'].queryset = sub_rule.objects.filter(rule_id=pk)
rules/views/my_detail.py
class MyDetailView(StartFlowMixin, generic.UpdateView):
model = EntRules
template_name = 'rules/my_detail.html'
form_class = MyDetailForm
layout = Layout(
Fieldset('Rule Details',
Row('rule',),
Row('entitlement_code',),
)
)
def activation_done(self, form):
ent_rule = form.save()
self.activation.process.entrule = ent_rule
super(MyDetailView, self).activation_done(form)
def get_object(self):
return self.activation.process.entrule
def get_form_kwargs(self):
kwargs = super(MyDetailView, self).get_form_kwargs()
pk = int(self.kwargs['pk'])
kwargs['rule_id'] = pk
return kwargs
rules/templates/rules/my_detail.html
{% extends "base.html" %}
{% load material_form %}
{% block content %}
<form method="POST">
{% csrf_token %}
<div class="row">
{% form form=form %} {% endform %}
{{ activation.management_form }}
<div class="right">
<button type="submit" name="_start" class="btn">Submit</button>
</div>
</div>
</form>
{% endblock %}
Can you please advise what could be the issue here ?
I looked at Process Views outside viewflow.frontend
However how do I pass the sub_rule pk "^(?P\d+)" to startview as given in the URL like below ?
class MyFlow(Flow):
start = flow.Start(detail_view_class=MyDetailTaskView)
Please advise.
You can just pass a custom detail view as an argument for flow.Start http://docs.viewflow.io/viewflow_flow_nodes.html#viewflow.flow.StartFunction.detail_view

Resources