我有下面的错误,我不知道问题是什么。 ValueError:视图bookmarks.views.bookmark_save_page未返回HttpResponse对象。它改为返回None。
以下是bookmarks.views.bookmark_save_page:
的代码def bookmark_save_page(request):
if request.method == 'POST':
form = BookmarkSaveForm(request.POST)
if form.is_valid():
link, dummy = Link.objects.get_or_create(
url = form.cleaned_data['url']
)
bookmark, created = Bookmark.objects.get_or_create(
user=request.user,
link = link
)
bookmark.title = form.cleaned_data['title']
if not created:
bookmark.tag_set.clear()
tag_names = form.cleaned_data['tags'].split()
for tag_names in tag_names :
tag, dummy = Tag.objects.get_or_create(name=tag_names)
bookmark.tag_set.add(tag)
bookmark.save()
return HttpResponseRedirect(
'/user/%s/' %request.user.username
)
else:
form = BookmarkSaveForm()
variables = RequestContext(request,{
'form' : form
})
return render_to_response('bookmark_save.html', variables)
'bookmark_save.html'的代码:
{% extends "base.html" %}
{% block title %}save your bookmark{% endblock %}
{% block head %}save your bookmark{% endblock %}
{% block content %}
<form method="post" action=".">
{{ form.as_p }}
<input type="submit" value="save" />
</form>
{% endblock %}
有什么问题?我错过了什么吗?
答案 0 :(得分:2)
您的整个代码在if
条件下缩进,因此在最初请求页面时,不会发送任何响应。您需要将最后return
移至与初始if
相同的级别:
def bookmark_save_page(request):
if request.method == 'POST':
form = BookmarkSaveForm(request.POST)
if form.is_valid():
link, dummy = Link.objects.get_or_create(
url = form.cleaned_data['url']
)
bookmark, created = Bookmark.objects.get_or_create(
user=request.user,
link = link
)
bookmark.title = form.cleaned_data['title']
if not created:
bookmark.tag_set.clear()
tag_names = form.cleaned_data['tags'].split()
for tag_names in tag_names :
tag, dummy = Tag.objects.get_or_create(name=tag_names)
bookmark.tag_set.add(tag)
bookmark.save()
return HttpResponseRedirect(
'/user/%s/' %request.user.username
)
else:
form = BookmarkSaveForm()
variables = RequestContext(request,{
'form' : form
})
return render_to_response('bookmark_save.html', variables)
您还可以进一步简化代码:
from django.shortcuts import render, redirect
def bookmark_save_request(request):
form = BookmarkSaveForm(request.POST or None)
if form.is_valid():
# .. your logic here
return redirect('/user/%s' % (request.user.username,))
return render(request, 'bookmark_save.html', {'form': form})