django我无法使用2个外键保存表单

时间:2010-05-26 20:56:45

标签: database django forms foreign-keys

我有一个回复课程:

class Reply(models.Model):
    reply_to = models.ForeignKey(New)
    creator = models.ForeignKey(User)
    reply = models.CharField(max_length=140,blank=False)

重播表格:

class ReplyForm(ModelForm):
class Meta:
      model = Reply
      fields = ['reply']

其中New是Post类(包含用户帖子) 和视图

def save_reply(request):
   #u = New.objects.get(pk=id)
if request.method == 'POST':

    form = ReplyForm(request.POST)
    if form.is_valid():
       new_obj = form.save(commit=False)
       new_obj.creator = request.user
       new_obj.reply_to = form.reply_to
     #  reply_to_id = u
       new_post = New(2) #this works hardcoded, but how can i get the blog New post #id, as a parameter, instead?
       new_obj.reply_to = new_post
       new_obj.save()
       return HttpResponseRedirect('.')    

否则:            form = ReplyForm()
   return render_to_response('replies / replies.html',{            '形式':形式,            },           context_instance = RequestContext(request))

其中created_by属于New class并代表帖子的创建者(将被回复)

如何将当前帖子分配给它下面的回复?

提前感谢!

2 个答案:

答案 0 :(得分:2)

我可能错过了一些东西,但reply_to需要一个新模型的实例。 New.id对我来说不像一个人?

new_obj.reply_to = New.id

您是否有可以分配的新模型实例?

啊,我看到你已经调整了问题

如果您没有新模型的实例,则需要创建一个

new_post = New(whatever, goes, here)
new_post.save()

然后将其分配给reply_to

new_obj.reply_to = new_post

或类似。

修改

我不确切地知道ReplyForm看起来像是在猜测,但可能是基于Reply对象,让用户以某种方式选择reply_to字段?

假设填写了表单的reply_to变量&正确我认为你应该能做到:

form = ReplyForm(request.POST)
if form.is_valid():
   new_obj = form.save(commit=False)
   new_obj.creator = request.user
   new_obj.reply_to = form.reply_to
   new_obj.save()

事实上,因为它是外键,new_obj = form.save(commit=False)可能已经为你设置了.reply_to? Django Model Forms文档可能有所帮助。

答案 1 :(得分:1)

不确定这是否适合您的应用,但您可以尝试使用form widget,特别是HiddenInput,以在表单中包含帖子(id)。像

这样的东西
class ReplyForm(ModelForm):
    reply_to = forms.ModelChoiceField(New.objects.all(), widget=forms.HiddenField)
    class Meta:
        model = Reply
        fields = ['reply', 'reply_to']
        widgets = {
           'reply_to': HiddenField,
        }

(不确定这是完全正确的,但请参阅overriding-the-default-field-types-or-widgets了解更多信息。)

您现在已经启用了需要传递给客户端并通过表单返回的ID,现在只需要在创建表单时将其放入显示中

else: 
    form = ReplyForm()
    form.reply_to = # ... fill in the current post (New inst) being replied to
    # presumably from somewhere in the request object?
    return render_to_response('replies/replies.html', { 'form': form, }, 

希望这不会导致你走错路 - 完全未经测试,E& OE,YMMV等等