Is there a simple way to remove query set objects in my template just to print product name without the objects
what it prints
class SellerAccountMixin(object):
products = []
def get_products(self):
account = self.get_account()
products = Product.objects.filter(seller=account)
self.products = products
return products
class SellerDashboard(SellerAccountMixin,FormMixin, View):
def get(self, request, *args, **kwargs):
context["products"] = self.get_products()
return render(request, "sellers/dashboard.html", context)
template
{% if products %}
<div class='pull-left col-sidebar '>
{{ products }}
</div>
You should iterate over your products, like:
{% if products %}
<div class='pull-left col-sidebar '>
{% for product in products %}{{ product.name }} {% endfor %}
</div>
{% endif %}
.name might be a different field. It should be the one you aim to render.
Related
I want to get m2m data in my template through the views but failing to do so. The thing is that I'm able to show the data of m2m field looping it from template itself but it does slow down the website.
My Team apps Model looks like this:
class Team(models.Model):
title = models.CharField(max_length=255)
team_country = CountryField(max_length=200, blank=True, null=True)
members = models.ManyToManyField(User, related_name='teams')
created_by = models.ForeignKey(User, related_name='created_teams', on_delete=models.CASCADE)
Now in my tournament app I'm trying to get "members" of the team.
My Tournamet Views look like this:
def tournament_page(request, slug):
page = 'tournament_page'
user = request.user
tournament = Tournament.objects.get(slug=slug)
players = tournament.participants.select_related('user')
all_players = Profile.objects.select_related('user')
side_tourneys_ongoing = Tournament.objects.filter(state='Ongoing')[:10]
side_tourneys_upcoming = Tournament.objects.filter(state='Upcoming')[:10]
side_tourneys_completed = Tournament.objects.filter(state='Completed')[:10]
teams = Team.objects.select_related('created_by')
context = {
'page': page,
'tournament': tournament,
'side_tourneys_ongoing': side_tourneys_ongoing,
'side_tourneys_upcoming': side_tourneys_upcoming,
'side_tourneys_completed': side_tourneys_completed,
'teams': teams,
'players':players,
'all_players':all_players
}
Now I'm able to show the teams with their members in the template using for loop inside the template itself as:
Html template
<div class="grid-x">
{% for team in teams %}
{% for player in players %}
{% if team.id == player.active_team_id and team.game == tournament.game %}
<div class="wf-card event-team">
<div> {{team.title}} </div>
<div class="event-team-players">
{% for member in team.members.all %}
{{ member.username }}
{% endfor %}
</div>
</div>
{% endif %}
{% endfor %}
{% endfor %}
</div>
What I want is to use this piece of code
{% for member in team.members.all %}
{{ member.username }}
{% endfor %}
in my views since it causes the website to slow down and idk why.
What I tried in my views is:
all_teams = Team.objects.all()
members = all_teams.members.all()
and
members = Team.objects.all().prefetch_related('members')
First one throws an error:
'QuerySet' object has no attribute 'members'
Second one shows lots of blank records
Tried almost everything with search but none of them helped except using the code that I provided directly in the template itself.
Edited based on comments below. You should be able to do this more simply by prefetching team members.
views.py
def tournament_page(request, slug):
page = 'tournament_page'
user = request.user
tournament = Tournament.objects.get(slug=slug)
all_players = Profile.objects.select_related('user')
side_tourneys_ongoing = Tournament.objects.filter(state='Ongoing')[:10]
side_tourneys_upcoming = Tournament.objects.filter(state='Upcoming')[:10]
side_tourneys_completed = Tournament.objects.filter(state='Completed')[:10]
teams = Team.objects.select_related('created_by').prefetch_related('members')
template.html
<div class="grid-x">
{% for team in teams %}
{% if team.game == tournament.game %}
<div class="wf-card event-team">
<div> {{team.title}} </div>
<div class="event-team-players">
{% for member in team.members.all %}
{{ member.username }}
{% endfor %}
</div>
</div>
{% endif %}
{% endfor %}
</div>
I have been working on a search bar in django and I am close but having some issues rendering the results to the page.
Views.py
class SearchResultsView(ListView):
model = Project
template_name = 'search_results.html'
def get_queryset(self):
proj=self.request.GET.get('proj')
proj_list=Project.objects.filter(
Q(name__icontains=proj) | Q(projectTag__icontains=proj)
)
proj_list1=Project.objects.filter(
Q(department__icontains=proj)
)
proj_list2 = list(set(proj_list) & set(proj_list1))
return proj_list2
class SearchPageView(TemplateView):
template_name = 'searchbar.html'
search_results.html
{% extends 'main/base.html' %}
<html>
{%block content%}
<h1> Search Results </h1>
{% if proj %}
<ul>
{% for project in proj_list2%}
<li>
{{project.name}}, {{project.department}}, {{project.projectTag}}
</li>
{% endfor %}
</ul>
{% else %}
<h2>sorry, no results</h2>
{% endif %}
{%endblock%}
</html>
Whenever I search something that should definitely yield results, I get "sorry, no results."
Thank you. Please help me to understand my disconnect. The bigger aim for this is to then add different models to query from (i.e. not just search in projects, but also search by user).
You are checking the wrong variable. The collection of elements is object_list, not proj or proj_list2:
{% if object_list %}
<ul>
{% for project in object_list %}
<li>
{{project.name}}, {{project.department}}, {{project.projectTag}}
</li>
{% endfor %}
</ul>
{% else %}
<h2>sorry, no results</h2>
{% endif %}
The search is also quite odd, you only retrieve items if both the department and the name or the tag matches. We can simplify this to:
class SearchResultsView(ListView):
model = Project
template_name = 'search_results.html'
def get_queryset(self):
proj = self.request.GET.get('proj')
return =Project.objects.filter(
Q(name__icontains=proj) | Q(projectTag__icontains=proj),
department__icontains=proj
)
but it is odd that the department and the name for example should match. If you want to match any of the three, we can work with:
class SearchResultsView(ListView):
model = Project
template_name = 'search_results.html'
def get_queryset(self):
proj = self.request.GET.get('proj')
return =Project.objects.filter(
Q(name__icontains=proj) |
Q(projectTag__icontains=proj) |
Q(department__icontains=proj)
)
I want to auto-update my total amount field using quantity and item price? is there any way to do it using a flask without javascript? I want the total amount to be updated while typing quantity and item price.
class ItemForm(FlaskForm):
item = StringField('Item')
quantity=IntegerField('Quantity')
item_price=IntegerField('Item Price')
class Meta:
csrf = False
class CostumerForm(FlaskForm):
costumer_name=StringField('Costumer Name: ')
item_detail = FieldList(FormField(ItemForm), min_entries=1)
add_item = SubmitField(label='Add Item')
remove_item = SubmitField(label='Remove Item')
total_amount=IntegerField('Total Amount')
paid_amount=IntegerField('Paid Amount')
submit=SubmitField('Submit')
proceed=SubmitField('Proceed')
#app.route('/costumer',methods=['GET','POST'])
#login_required
def costumer():
form=CostumerForm()
if form.add_item.data:
form.item_detail.append_entry()
return render_template('costumer.html', form=form)
if form.remove_item.data:
form.item_detail.pop_entry()
return render_template('costumer.html', form=form)
if form.validate_on_submit():
item=breakdown(form.item_detail.data)[0]
quantity=breakdown(form.item_detail.data)[1]
item_price=breakdown(form.item_detail.data)[2]
amount=breakdown(form.item_detail.data)[3]
total_amount=breakdown(form.item_detail.data)[4]
remaning_amount=total_amount-form.paid_amount.data
sales=Costumer(admin_id=current_user.id,item_id=item,
costumer_name=form.costumer_name.data,quantity=quantity,
item_price=item_price,amount=amount,total_amount=total_amount,
paid_amount=form.paid_amount.data,remaning_amount=remaning_amount)
db.session.add(sales)
db.session.commit()
return redirect(url_for('salesvoucher'))
return render_template('costumer.html',form=form)
costumer.html
Sales
{{form.hidden_tag()}}
{{form.costumer_name.label}}{{form.costumer_name(class='form-control input-group-ig',placeholder='Costumer Name')}}
Item
Quantity
Item Price
{% for field in form.item_detail %}
{% for f in field%}
{{ f(class='form-control') }}
{% endfor %}
{% endfor %}
{{ form.add_item(class='btn btn-primary') }} {{ form.remove_item(class='btn btn-danger') }}
{{form.proceed(class='btn btn-primary')}}
```
no way. even when you're updating in only on the frontend, you must use javascript.
views.py.
#login_required
def friends_profile(request):
f_profiles = Profile.objects.get(user=request.user)
return render(request, 'mains/friends_profile.html', {'f_profiles':f_profiles} )
urls.py
path('friends_profile/', views.friends_profile, name='friends_profile'),
template = friends_profile.html
{% extends "mains/base.html" %}
{% block content %}
{% for friends in f_profiles %}
{{ friends.full_name }}
{% empty %}
<li>NO DATA</li>
{% endfor %}
{% endblock content %}
models.py
class Profile(models.Model):
user = models.OneToOneField(User,
on_delete=models.CASCADE,default='',unique=True)
full_name = models.CharField(max_length=100,default='')
friends = models.ManyToManyField(User, related_name='friends',blank=True)
email = models.EmailField(max_length=60,default='')
date_added = models.DateTimeField(auto_now_add=True)
def get_friends(self):
return self.friends.all()
def get_friends_no(self):
return self.friends.all().count()
def __str__(self):
return f'{self.user.username}'
STATUS_CHOICES = (
('send', 'send'),
('accepted','accepted'),
)
class Relationship(models.Model):
sender = models.ForeignKey(Profile, on_delete=models.CASCADE,
related_name='sender')
receiver = models.ForeignKey(Profile, on_delete=models.CASCADE,
related_name='receiver')
status = models.CharField(max_length=8, choices=STATUS_CHOICES)
def __str__(self):
return f"{self.sender}-{self.receiver}-{self.status}"
'Profile' object is not iterable. This is raising when i open this template( friends_profiles.html ). Please... Help me in this ERROR. What am i missing in this ?
I will really appreciate your HELP.
You are only passing a single object f_profiles in the context to the template, but are trying to iterate over an iterable by doing {% for friends in f_profiles %}.
f_profiles = Profile.objects.get(user=request.user) this will only give you one object which is the profile of the request.user. You are not getting friends of the user with this line of code.
Also, it maybe better to use
f_profiles = get_object_or_404(Profile, user=request.user)
Try to replace this code in the templates:
{% for friends in f_profiles %}
{{ friends.full_name }}
with
{% for friend in f_profiles.friends.all %}
{{ friend.full_name}}
or
{% for friend in f_profiles.get_friends %}
{{ friend.full_name }}
Here is my image model, that I tied to the model Product
class Image(models.Model):
name = models.CharField(blank=True,max_length=20)
product = models.ForeignKey(Product)
image = models.ImageField(blank=True,null=True)
def __str__(self):
return self.name
Here is the view that I am using to try and display the images
def category(request, category_id):
categories = Category.objects.all()
images = Image.objects.all()
products = Product.objects.all()
try:
category = Category.objects.get(id=category_id)
except Category.DoesNotExist:
category = None;
template = loader.get_template('index.html')
context = {
'category': category,
'categories': categories,
'images': images,
'products': products
}
return HttpResponse(template.render(context,request))
and here is the html
{% for image in images %}
<img src="{{ image.url }}">
{% endfor %}
I know this definitely wouldn't work,but atleast this code displays the page instead of an error so i have been using it, can anyone please point me in the right direction to dipslay each image associated with each product.
Thank you!
You can try this:
{% for product in products%}
<p> {{product.name}} </p>
{% for simage in product.image_set.all %}
{% if simage.image%}
<img src="{{ simage.image.url }}">
{% endif %}
{% endfor %}
{% endfor %}