#StackBounty: #python #django Including an Item Context to a Post Model to activate if statement in Django

Bounty: 50

I am trying to add an Item to a list view, the UserPost list view has already a Post context.

In my project, a user can add a post and add an item each is a different app with different models.

So In my UserPost list view, I have my Posts looped related to a specific user related to it.

What I am trying to do is check if this post.user has an item filtered by the same user and if it does exist a button show appears in the page linking to another page with this list of items related to this user.
To be more descriptive I want to check for Item for the designer__post and link to this page which is {% url 'core:designer-posts' item.designer %}

I hope this clears my question if there are any more clarifications required or code please let me know to add it.

I tried to use make use of an Exists subquery [Django-doc] but I didn’t succeed it perfecting it

Here is the models.py

class Post(models.Model):
    designer = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)

Here is the views.py

class UserPostListView(ListView):
    model = Post
    template_name = "user_posts.html"
    context_object_name = 'posts'
    queryset = Post.objects.filter(admin_approved=True)
    paginate_by = 6

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Post.objects.filter(designer=user, admin_approved=True).order_by('-date_posted')

Here is the template user_posts.html

{% if item %}
 <a class="primary btn-lg" href="{% url 'core:designer-posts' item.designer %}" role="button">Go to items</a>
{% else %}
  <a href="{% url 'core:designer-posts' item.designer %}">
    <button type="button" class="btn btn-primary btn-lg btn-block">Go to items</button>
  </a>   
{% endif %}

here is the item models.py

class Item(models.Model):
    designer = models.ForeignKey(
        User, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)

here is the designerlist views.py that I am trying to link to from the user post view if it is available

class DesignerPostListView(ListView):
    model = Item
    template_name = "designer_posts.html"
    context_object_name = 'items'
    paginate_by = 6

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Item.objects.filter(designer=user).order_by('-timestamp')

enter image description here


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.