提交表单时视图未返回HttpResponse对象

时间:2014-09-28 06:50:13

标签: django django-forms

我有下面的错误,我不知道问题是什么。 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 %}

有什么问题?我错过了什么吗?

1 个答案:

答案 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})