Django: UnboundLocalError: local variable 'company' referenced before assignment

后端 未结 1 735
独厮守ぢ
独厮守ぢ 2021-01-25 04:26

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

        
相关标签:
1条回答
  • 2021-01-25 05:12

    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 another 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_obj = get_object_or_404(group1, pk=pk2)
        return group1_obj

    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_obj = get_object_or_404(group1, pk=pk2)
        return group1_obj

    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_obj = get_object_or_404(group1, pk=pk2, company=company_obj)
        return group1_obj

    Note: PEP-8 [Python-doc] advices class names to be written in CamelCase, whereas fields and local variables are written in lower_case. It is not uncommon to see something like some_class = SomeClass(), so because the camel case starts with an uppercase, clashes between local variables and classes, will never exist.

    0 讨论(0)
提交回复
热议问题