我试图设置通用外键,我正用头撞墙。我将尽可能多地发布代码,我会在一小时内再试一次。
我已经阅读了文档一百万次,但似乎没有帮助。
在我看来,这就是我正在做的事情。
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 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 都未设置。
有什么明显/愚蠢的错误吗?