Django-views

相关内容

How to split views.py to several smaller files in Django

When your views.py is too large, it becomes much more difficult to manage your code. So you might want to split views.py into several subviews, each of which contains a single sort of views.To split views.py, you could follow the following steps. Your original views.py might look like this:import ... def view1(request): pass def view2(request): passNow, create a new folder subviews aside with views.py , i.e. /Django/mysite/MyAPI/subviews. Next, create __init__.py, viewsa.py, and viewsb.py in the folder subviews to form the following folder/file structure :subviews/ __init__.py subviews1.py subviews2.pysubviews1.py :from .views import * def view1(request): passsubviews2.py :from .views import * def view2(request): pass__init__.py :from subviews1 import * from subviews2 import *Then this would work the same as a single views.py file. Don't forget to change the urls.py file before you reloading Django.
2024-05-01 14:11:30

django对象报错object has no attribute 'count'

提问我正在学习django/python,并被一个问题给卡住了。我有一个视图:create_document.py,我想在其中计算模型类NameDetails中的名字细节数量。但我不知道正确的写法!这是我models.py的代码: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) ....这是我create_document.py的代码,里面用到了django wizard。我想要确定的是用户在他们能够创建文档前,至少有一个名字。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)当我使用name_details_count = NameDetails(user=self.request.user).count()确定用户的NameDetails计数时,我得到了以下错误:NameDetails' object has no attribute 'count'我已经尝试了很多种组合,但现在还是卡住了。回答1你的get_context_data函数应该这样写:name_details_count = NameDetails.objects.filter(user=self.request.user).count()回答2眼下你正在以request.user为用户创建一个全新的NameDetails实例。相反,你应该查询数据库中当前用户已有的NameDetails,并对他们进行计数。你可以通过NameDetails.objects查询数据库:name_details_count = NameDetails.objects.filter(user=self.request.user).count()内容来源于StackOverflow, 遵循 CCBY-SA 4.0 许可协议进行翻译与使用。原文链接:django object has no attribute 'count'
2024-08-21 17:45:15