Django:根据用户身份验证的结果更改 url

Django: Change url based on result of user authentication

我是 django 的新手,一直卡在我认为很简单的问题上。我已经在我的应用程序中设置了用户身份验证,它工作正常,我遇到的问题是提交表单时出现的 url 地址。问题是:

我的表单上接受用户登录凭据的操作设置为 "{% url 'home' %}",这是对 /dashboard/home 的引用。这正是我希望 url 在成功登录时的样子。但是,当登录不成功的时候,我想停留在登录url,也就是/dashboard/login。可以想象,发生的情况是,如果登录不成功,url 仍会变为 /dashboard/home。我认为这对用户有误导性,通常只是不好的做法,但我不知道如何根据登录尝试的结果动态更改 url 。如何在尝试不成功时将 url 更改为 /dashboard/login,但在成功时将其保持为 /dashboard/home

我的文件

HTML 模板

已截断为表格。

        <form method="POST" action="{% url 'home' %}">
            {% csrf_token %}
            <div class="form">
                <label for="email" class="credentials">Email:</label>
                <input type="text" name="email" id="email" size="12" maxlength="30" />
            </div>
            <div class="form">
                <label for="password" class="credentials">Password:</label>
                <input type="password" name="password" id="password" size="12"
                    maxlength="30" />
            </div>
            <div class="submit">
                <input type="submit" name="submit" value="GET STARTED" />
            </div>
        </form>

观看次数

请原谅所有的打印功能,它们对初学者很有帮助 :) 我还尝试了一些通过上下文字典传递给模板的变量,我还没有从视图中删除这些变量(例如,"login_successful")

def portal(request):
if request.method == 'POST':
    print ("first if was executed")
    form = AuthenticationForm(request.POST)

    if form.is_valid():
        print ("second if was executed")
        username = request.POST['email']
        password = request.POST['password']
        user = authenticate(username=username, password=password)

        if user is not None:
            print("user authenticated")

            if user.is_active:
                print("user active")
                login_successful = 1
                print('login_successful: ',login_successful)
                login(request, user)
                d = (UserFields.objects.filter(userid__exact=username).values())

                d2 = d[0]
                print(d2)
                m = d2["manager"]
                am = d2["apexmanager"]
                print (m)
                print (am)
                if am==True:
                    print ("apex executed")
                    return render(request, 'dashboard/homeApexManager_new.html', {'login_error': login_successful})

                elif m==True:
                    print ("m true executed")
                    return render(request, 'dashboard/homeManager_new.html', {'login_error': login_successful})

                else:
                    print ("m false executed")
                    return render(request, 'dashboard/homeEmployee_new.html', {'login_error': login_successful})

            else:
                print("not active")
                return render(request, 'dashboard/login.html')

        else:
            print ("not authenticated")
            login_error = 1
            print (login_error)
            return render_to_response('dashboard/login.html', {'login_error': login_error})

    else:
        print ("form is not valid")
        login_error=1
        print (login_error)
        return render_to_response('dashboard/login.html', {'login_error': login_error})

else:
    print ("request is not POST")
    return render(request, 'dashboard/login.html', {'form': form})            

网址

from django.conf.urls import url
from . import views
from django.contrib.auth import views as auth_views

urlpatterns = [
    url(r'^login', auth_views.login,name = 'login'),
    url(r'^home', views.portal,name = 'home'),
        ]

正如 AMG 在他的评论中提到的那样,RightThing(tm) 要做的是在您的登录视图中处理表单提交 (POST),然后重定向到仪表板主页 url (如果表单有效且登录成功)或如果表单无效或登录失败则重新显示表单(无需重定向)。作为一般规则,这里是处理表单提交的规范方式(除了应该使用 GET 方法并且从不重定向的搜索表单):

def someformview(request, ...): 
    if request.method == "POST":
        # the user submitted the form, let's validate it
        form = SomeFormClass(request.POST)
        if form.is_valid():
            # ok, process the data and redirect the user
            do_something_with(form.cleaned_data)
            return redirect("someapp:anotherview")
        # if form is not valid just redisplay it again
        # so the user gets the error messages
    else:
        # assume a GET request: create an unbound form
        form = SomeFormClass()

   # we either had a GET request or invalid form, 
   # let's display it     
   return render(request, "someapp/someviewtemplate.html", {form:form})

根据您的问题我了解到,无论表单是否有效,您的表单都会在用户主页上重定向用户。

因此您不需要使用 action="{% url 'home' %}" 重定向用户 这意味着当提交表单时,无论是否成功登录,页面都必须在主页上重定向用户。

您必须使用您的视图进行重定向。下面我留下了例子和评论,希望对你有所帮助:

def portal(request):
  form = AuthenticationForm(request.POST)
  if request.method == 'POST': # checkout if method POST
    print ("first if was executed")
    if form.is_valid(): #checkout if form is valid
        print ("second if was executed")
        username = request.POST['email']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        return HttpResponseRedirect('/dashboard/home/') #if form is valid, it redirect user on home page
    else:
        return render(request, 'dashboard/login.html', {'form': form}) # if not valid it render this form on the same page
  else: # if method GET we just render the form
    print ("request is not POST")
    return render(request, 'dashboard/login.html', {'form': form}) 

希望对你有帮助。

更新

action 是 url 提交表单后将重定向页面的位置。因此,如果您将使用与我上面写的相同的视图,则不需要操作 url,只需保留它 action="."