·

django object has no attribute 'count'

Published at 2024-08-21 17:45:15Viewed 128 times
Professional article
Please reprint with source link

Question

I am learning django / python and I am stuck on an issue.

I have a view: create_document.py in which I want to count the number of name details from a models class: NameDetails.

I cannot get the correct syntax!

Here is my models.py code:

class NameDetails(FillableModelWithLanguageVersion):
    user = models.ForeignKey(User)
    name_details_prefix_title = models.CharField(null=True, blank=True, max_length=25)
    name_details_first_name = models.CharField(null=False, blank=False, max_length=50)
    name_details_middle_name = models.CharField(null=True, blank=True, max_length=100)
    ....

Here is my create_document.py code in which I have a django wizard. I want to make sure the user has more than 1 name before they can create a document:

from app_name.core.models import NameDetails

class CreateDocumentWizard(SessionWizardView):
    template_name = 'documents/document_create.html'

    form_list = [
        core_forms.CreateDocumentWizardForm01,
        core_forms.CreateDocumentWizardForm02,
        core_forms.CreateDocumentWizardForm03,
        core_forms.CreateDocumentWizardForm04,
    ]

    def get_form_kwargs(self, step=None):
        kwargs = super(CreateDocumentWizard, self).get_form_kwargs(step)
        kwargs.setdefault('user', self.request.user)
        return kwargs

    def get_context_data(self, form, **kwargs):

        name_details_count = NameDetails(user=self.request.user).count()
        if name_details_count < 1:
            return redirect(settings.MENU_DETAIL_LINK_NAME_DETAILS)

When I use the line to determine the count of NameDetails of the user: name_details_count = NameDetails(user=self.request.user).count(), I get the following error:

NameDetails' object has no attribute 'count'

I have tried many permutations, but I am stuck.

Answer 1

It should be like that in your get_context_data function:

name_details_count = NameDetails.objects.filter(user=self.request.user).count()

Answer 2

At the moment you're creating a brand new NameDetails instance with request.user as the user. Instead, you should query the database for existing NameDetails for the current user, and count them. You can query the database through NameDetails.objects:

name_details_count = NameDetails.objects.filter(user=self.request.user).count()


The content is from StackOverflow which is translated and used in accordance with the CCBY-SA 4.0 license agreement. Original link: django object has no attribute 'count'

0 人喜欢

Comments

There is no comment, let's add the first one.

弦圈热门内容

Get connected with us on social networks! Twitter

©2024 Guangzhou Sinephony Technology Co., Ltd All Rights Reserved