【问题标题】:Django form.py not updatingDjango form.py 没有更新
【发布时间】:2017-01-27 01:03:34
【问题描述】:

我一直在通过Django forms 'tutorial'。阅读完本教程后,我尝试对其进行修改以满足我的需要并对其进行自定义以很好地学习 Django 表单。我发现每当我修改表格时,网站都不会更新。我认为我的代码有错误,但我无法找到它。

# views.py
def contact(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 = ContactForm(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('/message_recived/')

# forms.py
from django import forms
class ContactForm(forms.Form):
    name = forms.CharField(label='Name', max_length=100)
    email = forms.EmailField(label='Email', max_length=100)
    message = forms.CharField(label='Message', max_length=500)


# models.py
from django.db import models
class Contact(models.Model):
    name = models.CharField(max_length=100)
    email = models.CharField(max_length=100)
    message = models.CharField(max_length=500)

这是contact.html 模板:

#contact.html
{% extends "BlogHome/headerAndFooter.html" %}
{% block content %}
<script>
document.title = "Pike Dzurny - Contact"
</script>
<form action="/message_recived/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>
{% endblock %}

我做错了吗?我已经尝试清除浏览器缓存,使用新浏览器,显然是刷新它。

【问题讨论】:

    标签: python django django-models django-1.8


    【解决方案1】:

    看起来您忘记在您的视图中回复render。 您还需要将表单包含在上下文中以正确呈现模板。

    尝试如下改变视图:

    def contact(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 = ContactForm(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('/message_recived/')
        else:
            form = ContactForm()       
        return render(request, 'contact.html', {'form': form}) 
    

    【讨论】:

    • @PikeD。嗯,当你在浏览器中打开页面时,你能检查它是否是正确的模板吗?你能看到页面上的表格吗?
    • 好的,我刚刚查看了我的模板,看起来我的模板有一个副本,除了一个是contact.html,另一个是Contact.html,看起来我正在编辑@987654325 @。然后我将 HTML 复制并粘贴到 contact.html 中,看起来它现在仍然没有呈现表单。
    • @PikeD。检查 headerahdfooter 模板是否具有名为 content 的块。也尝试在contact.html的这个块内添加测试文本,并检查它是否在浏览器中更新。
    • @PikeD。尝试在 return render() 行之前添加 print(form) 并检查将打印的内容。顺便说一句,您确定您使用的是联系人视图吗?)
    • @PikeD。您可以在 shell 中看到输出。当你像 python manage.py runserver 这样运行 django 时,python 将打印系统消息,如果你添加 print 来查看你也可以看到这个消息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 2018-01-12
    • 2017-01-28
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    相关资源
    最近更新 更多