问题
I am trying to make a url field in my detail view by passing two primary key in it...
This is what I have done in urls.py:
url(r'^company/(?P<pk1>\d+)/groupdetail/(?P<pk2>\d+)/$',views.group1DetailView.as_view(),name='groupdetail'),
And in my views:
def get_object(self):
pk1 = self.kwargs['pk1']
pk2 = self.kwargs['pk2']
company = get_object_or_404(company, pk=pk1)
group1 = get_object_or_404(group1, pk=pk2)
return group1
I am getting error in this line:
company = get_object_or_404(company, pk=pk1)
And in my group1 list view I have done this:
<a href="{% url 'accounting_double_entry:groupdetail' pk1=company_details.pk pk2=group1_details.pk %}">{{group1.group_Name}}</a>
Can anyone tell me what I am doing wrong in this code?
Thank you
回答1:
In your function, you assign to a variable named company
, so Python considers company
to be a local variable, but at that moment unassigned, so you will need to use anoter variable name to avoid this:
def get_object(self):
pk1 = self.kwargs['pk1']
pk2 = self.kwargs['pk2']
# make sure the variable name is different than the model name
company_obj = get_object_or_404(company, pk=pk1)
group1 = get_object_or_404(group1, pk=pk2)
return group1
Since you here however do not use company_obj
, you might want to drop the variable name:
def get_object(self):
pk1 = self.kwargs['pk1']
pk2 = self.kwargs['pk2']
get_object_or_404(company, pk=pk1)
group1 = get_object_or_404(group1, pk=pk2)
return group1
as an alternative, if your group1
is "related" to company
, and you want to chekck if that holds, it makes sense to filter on that company:
def get_object(self):
pk1 = self.kwargs['pk1']
pk2 = self.kwargs['pk2']
company_obj = get_object_or_404(company, pk=pk1)
group1 = get_object_or_404(group1, pk=pk2, company=company_obj)
return group1
Note: PEP-8 [Python-doc] advices class names to be written in
CamelCase
, whereas fields and local variables are written inlower_case
. It is not uncommon to see something likesome_class = SomeClass()
, so because the camel case starts with an uppercase, clashes between local variables and classes, will never exist.
来源:https://stackoverflow.com/questions/52603288/django-unboundlocalerror-local-variable-company-referenced-before-assignment