Disply the list of users with total posts - python

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 %}

Related

How to pass multiple values from models.py to HTML via views.py in Django

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 }}

Django: the detail page is not showing(template error)

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

How to compare DateTime in django template in Oneweek

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 %}

Two models in one Django DetailView and filtering by relation betwen them

I have a question. In my DetailView I want to placed data from two models. Moreover, I want to filter them, that on my scenario-detail was only that comments related to specyfic scenario, related by ForeignKey->Scenario.
My views.py:
class ScenarioDetailView(LoginRequiredMixin, DetailView):
model = Scenario
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['comments'] = Comment.objects.all()
return context
And in scenario_detail.html i have a simple {{ comments }}
I thinking on filtering my comment object in views.py, something like: Comment.objects.get(commentScenario=Scenario.id) but it didn't work at all.
My models.py:
class Scenario(models.Model):
scenarioTitle = models.CharField(max_length=256)
scenarioArea = models.ForeignKey(ScenarioArea, on_delete=models.CASCADE)
scenarioAuthor = models.ForeignKey(User, on_delete=models.CASCADE)
scenarioDate = models.DateTimeField(default=timezone.now)
scenarioDescription = models.TextField()
def __str__(self):
return self.scenarioTitle
def get_absolute_url(self):
return reverse('scenario-detail', kwargs={'pk': self.pk})
class Comment(models.Model):
commentText = models.CharField(max_length=256)
commentScenario = models.ForeignKey(Scenario, on_delete=models.CASCADE)
commentAuthor = models.ForeignKey(User, on_delete=models.CASCADE)
commentDate = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.commentText
And urls.py:
path('scenario/<int:pk>/', ScenarioDetailView.as_view(), name='scenario-detail'),
Could someone help me?
You don't need to send any extra context to your template in order to show the related comments; As you already have the related comments to your Scenario with backward relationship.
So you can simply use Scenario.comment_set.all in your template to access them.
As an example:
{% for comment in object.comment_set.all %}
{{ comment }}
{% endfor %}
try this
class ScenarioDetailView(LoginRequiredMixin, DetailView):
model = Scenario
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['comments'] = Comment.objects.filter(commentScenario=self.object)
return context

Django view with get context not working

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.

Categories

Resources