我无法弄清楚为什么验证在我的应用中不起作用。
我的问题是,每次我在模板中发送表单( base_contact.html )时,应用程序都会将我发送到 / Thanks / 视图,但它是如此很奇怪,因为即使模板中的表单为空或有多个验证错误,它也会这样做。所以我认为 form.is_valid()在这种情况下无法正常工作。这些是我的文件:
models.py
from django.db import models
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField(widget=forms.Textarea())
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
views.py
from django.shortcuts import render_to_response
from django.core.context_processors import csrf
from django.http import HttpResponseRedirect
from main.models import ContactForm
from django.core.mail import send_mail
def contact(request):
if request.method == 'POST': # If the form has been submitted...
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
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
cc_myself = form.cleaned_data['cc_myself']
recipients = ['example@gmail.com']
send_mail(subject, message, sender, recipients)
return HttpResponseRedirect('/Thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render_to_response('base_contact.html', {'form': form})
base_contact.html
<div class="forms">
<table>
<form action="/Contact/" method="post">{% csrf_token %}
<tr><th><label for="id_sender">Your email:</label></th>
<td><input class="text" type="text" name="sender" id="id_sender" /></td></tr>
<tr><th><label for="id_subject">Subject:</label></th>
<td><input class="text" id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>
<tr><th><label for="id_message">Message:</label></th>
<td><textarea class="styletextarea" name="message" id="id_message" rows="7" cols="35" /></textarea></td></tr>
<tr><td></td><td><input class="button" type="submit" value="Send" /></td></tr>
</form>
</table>
</div>
感谢您的帮助:)
答案 0 :(得分:1)
检查以下行的缩进
return HttpResponseRedirect('/Thanks/')
在Python(以及Django)中,缩进非常重要。每个缩进级别使用4个空格是recommended。避免使用标签。您可以经常更改文本编辑器或ide的设置,以便在按Tab键时使用4个空格。