python - 在仍然理智的情况下在 Django 中设置通用外键

标签 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(为了方便使用,所以我可以使用保存功能)。他们看起来像这样

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

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

我的相关类(class)是这样的

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 和对象 ID 都未设置。

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

最佳答案

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

试试这个:

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

关于python - 在仍然理智的情况下在 Django 中设置通用外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26534672/

相关文章:

php - 如何从输入其他字段中检索 'id' 列

python - 使用 Python 将数组中的负值替换为 0 并将大于 1 的值替换为 1 的最快方法是什么?

python - Matplotlib 热图标签

python - 如何使用Paramiko exec_command获取每个依赖的命令执行输出

django - Django模型表格-设置必填字段

python - Jenkins API URL 与名为 "api"的模块冲突

python - 从文本文件解析/循环 JSON 对象 (Python)

django - 如何使地理领域独一无二?

javascript - 显示选定的复选框在 javascript 中不起作用

javascript - 表单提交被完全忽略