Django 1.6-带重定向的可重用视图
我刚刚制作了一个可重复使用的评论应用程序,可以附加到任何模型上,请看我有问题的视图,我没有包括整个逻辑,只有一个与问题相关的 当没有request.POST时,一切正常,但是当我尝试添加注释时,在保存注释后,重定向出现了一些问题,我遇到了错误Django 1.6-带重定向的可重用视图,django,Django,我刚刚制作了一个可重复使用的评论应用程序,可以附加到任何模型上,请看我有问题的视图,我没有包括整个逻辑,只有一个与问题相关的 当没有request.POST时,一切正常,但是当我尝试添加注释时,在保存注释后,重定向出现了一些问题,我遇到了错误 dictionary update sequence element #0 has length 0; 2 is required 有问题的行是context.updatedictionary。添加评论时它看起来是空的,但我不明白为什么 我的逻辑是: 当
dictionary update sequence element #0 has length 0; 2 is required
有问题的行是context.updatedictionary。添加评论时它看起来是空的,但我不明白为什么
我的逻辑是:
当没有request.POST时,将返回view add_comment
{'comment_form':comment_form,'comments':comments}
当request.method==POST时,context.updatedictionary不应
甚至可以执行,因为返回重定向节点。结果应该是这样的
在视图概要文件中启动执行的代码,因为
重定向节点应指向
我知道我可以在profile.views.py中使用重定向,但是我需要为每个添加注释的视图执行重定向,这是非常不令人信服的
comment.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-另一个应用程序,我想通过只参考查看添加注释来减少添加注释的代码
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)
非常感谢您的快速帮助,现在它正在工作。但是我听说检查实例类型只能在最后的手段中使用:我还没有编程经验,这就是为什么我需要尽可能学习良好的实践,这就是为什么对于可重用子视图的想法,我总是试图避免重复的行,现在在每个带有附加注释的视图中,我都需要检查实例类型,也许我可以用字典更新之类的方法用对应类替换函数add_comment?再次感谢你的帮助。