I need to print the list of persons whose birthdays are today.
I do not know the correct way to introduce the current data variable in the if loop.
personal_list.html
{% for personal in personals %}
{% ifequal personal.data_nastere|date:"d/m" '??/??' %}
<ul>
<li><a class="titleOmagiat" href="{% url 'personalomagiat_detail' pk=personal.pk %}">
{{ personal.name }} {{ personal.surname }} </a>, {{ personal.birth_day|date:"d/m/Y" }}
</li>
</ul>
{% endifequal %}
{% endfor %}
models.py
class Personal(models.Model):
name = models.CharField(max_length=20)
surname = models.CharField(max_length=20)
birth_day = models.DateField(blank=True, null=True)
class Meta:
ordering = ['name']
def __str__(self):
return '%s %s' % (self.name, self.surname)
views.py
def personal_list(request):
personals = Personal.objects.order_by('name')
return render(request, 'blog/personal_list.html', {'personals': personals})
urls.py
urlpatterns = [
url(r'^personal/$', views.personal_list, name='personal_list'),
]
Tell me the correct answer in code.
The filtering must be done at the database level, not in the template, otherwise you are reading data from disk that you are not using which results in poor performances.
Update your view this way:
from django.utils import timezone
def personal_list(request):
today = timezone.now().date()
personals = Personal.objects.order_by('name').filter(
birth_day__month=today.month,
birth_day__day=today.day)
return render(request, 'blog/personal_list.html', {'personals': personals})
And your template this way:
<ul>
{% for personal in personals %}
<li><a class="titleOmagiat" href="{% url 'personalomagiat_detail' pk=personal.pk %}">
{{ personal.name }} {{ personal.surname }} </a>, {{ personal.birth_day|date:"d/m/Y" }}
</li>
{% endfor %}
</ul>
Related
I'm stuck on a problem. I need to filter all of the listings using the list.id in the for loop. Unfortunately, the filter function in Django could not be parsed. Is there another solution or is there a way to work around it? How can you run a function in Django HTML template. Thanks!
index.html
{% extends "auctions/layout.html" %}
{% block body %}
<h2>Active Listings</h2>
{% if not listing %}
<h3>Nothing listed...</h3>
{% endif %}
{% for list in listing %}
<h3>Listing: {{ list.title }}</h3>
{% if list.photo != "" %}
<img src="{{ list.photo }}">
{% endif %}
<p>{{ list.description }}</p>
{% if not bids.filter(listing=list.id) %} #This line could not be parsed
<h5>${{ list.price }}</h5>
{% else %}
<h5>${{ bids.filter(listing=list.id).order_by(-bids).first().bids }}</h5> #This line could not be parsed
{% endif %}
<p>
{% if not bids.filter(listing=list.id).count() %} #This line could not be parsed
0
{% else %}
{{ bids.filter(listing=list.id).count() }} #This line could not be parsed
{% endif %}
bid(s) so far.
{% if bids.filter(listing=list.id).order_by(-bids).first().bidder == user.username %} #This line could not be parsed
Your bid is the current bid.
{% elif not bids.filter(listing=list.id).order_by(-bids).first().bidder %} #This line could not be parsed
There is no bid.
{% elif bids.filter(listing=list.id).order_by(-bids).first().bidder != user.username %} #This line could not be parsed
{{ bids.filter(listing=list.id).order_by(-bids).first().bidder }} is the current bid. #This line could not be parsed
{% endif %}
</p>
{% if user.username != list.user and user.is_authenticated %}
<form action="{% url "index" %} method="post">
{% for form in forms %}
{{ form }}
<input type="submit" value="Bid">
</form>
{% endfor %%}
{% endif %}
<h4>Details</h4>
<ul>
{% if user.username == list.user %}
<li>Listed by: You</li>
{% else %}
<li>Listed by: {{ list.user }}</li>
{% endif %}
<li>Category: {{ list.category }}</li>
</ul>
<hr>
{% endfor %}
{% endblock %}
views.py
from .models import User, AuctionList, Bids, Comments
from .forms import AuctionForm, BidsForm
def index(request):
if request.method == "POST":
pass
else:
AL = AuctionList.objects.all()
Bd = Bids.objects.all()
forms = BidsForm()
return render(request, "auctions/index.html", {
"listing": AL.order_by("id"),
"bids": Bd,
"forms": forms
})
models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
pass
class AuctionList(models.Model):
CATEGORY_CHOICES = [
('Books', 'Books'),
('Business & Industrial', 'Business & Industrial'),
('Clothing, Shoes & Accessories', 'Clothing, Shoes & Accessories'),
('Collectibles', 'Collectibles'),
('Consumer Electronics', 'Consumer Electronics'),
('Crafts', 'Crafts'),
('Dolls & Bears', 'Dolls & Bears'),
('Home & Garden', 'Home & Garden'),
('Motors', 'Motors'),
('Pet Supplies', 'Pet Supplies'),
('Sporting Goods', 'Sporting Goods'),
('Sports Mem, Cards & Fan Shop', 'Sports Mem, Cards & Fan Shop'),
('Toys & Hobbies', 'Toys & Hobbies'),
('Antiques', 'Antiques'),
('Computers/Tablets & Networking', 'Computers/Tablets & Networking')
]
id = models.AutoField(primary_key=True)
user = models.CharField(max_length=20, default='None')
title = models.CharField(max_length=20)
category = models.CharField(
max_length=30, choices=CATEGORY_CHOICES, default='Books')
description = models.TextField()
price = models.FloatField()
photo = models.URLField(max_length=200, blank=True)
def __str__(self):
return f"({self.id}) | Title: {self.title} | Category: {self.category} | Price: {self.price} | Posted by: {self.user}"
class Bids(models.Model):
bidder = models.CharField(max_length=20, default='None')
listing = models.ForeignKey(
AuctionList, on_delete=models.CASCADE, related_name="bids")
bids = models.FloatField()
def __str__(self):
return f"Listing Key: {self.listing} | Bids: {self.bids}"
You can create another function in your views.py and pass it in your index function (example below to give you some idea in views.py & index.html)
def build_auctions_layout(username):
final_html = None
for list in listing:
final_html = '<h3>Listing: {}</h3>'.format(list.title)
if list.photo:
final_html += '<img src="{}"'.format(list.photo)
final_html += '<p>{}</p>'.format(list.description)
if not list.bids: #This line could not be parsed
final_html += '<h5>${}</h5>'.format(list.price)
else:
final_html += '<h5>${}</h5>'.format(list.bids.order_by(-bids).first().bids ) #This line could not be parsed
final_html += '<p>{} bid(s) so far'.format(list.bids.count())
if list.bids.order_by(-bids).first().bidder == username:
final_html += 'Your bid is the current bid.</p>'
else:
final_html += 'There is no bid.</p>'
return final_html
def index(request):
if request.method == "POST":
pass
else:
AL = AuctionList.objects.all()
Bd = Bids.objects.all()
forms = BidsForm()
return render(request, "auctions/index.html", {
"listing": AL.order_by("id"),
"bids": Bd,
"forms": forms,
"auctions_layout": build_auctions_layout(request.user.username)
})
#auctions/index.html
{% extends "auctions/layout.html" %}
{% block body %}
<h2>Active Listings</h2>
{% if not listing %}
<h3>Nothing listed...</h3>
{% endif %}
{{auctions_layout|safe}}
......
The answer is yes you can run filter function inside your html template. Infact filter functions are meant for and frequently used everywhere in django templates which you can find in django more precisely as Custom template filters
You can also create one filter function as per your requirement and use it anywhere inside your template which is known as Django Templatetags. These template tags are nothing but a sort of functions which you define yourself and implement in templates.Here I explain you step by step:
For referene, my project name is "working_blog_python" and app name is "branch"
1. open your terminal and type
(working_blog_python) $ cd branch
(working_blog_python) $ mkdir templatetags
(working_blog_python) $ touch templatetags/any_name_tags.py
2.Now inside your
any_name_tags.py
you can write your filter function like this
from django import template
register = template.Library()
#register.filter_function
def hrs(self):
return self.name.replace('-', ' ')
3.Now you can use this hrs() function anywhere in your templates, but don't forget to load {% load name_tags %} name_tag inside your template.
<p>Shop is located in {{branch.state | hrs | title}}.</p>
How can I access fields other than the grouper in a Django group_by function?
class dateEvent(models.Model):
event = models.ForeignKey('Event', on_delete=models.CASCADE)
start_date_time = models.DateTimeField(auto_now=False, auto_now_add=False)
def __str__(self):
return "%s" % (self.event.title)
def description(self):
return "%s" % (self.event.description)
class Event(models.Model):
description = RichTextUploadingField(max_length=200)
view:
def my_view(request):
events = dateEvent.objects.all()
context = {
'events': events,
}
return render(request, 'view.html', context)
template:
<ul>
{% for event in dateEvents_list %}
<li><h5>Event: {{ event.grouper }}</h5>
<h6>Description: {{ event.description }}</h6> #How can access the description of the main event?
<ul>
{% for dateEvent in event.list %}
<li>date: {{ dateEvent.start_date_time }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
I'd like to have the title, which is the grouper so it's fine, but also the description.
You can also access your grouper's list objects to get details about the "first record" in your group. So using:
event.grouper.list.0.<any_model_field_you_want>
Will work just fine. I have this in production and it solved my needs immediatly. I found this in a rejected feature request for Django here: https://code.djangoproject.com/ticket/13452
If you need to traverse your model's relationship tree you can do the following.
event.grouper.list.0.<related_model_name>.<any_model_field_you_want>
You can access model attributes from the grouper directly using event.grouper.<any-model-attribute>.
In your example here is how it would look:
<ul>
{% for event in dateEvents_list %}
<li><h5>Event: {{ event.grouper }}</h5>
<h6>Description: {{ event.grouper.description }}</h6>
<ul>
{% for dateEvent in event.list %}
<li>date: {{ dateEvent.start_date_time }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
I can't find any documentation around this usage.
am new to Django and am trying to create a blog site where users can sign up and post articles, but my problem is how can I display a user's post on the user's profile page so that when other users reading the post clicks on the author's name it takes them to the post.author's profile page with the post.author's recent post listed and not the request.user's post. here is my code.
here is accounts/views.py
views.py
#login_required()
def user_profile_view(request, username):
post = User.objects.filter(courses__author=username)
context = {'courses': courses}
return render(request, 'accounts/user_profile_view.html', context)
and here is post/models.py
models.py
class Posts(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
cover = ProcessedImageField(upload_to='post_featured_image',
processors=[ResizeToFill(600, 300)],
format='png',
options={'quality': 80},
blank=True)
slug = models.SlugField()
title = models.CharField(max_length=200)
body = models.TextField()
summary = models.TextField(max_length=200)
here is the template
post_list.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="col-lg-6">
{% for course in courses_list %}
<div class="central-meta item">
<div class="user-post">
<div class="friend-info">
{% if post.author.profile.avatar %}
<figure>
<img src="{{ post.author.profile.avatar.url }}" alt="">
</figure>
{% else %}
<img src="{% static 'default.ico' %}" alt="">
{% endif %}
<div class="friend-name">
<ins>{{ course.author.get_full_name|title }}</ins>
<span>published: {{ post.published }}</span>
</div>
<div class="post-meta">
{% if course.cover %}
<img src="{{ post.cover.url }}" alt="">
{% endif %}
<div class="friend-name">
<ins>{{ course.title|title }}</ins>
</div>
<div class="description">
<p><span>{{ post.summary|capfirst }}</span></p>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock content %}
here is my accounts/urls.py
urls.py
app_name = 'accounts'
urlpatterns = [
path('accounts/profile/<str:username>/', user_profile_view, name='user_profile'),
]
you should be able do that, easy and via lots of ways.
make a post model like this:
class Post(models.Model):
author = foreign_key(User, related_name="posts", on_delete=models.CASCADE)
title = char_field()
content ........
so with that related name you will be able to reverse from user to its posts too!.
in your template do this:
{{ post.author }}
this link will redirect user to the posts author dashboard if you arrange the urls pattern correctly.
then for sorting authors posts, you have to pass the dashboard_owner to the template and use this name instead of user which normally will refer to the request.user -> user who are visiting the page
{% for post in dash_owner.posts.all %}
<li> <a href="{{ post.get_abslute_url }}" target="_blink">
{{ post.title }} </a> </li>
{% endfor %}
in views.py
def dashboard(request, owner_id=None)
if owner_id:
dash_owner = get_or_404(User, id=owner_id)
elif request.user.is_authenticated:
dash_owner = User.objectd.get(id=request.user.id)
return render(request, 'dashboard.html', {'dash_owner': dash_owner})
in urls.py -> urlpatterns:
path('dashboard/<int:owner_id>/', views.dashboard, name="dashboard")
this is the idea behind that, but for get the better result, you may need to clearly define the get_absolute_url of User model, to give you the url which machts to
'dashboard/<int:id/'
or another way is instead of that, do this:
{{ post.author }}
I am trying to follow this previous question here:
Django: getting the list of related records for a list of objects
but can't seem to get it to work.
I get a list of owners but do not get a list of pet names. The html code doesn't seem to execute the 2nd FOR loop. Any ideas?
models.py
class Teacher(models.Model):
teacher = models.CharField(max_length=300, verbose_name="teacher")
def __unicode__(self):
return self.teacher
class Owner(models.Model):
relevantteacher = models.ForeignKey(Teacher, verbose_name="teacher")
owner = models.CharField(max_length=300, verbose_name="owner")
def __unicode__(self):
return self.owner
class PetName(models.Model):
relevantowner = models.ForeignKey(Owner, verbose_name="owner")
pet_name = models.CharField(max_length=50, verbose_name="pet Name")
def __unicode__(self):
return self.pet_name
views.py
def ownersandteachers(request):
owners = Owner.objects.all()
context = {'owners': owners}
return render(request, 'ownersandpets.html', context)
template
{% for i in owners %}
{{ i.owner }} has pets:<br />
{% for v in owners.petname_set.all %} //this doesn't seem to be executing
- {{ v.pet_name }}<br />
{% endfor %}
{% endfor %}
You are doing
{% for v in owners.petname_set.all %}
where you should be doing
{% for v in i.petname_set.all %}
owners is the queryset, but you need to get the petname_set for the individual object in the queryset which is i in this case.
Also, I would recommend a condition check if i.petname_set exists. If not, do not show the has pets: text.
{% for i in owners %}
{{ i.owner }}
{% if i.petname_set.count %} has pets:<br />
{% for v in i.petname_set.all %} //this doesn't seem to be executing
- {{ v.pet_name }}<br />
{% endfor %}
{% endif %}
{% endfor %}
I'm having some trouble using get_absolute_url in a template. It seems to work fine if I just pass in one of my store objects and say {{ store.get_absolute_url }}, but if I have to iterate through a dictionary of stores and then use the get_absolute_url function, it returns nothing. Exactly what I'm doing is below:
class Store(EthicalObject):
type = "Store"
name = models.CharField(max_length=50)
company = models.ForeignKey(Company, verbose_name="Company", null=True, blank=True)
location = models.OneToOneField(Location, verbose_name="Location", null=True, blank=True)
products = models.ManyToManyField('Product', related_name="%(class)s_related", db_table=u'ethicsdb_products_to_stores', blank=True)
companies = models.ManyToManyField('Company', related_name="%(class)s_related", db_table=u'ethicsdb_companies_to_stores', blank=True)
def get_absolute_url(self):
return ('store_details', [str(self.id)])
get_absolute_url = models.permalink(get_absolute_url)
This works:
views.py:
def fetch_sidebar_data(shop_object):
sidebar_modules = {}
if shop_object.content_type.name == 'company':
sidebar_modules['related_stores'] = shop_object.stores.all()
sidebar_modules['related_products'] = shop_object.products.all()
if shop_object.content_type.name == 'store':
sidebar_modules['related_companies'] = shop_object.companies.all()
sidebar_modules['related_products'] = shop_object.products.all()
if shop_object.content_type.name == 'product':
sidebar_modules['related_stores'] = shop_object.stores.all()
sidebar_modules['related_companies'] = shop_object.companies.all()
sidebar_modules['tags'] = shop_object.tags
return sidebar_modules['related_stores'][1]
def company_details(request, company_id):
company = get_object_or_404(Company, id=company_id)
sidebar_modules = fetch_sidebar_data(company)
return render_to_response('company/details.html', {'company': company, 'sidebar_modules': sidebar_modules}, context_instance=RequestContext(request))
template:
{% extends "base-onecol.html" %}
{% block page_div_extra_attr %}class="twocol"{% endblock %}
{% block sidebar_content %}
<div id="sidebar-right">
<h1>{{ sidebar_modules.name }}{{sidebar_modules.get_absolute_url }}</h1>
</div>
{% endblock %}
This doesn't work:
views.py:
def fetch_sidebar_data(shop_object):
sidebar_modules = {}
if shop_object.content_type.name == 'company':
sidebar_modules['related_stores'] = shop_object.stores.all()
sidebar_modules['related_products'] = shop_object.products.all()
if shop_object.content_type.name == 'store':
sidebar_modules['related_companies'] = shop_object.companies.all()
sidebar_modules['related_products'] = shop_object.products.all()
if shop_object.content_type.name == 'product':
sidebar_modules['related_stores'] = shop_object.stores.all()
sidebar_modules['related_companies'] = shop_object.companies.all()
sidebar_modules['tags'] = shop_object.tags
return sidebar_modules
template:
{% extends "base-onecol.html" %}
{% block page_div_extra_attr %}class="twocol"{% endblock %}
{% block sidebar_content %}
<div id="sidebar-right">
{% for module_name,module in sidebar_modules.items %}
{% ifequal module_name "related_stores" %}
<h3>Sold Here</h3>
{% for related_store in module.values %}
{{ related_store.name }}<br/>
{% endfor %}
{% endifequal %}
{% ifequal module_name "related_products" %}
<h3>Buy Local</h3>
{{ module }}<br/>
{% endifequal %}
{% ifequal module_name "related_companies" %}
<h3>
{{ module }}<br/>
{% endifequal %}
{% ifequal module_name "tags" %}
{{ module }}<br/>
{% endifequal %}
{% endfor %}
</div>
{% endblock %}
In the second one, I just get no return from get_absolute_url. I know it's working in other places when I print it out. Is this a Django bug, the inability to use get_absolute_url in a dictionary of dictionaries?
Wow, that was a rather convoluted question.
Your problem is here: {% for related_store in module.values %}
module is a QuerySet. .values is calling the QuerySet method which returns a dictionary containing the field values for each row. A dictionary has no get_absolute_url attribute, and get_absolute_url isn't a field in the model.
Just use {% for related_store in module %} and you'll be dealing with actual model instances rather than dictionaries, which means {{ related_store.get_absolute_url }} will work fine.