I'm trying to use different stylesheet in django template if the time since publish is less than 7 days.
but Its not works.
please help me to make code works
model.py
class Post(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
overview = models.TextField()
created = models.DateTimeField(default=timezone.now)
updated = models.DateTimeField(auto_now=True))
class Meta:
ordering = ('-created',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail',kwargs={
'id':self.id
})
#property
def less_than_week(self):
if self.created.datetime.date + datetime.timedelta(days=7) <= datetime.date.today():
return False
else:
return True
template.html
{% if post.created.date.less_than_week %}
<h1>sample test</h1>
{% endif %}
Related
I have a following models.py for my Django blog, I made a following views.py to pass the value of the slug for my URL parameter.
However I am struggling to create a model in views to get other data(person & description) from Category class.
I have tried some patterns by myself but can not pass them to HTML. (always Error or not showing)
Can you please give me some idea of how to solve this.
models.py
class Category(models.Model):
person = models.CharField(max_length=20)
description = models.TextField()
slug = models.SlugField()
def __str__(self):
return self.person
views.py
def blog_category(request, category):
posts = Post.objects.filter(categories__slug__contains=category).order_by("-created_on").distinct()
context = {"category": category, "posts": posts}
return render(request, "blog_category.html", context)
HTML(Localhost:8000/slug)
{{ person }}
{{ description }}
this is full code of my models.py
class Category(models.Model):
person = models.CharField(max_length=20)
description = models.TextField()
slug = models.SlugField()
def __str__(self):
return self.person
class Recommender(models.Model):
recommender_name = models.CharField(max_length=20)
slug = models.SlugField()
def __str__(self):
return self.recommender_name
class Post(models.Model):
book_title = models.CharField(max_length=255)
author = models.CharField(max_length=255)
book_link = models.CharField(max_length=255)
recommenders = models.ForeignKey("Recommender", on_delete=models.CASCADE,)
source = models.TextField()
source_link = models.CharField(max_length=255)
created_on = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
categories = models.ManyToManyField("Category", related_name="posts")
slug = models.SlugField()
def __str__(self):
return self.book_title
posts = Post.objects.filter(categories__slug__contains=category).order_by("-created_on").distinct()
Is going to return a queryset. It can have more than one instance of the model class (since you are using filter). In your context you are sending this queryset as posts to your templates.
So in your HTML you can use something like this. You need to use a for loop since there can be more than one item in posts.
{% for post in posts %}
{% for category in post.categories.all %}
{{ category.person }}
{{ category.description }}
{% endfor %}
{% endfor %}
I would look at this example.
Namely, if you render the template like it is shown in the example, you should be able to do
{{ category.person }} {{ category.description }}
I am building a blog in django 3. I want to filter all posts by author and display the results in author page. I can't seem to figure what is wrong with my code. Please help. If i can get an explaination on what is wrong with my code, that will be appreciated.
Views.py
class AuthorPostListView(ListView):
model = Post
paginate_by = 5
template_name = 'author_post.html'
def get_queryset(self):
return Post.objects.filter(author = self.request.user).order_by('created_on').reverse()
def get_context_data(self):
context = super(AuthorPostListView, self).get_context_data(**kwargs)
context['authorpost_list'] = Post.objects.all()
return context
Models.py
class Post(models.Model):
title = models.CharField(max_length=200)
post_slug = models.SlugField(max_length = 200, unique = True)
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now = True)
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name = 'blog_posts',
)
post_picture = models.ImageField(
upload_to = 'post_picture',
null = True,
blank = True,
default='/media/post_picture/2.jpg',
)
approved_comment = models.BooleanField(default=True)
tags = TaggableManager()
categories = models.ManyToManyField('Category', related_name = 'posts')
def approve(self):
self.approved_comment = True
self.save()
class Meta:
ordering = ['created_on']
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post_detail', args=[str(self.id)])
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
Template
{% for object in authorpost_list %}
{{ object.title }}
{% endfor %}
urls.py
urlpatterns = [
path('author_post/', views.AuthorPostListView.as_view(), name = 'author_posts'),
]
you are over-riding the actual view you wanted with get context data, so you can remove the get context method and call in the template as
{% for object in object_list %}
{{ object.title }}
{% endfor %}
or you can do
context['authorpost_list'] = Post.objects.filter(author = self.request.user).order_by('-created_on')
and call in template in the same way as you shown
am working on a Django project where showing the details of post and amount
here is my models.py of post
class Loader_post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE ,related_name="Loader")
pick_up_station = models.CharField(max_length=150)
destination_station = models.CharField(max_length=150)
sender_name = models.CharField(max_length=150)
phone_number = PhoneNumberField(null=False, blank=False, unique=True)
receiver_name = models.CharField(max_length=150)
def __str__(self):
return self.user.username
def get_absolute_url(self):
return reverse("Loader:my_job", kwargs={"pk": self.pk})
this is my second models which I inherit Loader post
class price(models.Model):
my_post = models.ForeignKey(Loader_post, related_name='prices',on_delete=models.CASCADE,
null=True, default='')
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True, default='')
driver_price = models.CharField(max_length=150, null=True)
driver_name = models.CharField(max_length=150, null=True)
approved_price = models.BooleanField(default=False)
status = models.BooleanField(default=False)
def get_absolute_url(self):
return reverse("Driver:Driverview")
def __str__(self):
return self.driver_price
this is the view.py of both list and details view
class offer_view(ListView, SelectRelatedMixin):
context_object_name = 'offern'
model = Loader_post
template_name = "offer.html"
def get_queryset(self):
qs = Loader_post.objects.filter(user=self.request.user)
return qs
class offer_view_detail(DetailView):
context_object_name = 'offernew'
model = Loader_post
template_name = "offer_detail.html"
here is my HTML page of list view ...when someone clicks on it it shows the detail of next post
offer.html
{% for my in offern %}
{{my.sender_name}} {% endfor %}
and when someone clicks on its route to the detail page .. but it shows template doesn't exist
this is my detail page ie. offer_details.hml
<p>{{offernew.sender_name}}</p>
<p>{{offernew.receiver_name}}</p>
{% for x in offernew.prices.all %}
<p>
<p>{{x.driver_name}}</p>
</p>
and this is urls.py
path('offerdetail/<int:pk>', views.offer_view_detail.as_view(),name="offerdetail"),
path('offer/', views.offer_view.as_view(), name="offer"),
Following on from comments,
In you ListView,
{{my.sender_name}}
here, the url specified is not defined in your urls.py, that's why it was showing no template doesn't exist, changing to this would solve this.
{{my.sender_name}}
Now, To show prices model in your DetailView, i would do something like this.
class offer_view_detail(DetailView):
context_object_name='offernew'
model = Loader_post
template_name = "offer_detail.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['price_model'] = self.object.prices.all()
return context
and In your Template
<p>{{offernew.sender_name}}</p>
<p>{{offernew.receiver_name}}</p>
{% for x in offernew.price_model %}
<p>{{x.driver_name}}</p>
{% endfor %}
Django Docs for DetailView
Have a quick question. Trying to use a relational model in one DetailView. However, no matter what I try the data does not display. I've tried a few versions of template tags to no avail.
html
{% for parts in relatedparts %}{{ parts.name }}
</div>{% endfor %}
views.py
class ErrorCodeView(DetailView):
context_object_name = 'error_code_details'
model = models.ErrorCodes
template_name = 'error_code_details.html'
def get_context_data(self, **kwargs):
# xxx will be available in the template as the related objects
context = super(ErrorCodeView, self).get_context_data(**kwargs)
context['relatedparts'] = RelatedParts.objects.filter(name=self.get_object())
return context
models.py
class ErrorCodes(models.Model):
name = models.CharField(max_length=256)
description = models.CharField(max_length=400)
instructions = models.CharField(max_length=256)
PartsNeeded = models.CharField(max_length=120, default='')
usercomments = models.CharField(max_length=400, default='', blank=True)
relpic = models.ImageField(upload_to='media/',blank=True)
relpictwo = models.ImageField(upload_to='media/',blank=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("errorcodes:errorcodeview",kwargs={'name':self.name})
class RelatedParts(models.Model):
name = models.CharField(max_length=256)
related_error_code = models.ForeignKey(ErrorCodes, on_delete=models.PROTECT)
def __str__(self):
return self.name
You don't need to do this at all. You can follow the relationship in the template.
{% for part in object.relatedparts_set.all %}{{ part.name }}{% endfor %}
You don't need any code in the view to enable this.
could it be that "name=self.get_object()" should be "name=self.get_object().name" ?
You currently have:
context['relatedparts'] = RelatedParts.objects.filter(name=self.get_object())
but that is probably producing an empty queryset.
How can I display the list of users with the count of total number of posts made by them in a separate HTML page ?
models.py
class Post(models.Model):
author = models.ForeignKey(User.request, on_delete = models.CASCADE)
title = models.CharField(max_length=100)
text = models.TextField()
slug = models.SlugField(unique=True, blank=True, default=uuid.uuid1)
created_date = models.DateTimeField(default=timezone.now)
likes = models.ManyToManyField(User, related_name='post_likes', blank = True)
def get_like_url(self):
return reverse("posts:like-toggle", kwargs={"slug": self.slug})
def get_api_like_url(self):
return reverse("posts:like-api-toggle", kwargs={"slug": self.slug})
def get_absolute_url(self):
return reverse("post_detail",kwargs={'pk':self.pk})
def __str__(self):
return self.title
def count_posts_of(user):
return Post.objects.filter(author=user).count()
You have to learn MVC architecture(MVT in django).
As a beginner first create a sample project to understand this - https://docs.djangoproject.com/en/2.0/intro/tutorial01/
Learn how models.py are written - https://docs.djangoproject.com/en/2.0/topics/db/models/
and how to writeviews.py - https://docs.djangoproject.com/en/2.0/topics/class-based-views/
Then connect them in urls.py - https://docs.djangoproject.com/en/2.0/topics/http/urls/
This is my solution at the moment, but it could be done differently.
First, add count_posts_of method to your User model whatever it is.
For instance I myself created a user model and add this method to it as following:
models.py
class User(models.Model):
name = models.CharField(max_length=100, blank=True, null=True)
#property
def count_posts_of(self):
return self.post_set.all().count()
now in the view pass all the users as context:
views.py
def user_post(request):
context = {'users': User.objects.all()}
return render(request, 'future/user_post_view.html', context)
and finally in the template show the user and their posts' count:
user_post_view.html
{% for user in users %}
{{ user.name }} :
{{ user.count_posts_of }},
{% endfor %}