2

我正在尝试使用引导下拉登录表单让用户登录。我可以硬编码我的用户名和密码并进行身份验证,但我试图让用户登录而不进入登录屏幕。这是我的代码:

模板:我使用操作调用 logUserIn url,以便表单可以发布到该视图。

<ul class="nav pull-right">
          {% if user.is_authenticated %}
          <li><a> Welcome {{ user.first_name }} </a></li>
          <li class="divider-vertical"></li>
          <li><a href="{% url 'caesarWorkflowApp.views.logUserOut' %}">Log Out</a></li>
          <li class="divider-vertical"></li>
          {% else %}
          <li class="dropdown">
            <a class="dropdown-toggle" href="#" data-toggle="dropdown">Sign In <strong class="caret"></strong></a>
            <div class="dropdown-menu" style="padding: 15px; padding-bottom: 0px;">
              <form action="{% url 'caesarWorkflowApp.views.logUserIn' %}" method="post" accept-charset="UTF-8">
                {% csrf_token %}
                <input id="user_username" style="margin-bottom: 15px;" type="text" name="username" placeholder="Username" size="30" />
                <input id="user_password" style="margin-bottom: 15px;" type="password" name="password" placeholder="Password" size="30" />
                <input id="user_remember_me" style="float: left; margin-right: 10px;" type="checkbox" name="user[remember_me]" value="1" />
                <label class="string optional" for="user_remember_me"> Remember me</label>
                <input class="btn btn-primary" style="clear: left; width: 100%; height: 32px; font-size: 13px;" type="submit" name="commit" value="Sign In" />
              </form>
            </div>
          </li>
            {% endif %}
          <li class="divider-vertical"></li>
        </ul>

在此处输入图像描述

网址:

urlpatterns = patterns('',
    url(r'^$', 'caesarWorkflowApp.views.home', name='default'),
    url(r'^$', 'caesarWorkflowApp.views.logUserIn'),
    url(r'^$', 'caesarWorkflowApp.views.logUserOut'),
)

视图:然后我有这个登录视图,它不起作用,因为即使表单发布成功,控制台也不会打印“输入”。我发错了吗?调用错误的操作?有谁知道如何在不为其创建模板的情况下创建登录/注销视图,以便它只刷新/重定向到主页?

def logUserIn(request):
    if request.method == 'POST':
        print 'enter'
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            # the password verified for the user
            if user.is_active:
                login(request, user)
                print("User is valid, active and authenticated")

            else:
                print("The password is valid, but the account has been disabled!")
        else:
            # the authentication system was unable to verify the username and password
            print("The username and password were incorrect.")

    response = render_to_response('home.html', {}, context_instance=RequestContext(request))
    return response

我还希望页面不要问我是否要重新加载,因为它是发布表单,我相信这是如果有人对此感兴趣的解决方案:停止浏览器要求在刷新时重新发送表单数据?

谢谢!

4

2 回答 2

3

您正在寻找的是所谓的 AJAX。我总是使用jQuery来处理 AJAX 请求,因为它使工作变得更容易。

以下是我通常的处理方式:

  1. 在我的 Django 项目中创建一个ajax应用程序,以使我的 AJAX 视图和 URL 远离我的其余代码(另外,我喜欢重复使用我的应用程序。从一个项目到另一个项目)
  2. ajax在应用程序中编写 AJAX 视图及其 URL
  3. 使用 jQuery 将 AJAX 请求应用于我的表单

模板

<form id="form-login" action="" method="post">
{% csrf_token %}
<!-- Put your form here -->
<button type="submit">submit</button>
</form>

JavaScript

$(document).ready(function() {
    $("#form-login").submit(function() {
        jQuery.ajax({
            "data":    $(this).serialize(),
            "type":    $(this).attr("method"),
            "url":     "{% url 'login-submit' %}",
            "success": function(response) {
                switch(response.code) {
                    // Do what you want with the received response
                }
            }
        });
        return false;
    });
});

AJAX 网址

urlpatterns = patterns('',
    url(r'^ajax/login/submit/$', 'path.to.login_submit', name='login-submit'),
)

AJAX 视图

@require_AJAX
def login_submit(request, label):
    # Code here the logging logic 
    response = HttpResponse(json.dumps({'code':'42'}), content_type='application/json')
    return response

请参阅装饰者的这个答案。require_AJAX

在提交表单时我经常使用 AJAX(不仅仅是日志记录),所以我将上面的 JavaScript 代码应用于我的所有表单(带有$("form").submit(...);)。但是我需要让视图知道我发布的表单。如果您需要,我会这样做:

  • 首先,您的 URL 应该欢迎一个参数(我的表单 ID)
  • 然后关联的视图将能够知道使用相应的标签来处理哪种情况
于 2013-07-12T19:18:48.033 回答
0

我无法让 AJAX 工作,所以我想出了这个解决方案:

模板:

<ul class="nav pull-right">
          {% if user.is_authenticated %}
          <li><a> Welcome, {{ user.first_name }} </a></li>
          <li class="divider-vertical"></li>
          <li><a href="/logout/">Log Out</a></li>
          <li class="divider-vertical"></li>
          {% else %}
          <li class="dropdown">
            <a class="dropdown-toggle" href="#" data-toggle="dropdown">Sign In <strong class="caret"></strong></a>
            <div class="dropdown-menu" style="padding: 15px; padding-bottom: 0px;">
              <form id="form-login" action="/" method="post" accept-charset="UTF-8">
                {% csrf_token %}
                <input id="user_username" style="margin-bottom: 15px;" type="text" name="username" placeholder="Username" size="30" />
                <input id="user_password" style="margin-bottom: 15px;" type="password" name="password" placeholder="Password" size="30" />
                <input id="user_remember_me" style="float: left; margin-right: 10px;" type="checkbox" name="user[remember_me]" value="1" />
                <label class="string optional" for="user_remember_me"> Remember me</label>
                <input class="btn btn-primary" style="clear: left; width: 100%; height: 32px; font-size: 13px;" type="submit" name="commit" value="Sign In" />
              </form>
            </div>
          </li>
          <li class="divider-vertical"></li>
          {% endif %}
        </ul>

网址:

urlpatterns = patterns('',
    url(r'^$', 'caesarWorkflowApp.views.home', name='default'),
    url(r'^login/$', 'caesarWorkflowApp.views.logUserIn'),
    url(r'^logout/$', 'caesarWorkflowApp.views.logUserOut'),
)

意见:

def logUserIn(request):
    print 'enter'
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        # the password verified for the user
        if user.is_active:
            login(request, user)
            print("User is valid, active and authenticated")

        else:
            print("The password is valid, but the account has been disabled!")
    else:
        # the authentication system was unable to verify the username and password
        print("The username and password were incorrect.")

    response = render_to_response('home.html', {}, context_instance=RequestContext(request))
    return response

def logUserOut(request):
    logout(request)
    return HttpResponseRedirect('/')

完美地工作,真的很好看!=)

于 2013-07-12T20:39:27.533 回答