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

Dee*_*pak 3 python forms django 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)
Run Code Online (Sandbox Code Playgroud)

这些表单都是 ModelForm(为了便于使用,所以我可以使用保存功能)。他们看起来像这样

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

class CommentDataForm(forms.ModelForm):
    class Meta:
        model = CommentData
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

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

有没有什么明显的/多么愚蠢的错误?

Ale*_*voy 5

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

\n\n

尝试这个:

\n\n
stream_instance = stream_form.save(commit=False)\nstream_instance.content_object = attempt\nstream_instance.save()\n
Run Code Online (Sandbox Code Playgroud)\n