Django:登录用户并刷新同一页面而不定义模板?

时间:2013-07-12 18:24:28

标签: django templates view login refresh

我正在尝试使用表单中的引导下拉符号来让用户登录。我能够对我的用户名和密码进行硬编码并进行身份验证,但我正在尝试用户登录而无需登录屏幕。这是我的代码:

模板: 我使用action来调用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>

enter image description here

URLS:

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

视图: 然后我有登录的这个视图,这是行不通的,因为即使表单成功发布,控制台也不会打印'enter'。我发错了吗?打错了行动? 是否有人知道如何创建登录/注销视图而不为其创建模板,以便只刷新/重定向到主页?

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

我还希望页面不要问我是否要重新加载,因为它的帖子形式,我相信这是解决方案以防任何人对此感兴趣:Stop browsers asking to resend form data on refresh?

谢谢!

2 个答案:

答案 0 :(得分:3)

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

以下是我的处理方式:

  1. 在我的Django项目中创建一个ajax应用程序,以保持我的AJAX视图和URL远离我的其余代码(我也喜欢重新使用我的应用程序。从一个项目到另一个项目)
  2. ajax应用程序
  3. 中对AJAX视图及其URL进行编码
  4. 使用jQuery
  5. 将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
    

    请参阅this answer了解require_AJAX装饰者。

    在提交表单(不仅仅是日志记录)时,我经常使用AJAX,因此我将上述JavaScript代码应用于我的所有表单(使用$("form").submit(...);)。但我需要让视图知道我发布的是哪种形式。以下是我如何处理以防万一:

    • 首先,您的网址应该欢迎参数(表格的ID为我)
    • 然后,相关视图将能够知道使用相应标签处理哪种情况

答案 1 :(得分:0)

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

TEMPLATE:

<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>

URLS:

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('/')

工作完美,看起来非常好看! =)