'的QueryDict'对象没有属性' association'

时间:2017-03-11 19:06:08

标签: python django python-2.7 python-3.x django-views

管理员(已登录)想要注册一个与admin具有相同关联名称的成员,但会抛出此错误。

我有什么遗失的吗?

还是新手,非常感谢你的帮助,伙计们!

管理员\ models.py

class Administrator(AbstractUser):
    ...
    association= models.ForeignKey(Association)


    class Meta:
        db_table = 'Administrator'

构件\ models.py

from pl.admin.models import Administrator


class Association(models.Model):
    asoc_name = models.CharField(max_length=100)

    class Meta:
        db_table = 'Association'

    def __str__(self):
        return self.asoc_name

forms.py

class RegForm(forms.ModelForm):
    ...
    association = forms.ModelChoiceField(queryset=Association.objects.none())
     ...


    class Meta:
        model = Administrator
        fields = [..., 'association', ...]

    def __init__(self, user, *args, **kwargs):
        super(RegForm, self).__init__(*args, **kwargs)
        self.fields['association'].queryset = Association.objects.filter(
                                              asoc_name=user.association)

views.py

def member_signup(request):
    if request.method == 'POST':
        form = RegForm(request.POST, request.user)
        if not form.is_valid():
            return render(request, 'member/member_signup.html',
                          {'form': form})

        else:
            ...
            asoc = form.cleaned_data.get('association')
            ...
            Member.objects.create(...
                                  association=asoc,    
                                  ...)
            user = authenticate(...
                                association=asoc,
                                ...)
            return redirect('/')

    else:
        return render(request, 'member/member_signup.html',
                      {'form': RegForm(request.user)})

使用追溯编辑

Traceback (most recent call last):
   File "C:\Python36\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
      response = get_response(request)
   File "C:\Python36\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
      response = self.process_exception_by_middleware(e, request)
   File "C:\Python36\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
      response = wrapped_callback(request, *callback_args, **callback_kwargs)
   File "C:\...\member\views.py", line 184, in member_signup
      form = RegForm(request.POST, request.user)
   File "C:\...\member\forms.py", line 113, in __init__
      self.fields['association'].queryset = Association.objects.filter(asoc_name=user.association)
AttributeError: 'QueryDict' object has no attribute 'association'

1 个答案:

答案 0 :(得分:1)

user是表单的第一个参数,但在if子句中,您将request.POST之后的第二个参数传递给它。

一般情况下,您应该避免更改表单实例化的签名;相反,您应该将用户作为关键字参数传递,并从kwargs获取。