【发布时间】:2018-01-26 20:54:01
【问题描述】:
我已经阅读了许多关于如何将 ajax 与 django 表单集成的教程,但都非常复杂。我有一个带有注册表单的注册模型和如下视图。 models.py
from django.db import models
class SignUp(models.Model):
name = models.CharField(max_length=120, blank=True, null=True)
email = models.EmailField()
def __unicode__(self):
return self.email
和forms.py
from django import forms
from .models import SignUp
class SignUpForm(forms.ModelForm):
class Meta:
model = SignUp
fields = ['name', 'email']
def clean_name(self):
name = self.cleaned_data.get('name')
return name
def clean_email(self):
email = self.cleaned_data.get('email')
try:
match = SignUp.objects.get(email=email)
except SignUp.DoesNotExist:
return email
raise forms.ValidationError('This email address is already subscribed.')
views.py
from django.shortcuts import render
from django.core.mail import send_mail
from django.conf import settings
from .forms import SignUpForm
def index(request):
form = SignUpForm(request.POST or None)
if form.is_valid():
name = form.clean_name()
email = form.clean_email()
instance = form.save()
subject = 'Bruke Church news'
from_email = settings.EMAIL_HOST_USER
to_email = [email]
contact_message = "%s:Thank you for signing up for our newsletter via %s. we'll be in touch" %(
name,
email)
send_mail (subject,
contact_message,
from_email,
to_email,
fail_silently=False)
context = {
"form": form
}
return render(request, "index.html",context)
我的html表单看起来像这样
<form action="" method="POST">
{% csrf_token %}
{{form|crispy}}
<input type="submit" value="Sign up" class="btn btn-primary">
</form>
这段代码运行良好,但它加载了整个页面,我只想加载表单。谷歌搜索后,我发现了 Ajax 的概念,但这样做确实有问题。请帮助我谢谢
【问题讨论】:
标签: javascript python ajax django django-forms