我想要一张邀请函表格。我创建了一个表单但是当我转到url / invitations / request时,显示的是无效块,而不是带有表单的模板。可能是什么原因?
url(r'^request/$', requestInvitation, name='request-invitation'),
@csrf_exempt
def requestInvitation(request):
form = InviteForm(request.POST or None)
response_data = {}
if form.is_valid():
join = form.save(commit=False)
email = form.cleaned_data.get('email')
already_join, created = Invitation.objects.get_or_create(email=email)
if created:
already_join.invite_code = get_invite_code()
already_join.save()
response_data['result'] = "Thank you for your interest"
response_data['email'] = email
print ('response_data', response_data)
return HttpResponse(json.dumps(response_data),content_type="application/json")
else:
return HttpResponse(json.dumps({'result': 'Error message'}))
# return HttpResponseRedirect('/')
context = {"form": form}
return render(request, 'invitation/invitation.html', context)
<form method="POST" class="invitation-form vcenter" action=".">
{% csrf_token %}
<div class="ui action input">
<input type="email" class="requested_email" name="email" placeholder="Email address">
<button class="ui button primary">Request Invite</button>
</div>
</form>
答案 0 :(得分:0)
我认为,您需要将POST调用分开。我的意思是,你需要检查请求方法是否是POST。像这样:
if request.method == 'POST': # If the form has been submitted...
response_data = {}
if form.is_valid():
join = form.save(commit=False)
email = form.cleaned_data.get('email')
already_join, created = Invitation.objects.get_or_create(email=email)
if created:
already_join.invite_code = get_invite_code()
already_join.save()
response_data['result'] = "Thank you for your interest"
response_data['email'] = email
print ('response_data', response_data)
return HttpResponse(json.dumps(response_data),content_type="application/json")
else:
return HttpResponse(json.dumps({'result': 'Error message'}))
# return HttpResponseRedirect('/')
else:
# An unbound form
答案 1 :(得分:0)
以下是request
的工作流程:
发出GET
个请求(您只是访问/invitations/request
。因此request.POST
为空{}
。
form = InviteForm(request.POST or None)
。因此,InviteForm
无效。
if form.is_valid():
为False
。
else: return HttpResponse(json.dumps({'result': 'Error message'}))
。因此,执行else
子句,返回JSON
响应,您将在模板中显示该响应。现在,对于解决方案:
@csrf_exempt
def requestInvitation(request):
form = InviteForm()
response_data = {}
if request.method == 'POST':
# This is a POST request, so request.POST will not be {}
form = InviteForm(request.POST)
if form.is_valid():
join = form.save(commit=False)
email = form.cleaned_data.get('email')
already_join, created = Invitation.objects.get_or_create(email=email)
if created:
already_join.invite_code = get_invite_code()
already_join.save()
response_data['result'] = "Thank you for your interest"
response_data['email'] = email
print ('response_data', response_data)
return HttpResponse(json.dumps(response_data),content_type="application/json")
else:
return HttpResponse(json.dumps({'result': 'Error message'}))
context = {'form': form}
return render(request, 'invitation/invitation.html', context)