0
我需要在我的項目的每個頁面上都有登錄表單,並且我正在使用inclusion tags來實現它。 Django的文檔和像this one一些例子,我寫了下面的代碼至今:在包含標籤的每個頁面上登錄:示例和疑惑
項目樹:
myProj ├── myProj │ └── settings.py ├── celeryPy2 │ ├── forms.py │ ├── templatetags │ │ └── my_tags.py │ ├── urls.py │ └── views.py └── templates ├── base.html └── celeryPy2 ├── login.html └── start.html
urls.py
from django.contrib.auth.views import login, logout urlpatterns = patterns('celeryPy2.views', url(r'^$', 'start', name='start'), url(r'^accounts/login/$', login, name='login'), url(r'^accounts/logout/$', logout, {'next_page':'/celeryPy2'}, name='logout'), )
意見。 py
def start(request): return render_to_response('celeryPy2/start.html', {}, context_instance=RequestContext(request))
的start.html
{% extends "base.html" %} {% block title %}celeryPy2 start page{% endblock title %} {% block content %} {% load my_tags %} {% login_form %} {% endblock content %}
base.html文件
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head><meta charset="utf-8" /><title>celeryPy2</title></head> <body> <div id="header">{% block header %}{% endblock %}</div> <div id="content">{% block content %}{% endblock %}</div> <footer id="footer">{% block footer %}{% endblock %}</footer> </body> </html>
my_tags.py
from django import template register = template.Library() from celeryPy2.forms import UserForm @register.inclusion_tag('celeryPy2/login.html', takes_context=True) def login_form(context): form = UserForm user = context['user'] return {'form': form,'user': user}
forms.py
class UserForm(ModelForm): class Meta: model = User fields = ('username','password')
的login.html
{% if not user.is_authenticated %} <form id="idLogInForm" method="post" action="{% url 'django.contrib.auth.views.login' %}?next=/celeryPy2" class="loginForm">{% csrf_token %} {{ form.as_p }} <button id="idLogInSubmit" name="idLogInSubmit" type="submit">Login</button> </form> {% else %} <form id="idLogOutForm" method="post" action="{% url 'django.contrib.auth.views.logout' %}">{% csrf_token %} <span id="welcomeUserId" class="welcomeUserClass">Welcome, <strong>{{ user.username }}</strong></span> <button id="idLogOutSubmit" name="idLogOutSubmit" type="submit">Logout</button> </form> {% endif %}
我有以下問題和疑惑:
- 那是一個正確的方式來實現,否則我可以得到安全問題?
- 當我插入錯誤的用戶憑據時,我正確地得到錯誤
Please enter a correct username and password. Note that both fields may be case-sensitive.
和瀏覽器url欄設置爲/celeryPy2/accounts/login/?next=/celeryPy2
。但是如果我嘗試重新登錄,它會嘗試訪問不存在的網址/accounts/profile/
。爲什麼?我必須說我的settings.py中沒有LOGIN_URL
或LOGIN_REDIRECT_URL
。 [解決,見下] - 爲什麼我得到的密碼輸入字段與明文,而不是蒙面字符隱藏,因爲它應該是? [求助,見下]
- 爲什麼我會在username輸入字段旁邊得到標籤
Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters
? [已解決,見下文]
這是我發現有一個代碼插件在每一頁重用,是能夠以更符合內置功能的Django的方式。它對我來說看起來有點棘手(涉及很多文件),可能還有一些細節尚未完善,但我發現這是完成任務的最簡單方法。 任何其他更好想法是歡迎的!
我已經解決了點2,3和4與下面報告的代碼更正。只有點1仍然打開... – caneta