【问题标题】:Django - A bit lost with forms [closed]Django - 表单有点迷失[关闭]
【发布时间】:2014-04-22 10:50:18
【问题描述】:

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

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

谢谢。

【问题讨论】:

  • 您的具体问题是什么?你有什么不明白的?
  • 在我的问题中说过,表单的代码放置在哪里以及一个基本的例子来看看它是如何工作的。

标签: python django django-forms


【解决方案1】:

来自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>

【讨论】:

  • 很抱歉。更新了答案。
  • 正是我想要的,谢谢!
  • 我试过了,但我有一个小问题,当我想访问表单时,它会自动将我重定向到 contact.html 并且我已经设置了正确的验证:if form.is_valid (): # 所有验证规则通过 subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] sender = form.cleaned_data['sender'] cc_myself = form.cleaned_data['cc_myself']跨度>
  • 您可能应该删除模板中的 action="/contact/" 部分。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-04
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-16
    • 2013-06-06
    相关资源
    最近更新 更多