일반적인 외래 키를 설정하려고 벽에서 머리를 세우고 있습니다. 나는 가능한 한 많은 코드를 게시하려고하고 1 시간 후에 다시 시도 할 것입니다.Django에서 일반적인 외래 키 설정하기
설명서를 수 백만 번 읽었지만 도움이되지 않는 것 같습니다.
내가보기에 내가 한 일은 다음과 같습니다.
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 (사용 편의성을 위해 저장 기능을 사용할 수 있음)입니다. 그들은 모두가 이렇게 간단한데하지만 콘텐츠 _가, OBJECT_ID 및 content_object가 공을 재생하고 싶지 않아 내 관련 수업이
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)
모습이
class StreamForm(forms.ModelForm):
class Meta:
model = Stream
exclude = ['object_id', 'content_object']
class CommentDataForm(forms.ModelForm):
class Meta:
model = CommentData
처럼 보인다. 내가하고 싶은 것은 Comment Data 폼의 인스턴스를 생성하고 그것을 content_object 타입에 할당하는 것입니다. 나는 content_object가 아무 것도 돌려주지 않는 한 스트림과 코멘트 데이터의 인스턴스로 끝난다. (HttpResponse로 말할 수있는 한) content_type과 object id는 모두 unset이다.
눈부신 부분이 있습니까/어리석은 실수입니까?
이 필요하지 않을 수 있지만, 오류 메시지/추적, 그것은 – Parker
좀 더 쉽게 성가신 부분 그게 전부 코드를 통과 만든다합니다 도움이 될
, 나는 오류없이 정보를 제출 . 결국 StreamData 인스턴스와 CommentData의 인스턴스로 끝나지 만 함께 링크 할 수는 없습니다. – Deepak문제는 모델 정의가 아니라 웹 서버와 시스템에 설치된 다른 (이전 버전의이 모델들) 바인딩입니다. ? 즉 배포가 소프트웨어 자체가 아니라 문제입니다. –