Django - 表格有点丢失

时间:2014-04-22 10:50:19

标签: python django django-forms

我在Django表单中工作。我有点迷失在哪里放置关于表单的代码(forms.py或models.py?)以及哪些代码放在我的模板中。我搜索过文档,但无法弄清楚,我在Django中有点新鲜,谢谢。

如果有人能给我一个简单形式的完整例子来理解这些东西,我将不胜感激。

感谢。

2 个答案:

答案 0 :(得分:3)

来自Django docs

您应该在 forms.py

中创建表单类

实施例

from django import forms

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = forms.EmailField()
    cc_myself = forms.BooleanField(required=False)

要在模板中呈现表单,您需要将其添加到上下文中。所以你的 views.py 看起来应该是这样的。

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

def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        # ContactForm was defined in the the previous section
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = ContactForm() # An unbound form

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

注意这一部分。字典{'form':form}是您的请求上下文,这意味着密钥将被添加到您的模板变量中。

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

现在,您可以在模板中使用它。

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

答案 1 :(得分:1)

您可以查看此基本示例,在以下链接中提供,以便在django中处理POST表单。

http://www.pythoncentral.io/how-to-use-python-django-forms/