Django表单字段未显示

时间:2017-08-02 17:21:12

标签: python django

您好我无法让我的表单正常工作。显示按钮但charfield从不显示。我尝试使用带有“sent”参数的if语句并且它有效。我只是跟着django doc。我没有在其他帖子中找到解决方案。

这是我的 forms.py

from django import forms

class CharacterForm(forms.Form):
    character_name = forms.CharField(label='Search', max_length=30)

views.py

from django.shortcuts import render
from .forms import CharacterForm

def index(request):
    return render(request, 'perso/pages/index.html')

def get_character(request):
        character_name = ''
        sent = False
        if request.method == 'POST':
            form = CharacterForm(request.POST)
            if form.is_valid():
                character_name = form.cleaned_data['character_name']
                sent = True
        else:
            form = CharacterForm()
        return render(request, 'perso/pages/index.html', {
            'form': form, 
            'character_name': character_name,
            'sent': sent
        })

Perso是应用的名称,在perso中的Urls.py

from django.conf.urls import url 

from . import views

app_name = 'perso'
urlpatterns = [
    url(r'^$', views.index, name="index"),
]

我在perso模板索引中的表单

<form action="{% url "perso:index" %}" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit" />
</form>

以下是浏览器中显示的内容:

<form action="/perso/" method="post">
    <input type='hidden' name='csrfmiddlewaretoken' value='IWmBEknyibHw4LpvjnyfLWKcUOXLbw27RdHgR7GjhTDelCLGZ51QeF3y9wRyC0Mg' />
    <input type="submit" value="Submit" />
</form>

缺少charfield。控制台没有错误。

1 个答案:

答案 0 :(得分:0)

您的代码中有一些异常,错过了渲染函数中的模板名称参数。在渲染功能中提供相应HTML文件的template name。您还错过了提供character_name和已发送变量的默认参数。请参阅文档here

from django.shortcuts import render
from .forms import CharacterForm
def get_character(request):
    character_name = ''
    sent = False
    if request.method == 'POST':
        form = CharacterForm(request.POST)
        if form.is_valid():
            character_name = form.cleaned_data['character_name']
            sent = True
    else:
        form = CharacterForm()
    return render(request, 'template_name.html', {
        'form': form, 
        'character_name': character_name,
        'sent': sent
    })

你错误地没有为在模板中设置表单的views.py中的函数设置urls.py模式

from django.conf.urls import url 
from . import views

app_name = 'perso'
urlpatterns = [
    url(r'^$', views.index, name="index"),
    url(r'^character$', views.get_character, name="character"),
]

您还需要在帖子请求template链接<{p>中URL进行更正

<form action="{% url "perso:character" %}" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit" />
</form>

现在,您的表单可以在http://localhost:8000/character

上找到