在多个模板中显示相同的表单

时间:2017-04-11 16:55:36

标签: python django django-forms django-views

我有一个需要在两个不同模板中显示的表单。一个是主页面,即在邀请页面上仅显示邀请表单,另一个在主页中。当从主页填写表单时,如果有错误,则应该从该表单的主页显示错误,即邀请模板。

我可以在邀请模板中显示表单并且错误显示也可以正常工作但是如果我从主页填写表单,我总是得到'此字段是必需的'错误,即使我通过了正确的价值。

这是我的代码

def requestInvitation(request):
    form = InviteForm(request.POST or None)
    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()
            send_request_received_email.delay(email,already_join.email_tracker)
            messages.success(request, "Thank you for your interest.")
        return HttpResponseRedirect('/')
    context = {"form": form}
    return render(request, 'invitation/invitation.html', context)


def index(request):
    form = InviteForm(request.POST or None)
    context = {"form": form}
    if not request.user.is_authenticated():
        return render(request, "home.html", context)
    else:
        return render(request, "home.html", context)


url(r'^request/$', requestInvitation, name='request-invitation'),

更新

def index(request):
    form = InviteForm(request.POST or None)
    if form.is_valid():
        join = form.save(commit=False)
        print ('noin', join)
        email = form.cleaned_data.get('email')
        already_join, created = Invitation.objects.get_or_create(email=email)
        print ('already_join', already_join, created)
        if created:
            already_join.invite_code = get_invite_code()
            already_join.save()
            send_request_received_email.delay(email,already_join.email_tracker)
            messages.success(request, "Thank you for your interest")
            return HttpResponseRedirect('/')
        else:
            return HttpResponseRedirect('/invitations/request')
    # return HttpResponseRedirect('/invitations/request')
    context = {"form": form}
    return render(request, 'index.html', context)

我将索引视图更改为此。如果我填写正确的值,数据将被保存,但如果有错误,它不会重定向到/ invitation / request页面以显示该错误。如果我在form.is_invalid()的else条件下使用HttpResponseRedirect,那么当我进入主页时,我立即被重定向到/ invitation / request页面。

1 个答案:

答案 0 :(得分:0)

您没有在家庭视图中验证并保存表单,因此基本上它仍然是空的