我正在用头撞墙,试图设置一个通用外键。我会尽可能多地发布代码,一个小时后我会再试一次。
我已经阅读了无数次这些文档,但似乎没有任何帮助。
以下是我的看法。
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都未设置。
有明显的错误吗?
如果在commit=False(表单对象)的情况下调用save(),那么它将返回一个尚未保存到数据库的对象。但是您将继续使用对象形式,而不是模型的对象。
试试这个:
stream_instance = stream_form.save(commit=False)
stream_instance.content_object = attempt
stream_instance.save()