为什么POST请求中不存在该属性?

时间:2018-01-17 08:19:26

标签: python django

我正在尝试使用基于forms.ModelForm的查询填充forms.Form中的字段。不幸的是,我得到一个AttributeError,表明该字段不存在,我不确定为什么会这样。

错误为AttributeError: 'ElectionSuggestionForm' object has no attribute 'PostElection'

这是views.py:

def new_post(request):
    if request.method == 'POST':
        form = NewPostForm(request.POST)
        election_form = ElectionSuggestionForm(request.user, request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = Candidate.objects.get(UserID=request.user, ElectionID=election_form.PostElection)
            post.save()
            return redirect('/feed/')
    else:    
        form = NewPostForm()
        election_form = ElectionSuggestionForm(request.user)
    return render(request, 'campaign/new_post.html', {
        "form": form,
        "election_form": election_form,
    })

这是forms.py:

class ElectionSuggestionForm(forms.Form):

    PostElection = forms.ModelChoiceField(queryset=None)

    def __init__(self, user, *args, **kwargs):
        super(ElectionSuggestionForm, self).__init__(*args, **kwargs)
        print(Election.objects.all().filter(candidate__UserID=user))
        self.fields['PostElection'].queryset = Election.objects.all().filter(candidate__UserID=user)

由于

1 个答案:

答案 0 :(得分:2)

以下列方式访问您必须执行的表单的PostElection属性的值

election_form.cleaned_data['PostElection']

self.cleaned_data是一个字典,在调用is_valid()方法后接收所有已清理和验证的数据。

请务必同时致电is_valid()上的election_form

def new_post(request):
    if request.method == 'POST':
        form = NewPostForm(request.POST)
        election_form = ElectionSuggestionForm(request.user, request.POST)
        if form.is_valid() and election_form.is_valid():
            post = form.save(commit=False)
            post.author = Candidate.objects.get(
                UserID=request.user, 
                ElectionID=election_form.cleaned_data['PostElection']
                )
            post.save()
            return redirect('/feed/')
    else:    
        form = NewPostForm()
        election_form = ElectionSuggestionForm(request.user)
    return render(request, 'campaign/new_post.html', {
        "form": form,
        "election_form": election_form,
    })