Django 1.6-带重定向的可重用视图



我刚刚制作了一个可重复使用的评论应用程序,可以附加到任何模型上,请查看我有问题的视图(我没有包括整个逻辑,只包括与问题相关的逻辑)。

当没有请求时。POST,一切都很好,但是当我试图添加评论时,在保存后重定向出现了一些问题,我得到了错误

dictionary update sequence element #0 has length 0; 2 is required

有问题的行是context.update(dictionary)。当添加注释时,它看起来是空的,但我不明白为什么。

我的逻辑是:

  1. 当没有请求时。POST,视图add_comment将返回{'comment_form':comment_form,'comment':comments}

  2. request.method==POST'context.update(dictionary)不应该甚至被执行,因为返回重定向(节点)。结果应该是启动在视图配置文件中执行的代码,因为这是重定向(节点)应导致.

我知道我可以在profile.views.py中使用重定向,但我需要对每个添加了注释的视图都这样做,这是非常不可信的。

评论.views.py

from django.shortcuts import redirect
from comment.forms import AddCommentForm
from comment.models import Comment
def add_comment(request, node):
    if request.user.is_authenticated():
        user = request.user
    else:
        user = None
        comment_form = None
    comments = Comment.objects.get_comments(node) # custom manager method for getting all comments
    if user:
        if request.method == 'POST':
            comment_form = AddCommentForm(request.POST)
            if comment_form.is_valid():
                comment_form.save(node=node, user=user) # custom form save method, updating missing fields
                return redirect(node) #redirect to node.get_absolute_url()
        else:
            comment_form = AddCommentForm()
    return {'comment_form': comment_form, 'comments': comments}

profile.views.py-另一个应用程序,我想通过只引用视图add_comment 来减少添加注释的代码

from django.shortcuts import render, get_object_or_404
from django.contrib.auth.models import User
from comment.views import add_comment
def profile(request, id):
    user = get_object_or_404(User, id=id)
    dictionary = add_comment(request, user)
    context = {'user': user}
    context.update(dictionary) #problematic line
    return render(request, 'profile/profile account.html', context)

问题是add_comment可以返回一些不是字典的东西:即重定向(这是HttpResponse的子类)。在使用之前,您可以随时检查返回的内容的类型:

result = add_comment(request, user)
if not isinstance(result, dict):
    return result
else:
    context.update(result)

最新更新