我为帖子制作了一个模型,并且必须制作一个表单才能接受该帖子。我使用下面给出的视图生成一个表单,用于创建一个表单和编辑一个表单,如果它存在。
如果帖子存在则会有一个有效的post_id,我将选择正确的帖子对象并显示填写了字段的表单,但如果没有post_id,那么我将生成一个新的空白表单。
但是我收到错误
我做错了什么?
def post_form(request,post_id):
context_instance=RequestContext(request)
if post_id:
post = get_object_or_404(Post, pk=post_id)
else:
#if the user is authenticated then pass the user object
if request.user.is_authenticated():
post = Post(creator=request.user)
else:
post = Post()
if request.method == 'POST':
if 'save' in request.POST:
form = PostForm(request.POST, instance = post)
if form.is_valid():
form.save()
return redirect(post)
# Instantiate an empty form with the given user
else:
form = PostForm(instance = post)
return render_to_response('forum/post.html', {'form':form}, context_instance)
答案 0 :(得分:1)
看起来您需要post_id
def post_form(request, post_id=None):
...