Django的 - 阿贾克斯模式登录/注册 [英] Django - Ajax modal login/registration

查看:356
本文介绍了Django的 - 阿贾克斯模式登录/注册的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目中,我需要弹出一个模态窗口为未通过身份验证的用户。

I have a project in which I need to pop a modal window for not authenticated users.

此模式将允许直接登录创建一个帐户。

This modal will allow to login directly or create an account.

那么它将包含两种形式:

So it will contain two forms:

  • django.contrib.auth.forms.AuthenticationForm
  • registration.forms.RegistrationForm
  • django.contrib.auth.forms.AuthenticationForm
  • registration.forms.RegistrationForm

下面是我的看法得到两种形式:

Here is my view to get both forms:

def ajax_registration(request):
    obj = {
        'login_form': AuthenticationForm(),
        'registration_form': RegistrationForm(),
    }
    return render(request, 'common/ajax_registration.html', obj)

和我的模板显示表单标签

And my template displaying the forms tabbed

<ul class="nav nav-tabs">
  <li><a href="#tab1" data-toggle="tab">{% trans 'Login' %}</a></li>
  <li><a href="#tab2" data-toggle="tab">{% trans 'Registration' %}</a></li>
</ul>
<div class="tab-content">
  <div class="tab-pane active" id="tab1">
    {{ login_form|bootstrap }}
  </div>
  <div class="tab-pane" id="tab2">
    {{ registration_form|bootstrap }}
  </div>
</div>

问题是:由于我使用AJAX来显示这个模式,我如何可以验证所选择的形式,preferably使用已经写<一href="http://docs.b-list.org/django-registration/0.8/views.html#registration.views.register"><$c$c>django-registrations注册 和放大器; <一href="https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.views.login"><$c$c>django.contrib.auth登录 看法?

Question is: Since I'm using ajax to display this modal, How can I validate the selected form, preferably using the already written django-registrations register & django.contrib.auth login views ?

推荐答案

在除了Maddog的答案,你需要一些JavaScript提交表单回到那个呈现的形式的URL。使用jQuery它可能是这样的:

In addition to Maddog's answer you need some javascript to submit the form back to the URL that rendered the form. Using jquery it could be something like:

$('form').submit(function(e){
        e.preventDefault();
        var form = $(e.target);

        $.ajax({
            url: '{% url YOUR_REGISTRATION_URL %}',
            type: 'post',
            data: account_form.serialize() + '&' + form.serialize(),
            error: function(xhr, ajaxOptions, thrownError){ alert(thrownError); },
            success: function(){}
        })
 })

您并不需要用表格做提交的元素,你可以使用任何元素与$()。点击(当然)。

You don't need to do it with a form submit element, you could use any element with $().click(), of course.

这篇关于Django的 - 阿贾克斯模式登录/注册的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆