如何从登录页面重定向到:Django中的8000 /用户名

时间:2012-12-18 09:42:15

标签: django login

我在主页上有我的登录表单,即“/”。现在从那里我想将用户重定向到0.0.0.0:8000/username,其中'username'不是静态的,它对于不同的用户我是不同的。 我是Django的初学者。请在部门解释。提前致谢

1 个答案:

答案 0 :(得分:1)

你可以做的是在你的urls.py中定义一个主页和个人资料网址。

#urls.py
url(r'^$', 'app.views.home'),
url(r'^(?P<username>\w+)/$', 'app.views.profile'),

现在在views.py下定义2个视图,一个用于呈现主页,第二个用于呈现配置文件页面

# views.py

import models
from django.shortcuts import render_to_response
from django.templates import RequestContext
from django.contrib.auth import authenticate, login

def home(request):
    """
    this is the landing page for your application.
    """
    if request.method == 'POST':
        username, password = request.POST['username'], request.POST['password']
        user = authenticate(username=username, password=password)
        if not user is None:
            login(request, user)
            # send a successful login message here
        else:
            # Send an Invalid Username or password message here
    if request.user.is_authenticated():
        # Redirect to profile page
        redirect('/%s/' % request.user.username)
    else:
        # Show the homepage with login form
        return render_to_response('home.html', context_instance=RequestContext(request))


def profile(request, username):
    """
    This view renders a user's profile
    """

    user = user.objects.get(username=username)
    render_to_response('profile.html', { 'user' : user})

现在,当请求第一个网址/时,它会将请求转发给app.views.home,这意味着主视图=== = =>&gt; views.py === =====> app申请。

主视图检查用户是否经过身份验证。如果用户通过身份验证,则会调用网址/username,否则只会在模板目录中呈现名为home.html的模板。

配置文件视图接受2个参数,1。request和2. username。现在,当使用上述参数调用配置文件视图时,它将获取所提供用户名的用户实例,并将其存储在user变量中,然后将其传递给profile.html模板。

也请仔细阅读Poll Application Tutorial on Django Project来熟悉django的力量。

:)