0

My question is two phased but it's from the same Django Model. I am trying to get my Category model to work properly with my Petition model. Currently,

I get this 'FieldError' error when I define a queryset for my 'CategoryView' class:

Cannot resolve keyword 'created_on' into field. Choices are: description, id, petition, slug, title

Here is the code for the 'CategoryView' class:

class CategoryView(generic.ListView):
    model = Category
    template_name = 'petition/category.html'
    context_object_name = 'category_list'

    def get_queryset(self):
        return Category.objects.order_by('-created_on')[:10]

Here is the code in my models.py:

class Category(models.Model):
    title = models.CharField(max_length=90, default="Select an appropriate category")
    slug = models.SlugField(max_length=200, unique=True)
    description = models.TextField(null=False, blank=False)

    class Meta:
        verbose_name_plural = "Categories"

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return "/categories/%s/"%self.slug

class Petition(models.Model):
    title = models.CharField(max_length= 90, default="Enter petition title here")
    created_on = models.DateTimeField(auto_now_add=True)
    image = models.ImageField(null=False, upload_to=imageupload)
    video = models.CharField(max_length=600, default="Enter an external video link")
    petition = models.TextField(null=False, default="Type your petition here")
    created_by = models.ForeignKey(User)
    category = models.ManyToManyField(Category)

    def total_likes(self):
        return self.like_set.count()

    def __str__(self):
        return self.title[:50]

    def get_signatures(self):
        return self.signature_set.all()

I get the 'FieldError' on my category view template (category.html) when the 'get_queryset()' has been defined.

When I comment it out, the page displays but posts are not retrieved; I get a list of the categories instead. Here is my category view template(category.html):

{% include 'layout/header.html' %}
{% load humanize %}

    <div class="container content">
    <div class="row">
    <div class="col-md-8 post-area">
    {% if category_list %}
{% for petition in category_list %}
<div class="petition-block">
<h2 class="home-title"><a href="{% url 'detail' pk=petition.id %}">{{petition.title}}</a></h2>
<span class="petition-meta">
Created {{petition.created_on|naturaltime}} by 
{% if petition.created_by == user %}
You 
{% else %}
@{{ petition.created_by }}
{% endif %} 
    {% if petition.created_by == user %}
    <a href="{% url 'editpetition' pk=petition.id %}">Edit</a>
    {% endif %}
    {% if petition.created_by == user %}
    <a href="{% url 'deletepetition' pk=petition.id %}">Delete</a>
    {% endif %}
</span>

    {% if petition.image %}
        <img src="{{ petition.image.url }}" alt="petition image" class="img-responsive" />
    {% endif %}

</div><!--//petition-block-->
{% endfor %}

{% else %}

    <p>Sorry, there are no posts in the database</p>

{% endif %}
</div>


<div class="col-md-4">
<h3>Topics</h3>
<ul>
    {% for petition in category_list %}
    <li><a href="#">{{petition.title}}</a></li>
    {% endfor %}
</ul>
</div>

</body>
</html>

What am I doing wrong? Please help.

1 Answer 1

0

That's because you are trying to order the Category's queryset by created_on and your Category model doesn't have any field called created_on. That field is within Petition model. If you want to order the categories by petition's created_on you should do a "join" between tables, but with Django's ORM is easy.

For simplicity on your code is better to name the relation

class Petition(models.Model):
    ...
    categories = models.ManyToManyField(Category, related_name='petitions')
    ...

Now you can refer to the category's petitions as 'petitions'

Category.objects.order_by('-petitions__created_on')

For use the petitions within the template the best way is prefetch the petitions on the queryset to avoid hitting the database every time in the for loop.

Category.objects.prefetch_related('petitions').order_by('-petitions__created_on')

That would bring every petition for each category. So in your template you can use:

{% for category in category_list %}
    {% for petition in category.petitions.all %}
        ...
        @{{ petition.created_by }}
        ...
    {% end for %}
{% end for %}
4
  • Thanks for the response. The value returned in my query set with what you suggested and I am still getting the same error: Cannot resolve keyword 'petition_set__created_on' into field. Jan 21, 2016 at 3:08
  • Okay, I changed it to: def get_queryset(self): return Category.objects.order_by('-petition__created_on')[:10] and it's loading fine now except that the template (category.html) is still returning the category lists instead of displaying the posts in the category Jan 21, 2016 at 3:40
  • Ahh that's because you are only passing the categories to the template. Look how the listview works ccbv.co.uk/projects/Django/1.9/django.views.generic.list/…. I'll edit the answer to complete your question
    – harveydf
    Jan 21, 2016 at 12:47
  • I got another error: Cannot find 'petition' on Category object, 'petition' is an invalid parameter to prefetch_related() Jan 21, 2016 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.