在Django中设置通用外键,同时仍然保持理智

时间:2014-10-23 18:17:54

标签: python django forms generic-foreign-key

我正试图设置一个通用的外键,撞到墙上。我会发布尽可能多的代码,然后我会在一小时内再次尝试。

我已经阅读了一百万次文档,但它似乎没有帮助。

以下是我在我看来所做的事情。

def create_stream(request):
    stream_form = StreamForm()
    comment_form = CommentDataForm()

    if request.POST:    
        stream_form = StreamForm(request.POST)
        comment_form = CommentDataForm(request.POST)    
        if stream_form.is_valid() and comment_form.is_valid():

            attempt = comment_form.save()

            stream_form.save(commit=False)
            stream_form.content_object = attempt
            stream_form.save()

            return HttpResponseRedirect('/main/')
        else:
            HttpResponse('Nope')

    context = {'form1':stream_form, 'form2':comment_form}
    template = 'nregistration.html'
    return render(request, template, context)

表单都是ModelForms(为了便于使用,所以我可以使用save函数)。他们看起来像这样

class StreamForm(forms.ModelForm):
    class Meta:
        model = Stream
        exclude = ['object_id', 'content_object']

class CommentDataForm(forms.ModelForm):
    class Meta:
        model = CommentData

我的相关课程看起来像这样

class Stream(models.Model):
    uid = models.CharField(max_length=20, null=True, blank=True)
    str_type = models.CharField(max_length=120, default='ABC')
    creator = models.ForeignKey(User, related_name="author", null=True, blank=True)
    parent = models.ForeignKey('self', related_name="child_of", null=True, blank=True)
    create_timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)


    limit = models.Q(app_label='picture', model='commentdata') | models.Q(app_label='picture', model='repsonsedata')

    content_type = models.ForeignKey(ContentType,verbose_name='content page',limit_choices_to=limit,null=True,blank=True)
    object_id = models.PositiveIntegerField(verbose_name= 'related object',null=True)
    content_object = GenericForeignKey('content_type', 'object_id')

    def __unicode__(self):
        return self.uid 

    class Meta:
        unique_together = ('uid',)

class CommentData(models.Model):
    uid = models.CharField(max_length=20, null=True, blank=True)
    contents = models.CharField(max_length=120, default='ABC')  
    create_timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)

class ResponseData(models.Model):
    uid = models.CharField(max_length=20, null=True, blank=True)
    contents = models.CharField(max_length=120, default='ABC')  
    create_timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)

这一切看起来都很简单但是content_type,object_id和content_object并不想玩球。我想要做的是创建一个Comment Data表单的实例,并将其分配给content_object类型。我最终得到了一个流和注释数据的实例,其中content_object没有返回任何内容(据我所知,HttpResponse)并且content_type和object id都未设置。

是否有明显的/傻瓜错误?

1 个答案:

答案 0 :(得分:4)

如果使用commit = False(在表单对象中)调用save(),则它将返回尚未保存到数据库的对象。但是你继续使用对象形式而不是模型的对象。

试试这个:

stream_instance = stream_form.save(commit=False)
stream_instance.content_object = attempt
stream_instance.save()