我正在编写一个非常简单的导航栏。例如,下面是我的登录视图。当我打开登录页面时,我可以看到我的base.html的结果,但由于某种原因,我看不到我的login.html的结果。这意味着我只能看到我写的表单的顶部链接栏。
view.py--登录视图
def login(request):
if request.method == 'POST':
form = UserLoginForm(request.POST)
if form.is_valid():
m = UserLogin.objects.get(user_name=request.POST['user_name'])
if m.password == request.POST['password']:
request.session['member_id'] = m.id
return HttpResponseRedirect('/game')
else:
c = {'form': form,
'error_message': "Your username and password didn't match."}
c.update(csrf(request))
return render_to_respons('game/login.html', c)
else:
form = UserLoginForm()
c = {'form': form}
c.update(csrf(request))
return render_to_response('game/login.html', c)
base.html
<div id="navigation">
<a href="/game">Home</a>
<a href="/game/upload">Upload</a>
<a href="/game/registration">Register</a>
<a href="/game/login">Login</a>
</div>
login.html
{% extends "base.html" %}
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="/game/login/" method="post">
{% csrf_token %}
<table border='0'>
<div class="fieldWrapper"><tr><td>
{{ form.user_name.errors }}</td><td></td></tr><tr><td>
<label for="id_user_name">User Name:</label></td><td>
{{ form.user_name }}</td></tr>
</div>
<div class="fieldWrapper"><tr><td>
{{ form.password.errors }}</td><td></td><tr><td>
<label for="id_password">Password:</label></td><td>
{{ form.password }}</td></tr>
</div>
</table>
<input type="submit" value="Login" />
</form>
您需要定义blocks
才能使用模板继承。例如,将base.html更改为:
<div id="navigation">
<a href="/game">Home</a>
<a href="/game/upload">Upload</a>
<a href="/game/registration">Register</a>
<a href="/game/login">Login</a>
</div>
{% block content %}{% endblock %}
然后将您的登录代码放入内容块:
{% extends "base.html" %}
{% block content %}
...login.html content goes here
{% endblock %}
查看文档了解更多详细信息。