Django:如何在HtpResponseRedirect中发送参数

时间:2016-08-21 08:47:00

标签: python django django-templates django-views django-urls

Views.py

from django.shortcuts import render
from django.template.context_processors import csrf
from  django.http import HttpResponseRedirect
from  django.shortcuts import render_to_response

from .models import studentDetails
from .forms import loginForm

# Create your views here.


def login(request):
    c = {}
    c.update(csrf(request))
    return render(request, "login.html", c)

def auth_view(request):
    username = request.POST.get("username", "")
    password = request.POST.get("password", "")

    q = studentDetails.objects.get(name=username)

    if q.password==password:
        return  HttpResponseRedirect("/student/accounts/loggedin")

    return  HttpResponseRedirect("/studemt/accounts/invalid")



def loggedin(request):
    username = request.GET.get("username")
    return  render(request, "loggedin.html", {"full_name": username})


def invalid(request):
    return  render(request, "invalid_login.html")


def logout(request):
    return  render(request, "logout.html")

Urls.py

from django.conf.urls import url
from django.contrib import admin
from .views import (
    login,
    auth_view,
    loggedin,
    logout
    )


urlpatterns = [
    url(r"^accounts/login/$", login ,  name="login"),
    url(r"^accounts/auth/$", auth_view ,name="auth_view"),
    url(r"^accounts/loggedin/$", loggedin , name="loggedin"),
    url(r"^accounts/logout/$", logout, name="logout"),

]

我想将auth_view的用户名发送到登录视图,但我不知道该怎么做。  我使用过username = request.GET.get("username")但它无效。 我想在网址中显示用户名,使其看起来像/student/username/ 其中用户名将随着不同的用户登录而变化。

1 个答案:

答案 0 :(得分:0)

您应首先在url中传递参数:

url(r'^student/(?P<username>\w+)/$', views.userpage, name='userpage)

但最好使用pk字段或name + pk字段作为url parametr,因为用户名可以重复。
现在您可以在视图中传递此参数并且不要使用硬核网址,而是使用带有网址名称的reverse

def auth_view(request):
    username = request.POST.get("username", "")
    password = request.POST.get("password", "")

    q = studentDetails.objects.get(name=username)

    if q.password==password:
        return  HttpResponseRedirect(reverse('userpage', args=[q.username]))

    return  HttpResponseRedirect(reverse('invalid'))