2012-12-18 28 views

回答

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

現在,當第一個URL /要求它請求轉發到app.views.home哪些表示主視圖===在===> views.py ===在===>app應用程序中。

主視圖檢查用戶是否被認證。如果用戶通過身份驗證,則會調用url /username,否則它只會在模板目錄中呈現名爲home.html的模板。

配置文件視圖接受2個參數,1.請求和2.用戶名。現在,當使用上述參數調用配置文件視圖時,它將獲取所提供用戶名的用戶實例,並將其存儲在user變量中,然後將其傳遞給profile.html模板。

也請通讀非常容易的Poll Application Tutorial on Django Project來熟悉django的力量。

:)

+0

但是,問題是,當我點擊提交在「/」,其中做指導,即會在什麼樣的行動=「?」。 –

+0

它取決於您想要處理登錄的位置,請將'action ='屬性留空。如果你想要主視圖來處理登錄。我已更新答案以處理表單發佈中的登錄,然後重定向用戶。看一看。 – Amyth

+0

謝謝,解決了問題.......我在我的url pattens的順序有問題。我保留動態網址結束,它解決了問題 –

相關問題