Django表单字段不会在我的模板中显示

时间:2017-10-10 10:09:36

标签: python django django-forms

表单字段不会显示在浏览器中。只显示提交按钮。

views.py 代码:

def vote(request, pk):
    # check if request is post
    if request.method == 'POST':
        # create a form and populate it with data from request
        form = forms.Vote(request.POST)
        if form.is_valid():
            fact = Fact.objects.get(pk=pk)
            fact.votes += int(form.cleaned_data['vote'])
            fact.save()
            return HttpResponseRedirect(reverse(
                'facts:detail',
                args=(pk,)
            ))
    else:
        form = forms.Vote()
    return render(request, 'facts/fact_detail.html', {'form': form})

模板(fact_detail.html)代码:

<form method='POST'>
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="vote" />
</form>

表单类(forms.py)代码:

VOTE_CHOICES = [
    (1, 'upvote'),
    (0, 'downvote')
]


class Vote(forms.Form):
    vote = forms.ChoiceField(choices=VOTE_CHOICES,  widget=forms.RadioSelect())

2 个答案:

答案 0 :(得分:0)

投票方法的 views.py 在本地初始化表单变量,然后将其作为参数传递。

def vote(request, pk):
     form=""
    //rest of the code//
       return render(request, 'facts/fact_detail.html', {'form': form})

答案 1 :(得分:0)

我建议从django文档检查通用编辑视图我认为它有解决方案 [https://docs.djangoproject.com/en/1.11/ref/class-based-views/generic-editing/#createview][1]