使用app-engine-patch發揮Django的威力(七)

researcher

This site has been moved to dreamerslab.com

本站已經移至 dreamerslab.com

讓guestbook作用

現在讓我們添加創建和顯示guestbook條目的能力。添加如下代碼到/guestbook/views.py的末尾:

from django.views.generic.list_detail import object_list
from django.views.generic.create_update import create_object
from django.contrib.auth.decorators import login_required
from guestbook.models importGreeting

def list_entries(request):
return object_list(request,Greeting.all())

@login_required
def create_entry(request):
# Add username to POST data, so it gets set in the created model
# You could also use a hidden form field for example, but this is more secure
request.POST = request.POST.copy()
request.POST['author']= str(request.user.key())
return create_object(request,Greeting, post_save_redirect=’/guestbook’)

並更改/gustbook/urls.py:

from django.conf.urls.defaults import*

urlpatterns = patterns(”,
(r’^,’guestbook.views.list_entries’),
(r’^sign/,’guestbook.views.create_entry’),
(r’^signup/,’guestbook.views.create_new_user’),
(r’^login/,’django.contrib.auth.views.login’,{‘template_name’:'guestbook/user_create_form.html’}),
(r’^logout/,’django.contrib.auth.views.logout_then_login’,{‘login_url’:'/guestbook/’}),
)

這個generic view 期望你創建一個/guestbook/templates/greeting_list.html的模板:

<html>
<head>
</head>
<body>
<divclass=”login”>
{% if user.is_authenticated %}
Welcome, {{ user.username }}
{% if user.is_active %}
<ahref=”/guestbook/logout”>
{% else %}
<ahref=”{% google_logout_url “/guestbook/” %}”>
{% endif %}Logout</a>
{% else %}
<ahref=”{% google_login_url request.get_full_path %}”>Login with your Google account</a><br>
<ahref=”/guestbook/login”>Login with your normal account</a><br>
<ahref=”/guestbook/signup”>Sign up</a><br>
{% endif %}
</div>
{% for object in object_list %}
<p>{{object.author.username}}: {{object.content}}</p>
{% endfor %}
<ahref=”/guestbook/sign/”>Add entry</a>
</body>
</html>

and /guestbook/templates/greeting_form.html:
<html>
<head>
</head>
<body>
<formmethod=”POST”action=”.”>
{{form.content}}
<inputtype=”submit”value=”create”>
</form>
</body>
</html>

登入留言現在已經能作用了。我們已經為/guestbook/修改了generic view提供的index.html模板 ,通過引用相關函數增加了顯示留言列表功能。Django提供的login_required裝飾器能確保使用者必須登入才能訪問所請求的視圖。裝飾器默認 登入網址為/accounts/login/ ,可以在settings.py文件裡修改:

LOGIN_URL = ‘/guestbook/login’

注意:如果想要匿名使用者能夠登入留言,將考慮的事實是匿名使用者不存在關鍵屬性(key-attribute)。

參考來源

使用app-engine-patch發揮Django的威力

Related Posts


Comments are closed.