使用ModelChoiceField的Django表单始终无效

时间:2016-09-14 23:08:41

标签: django django-forms django-views

以下是我的模板的相关部分。我试图将选定的字段从下拉菜单发送到我的表单。

<form action="character_chat" method="post">
    <select id="character_name">
        {% for character in characters %}
        <option name={{character}}>{{character}}</option>
        {% endfor %}
    </select>
    <input type="submit" value="Select">
</form>

视图中的相关代码:

def character_chat(request):
    class CharacterForm(forms.Form):
        character_name = forms.ModelChoiceField(queryset=Character.objects.all())

    if request.method == 'POST':
         form = CharacterForm(request.POST)
         if form.is_valid():
            print("Valid form!")
            print(form.cleaned_data['character_name'])

我从未看过打印语句,因此表单似乎总是无效。任何建议或意见将不胜感激!

1 个答案:

答案 0 :(得分:1)

您应该在模板中使用{{ form.character_name }}。不需要创建一个html选择元素,因为Django免费提供这个。此外,Django实际上使用name HTML属性,而不是id。此外,如果您想在不使用上下文中的form的情况下执行此操作,则<option>标记看起来会更像这样:

<option value={{character.id}}>{{character}}</option>

查看文档以获取更多信息:https://docs.djangoproject.com/en/1.10/topics/forms/#rendering-fields-manually

由于评论而更新:

您需要先将表单放在模板的上下文中,然后才能使用它。以下是从the Django form docs获取的一个非常适用的示例:

from django.shortcuts import render
from django.http import HttpResponseRedirect

from .forms import NameForm

def get_name(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = NameForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            return HttpResponseRedirect('/thanks/')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = NameForm()

    return render(request, 'name.html', {'form': form})

请注意,如果请求方法是GET,它们是否使用模板呈现请求,并将form放在上下文字典中?这也是你需要做的事情:

def character_chat(request):
    class CharacterForm(forms.Form):
        character_name = forms.ModelChoiceField(queryset=Character.objects.all())

    if request.method == 'POST':
         form = CharacterForm(request.POST)
         if form.is_valid():
            print("Valid form!")
            print(form.cleaned_data['character_name'])
            # now you should redirect
    else: # GET request method
        form = CharacterForm()
        return render(request, 'NAME OF YOUR TEMPLATE HERE', {'form': form})