我试图让表单从用户那里获取信息并使用此信息发送电子邮件。这是我的代码:
#forms.py
from django import forms
class ContactForm(forms.Form):
nome = forms.CharField(required=True)
email = forms.EmailField(required=True)
msg = forms.CharField(
required=True,
widget=forms.Textarea
)
#views.py
from django.shortcuts import render, redirect, get_object_or_404, HttpResponseRedirect, render_to_response
from django.core.mail import send_mail
from .forms import ContactForm
def contato(request):
form_class = ContactForm
if request.method == 'POST':
form = form_class(request.POST)
if form.is_valid():
nome = request.POST.get('nome')
email = request.POST.get('email')
msg = request.POST.get('msg')
send_mail('Subject here', msg, email, ['testmail@gmail.com'], fail_silently=False)
return HttpResponseRedirect('blog/inicio')
return render(request, 'blog/inicio.html', {'form': form})
#contato.html
{% extends "blog/base.html" %}
{% block content %}
<form role="form" action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endblock %}
当我尝试进入联系页面时,我收到此错误:
local variable 'form' referenced before assignment
它说错误出现在这行views.py中:
return render(request, 'blog/inicio.html', {'form': form})
我在Django上有点新鲜,你能帮助我吗?
答案 0 :(得分:7)
您在此form
块中定义if request.method == 'POST':
变量。
如果您使用GET请求访问view
form
未定义。
您应该将视图更改为以下内容:
def contato(request):
form_class = ContactForm
# if request is not post, initialize an empty form
form = form_class(request.POST or None)
if request.method == 'POST':
if form.is_valid():
nome = request.POST.get('nome')
email = request.POST.get('email')
msg = request.POST.get('msg')
send_mail('Subject here', msg, email, ['testmail@gmail.com'], fail_silently=False)
return HttpResponseRedirect('blog/inicio')
return render(request, 'blog/inicio.html', {'form': form})
答案 1 :(得分:0)
如果可以通过初始化一个空的“形式”来说 - “附带损害”,那么你也可以提供一个“虚拟”值作为填充,直到“request.POST”被初始化...... / p>
{{1}}
答案 2 :(得分:0)
Django文档处理此问题,但与其他答案稍有不同。参见https://docs.djangoproject.com/en/dev/topics/forms/#using-a-form-in-a-view
使用else,如果请求不是POST,则创建空白表格。以下内容直接从文档中粘贴。
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})
答案 3 :(得分:0)
唯一的问题是您没有将ContactForm声明为函数, 从此改变;
def contato(请求): form_class = ContactForm 如果request.method =='POST':
TO; def contato(请求): form_class = ContactForm() 如果request.method =='POST':