我是 django 的初学者,所以开始了我的测试项目。
有一个 home.html 提供注册或登录/注销的选项。我还创建了一个单独的应用程序registration
来处理这些请求。
设置.py
MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media').replace('\\','/')
MEDIA_URL = 'media/'
网址.py
url(r'^$', direct_to_template, {"template": "home.html",}, name="home"),
url(r'^register/', direct_to_template, {"template": "register.html",}, name="register"),
url(r'^accounts', include('registration.urls')),
base.html
<head>
<link rel="stylesheet" href="{{ MEDIA_URL }}style.css" />
</head><body>
<div style="text-align: right;">
<form action="/accounts/login" method="post">
{% csrf_token %}
<p><span>Username:</span><input type="text" name="username" /></p>
<p><span>Password:</span><input type="password" name="password"/></p>
<p><input class="submit" type="submit" value="Login" /> </p>
</form>
<a href="/accounts/logout">Logout</a>
</div>
<h1>Welcome</h1>
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
<p>Welcome, new user. Please log in.</p>
{% endif %}
{% block content %}
{% endblock %}
主页.html
{% extends "base.html" %}
{% block content %}
<p>
This is a test site. If you do not have an account, <a href="/register">Register</a>
</p>
{% endblock %}
注册.html
{% extends "base.html" %}
{% block content %}
<h1> Register </h1> <br />
<form action="/accounts" method="post">
{% csrf_token %}
<p><span>Username:</span><input type="text" name="username" /></p><br />
<p><span>Email:</span><input type="text" name="email" /></p><br />
<p><span>Password:</span><input type="password" name="password"/></p><br />
<p><span>Re-password:</span><input type="password" name="repassword"/></p><br />
<p><input class="submit" type="submit" value="Register" /> </p>
</form>
{% endblock %}
urls.py - 注册
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
url(r'^$', registerfun),
url(r'/login$', loginfun),
url(r'/logout$', logoutfun),
views.py - 注册
def registerfun(request):
#validate and obtain request parameters
if not errors:
user = User.objects.create_user(username, email, password)
user.save()
return render_to_response('home.html',{'errors':errors}, context_instance=RequestContext(request))
def loginfun(request):
#obtaion request parameters
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return render_to_response('home.html')
else:
errors.append('Account disabled')
return render_to_response('home.html',{'errors':errors}, context_instance=RequestContext(request))
else:
errors.append('Invalid username/password')
return render_to_response('home.html',{'errors':errors}, context_instance=RequestContext(request))
我面临2个问题
- css 没有加载。它在
media/style.css
. - 登录和注销时,url 从 /accounts/login 变为 /accounts/logout。我该如何避免它并使其保持在根?此外,当我在http://localhost:8000/accounts/logout页面上尝试登录时,它给了我
CSRF verification failed. Request aborted.
错误