简体   繁体   中英

Django Form Fields won't show in my template

The form field won't show up in the browser. There is only the submit button showing up.

views.py code:

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})

template(fact_detail.html) code:

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

Form class(forms.py) code:

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


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

In views.py for the vote method initialize the form variable locally, before passing it as a parameter.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM