在第二个表单中自动包含外键

时间:2015-11-09 13:36:38

标签: django python-3.x

我正在尝试在ReviewComments模型中使用主键与同一网页内的ReviewPhoto模型中的外键进行链接。

Model.py

class ReviewComments(models.Model):
    comment_id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=120)
    comment = models.CharField(max_length=250)
    receipt_document = models.FileField(upload_to='receipt_document', default=None, )
    service_provider = models.ForeignKey(ServiceProvider)
    user_id = models.CharField(max_length=10, null=True, blank=True, )

class ReviewPhoto(models.Model):
    photo_id = models.AutoField(primary_key=True)
    photo_description = models.CharField(max_length=255)
    photo = models.ImageField(upload_to='review_photo', default=None)
    review_comments = models.ForeignKey(ReviewComments)

Views.py

def form_review_view(request):
    if request.method == 'POST':
        form_1 = ReviewForm(request.POST, request.FILES)
        form_2 = PhotoForm(request.POST, request.FILES)
        if form_1.is_valid() and form_2.is_valid():
            form_1.save()
            form_2.save()
            return redirect('index_view')
        else:
            return render_to_response(
                'form_review.html',
                {'form_1': form_1, 'form_2': form_2},
                context_instance=RequestContext(request),
            )
    else:
        form_1 = ReviewForm()
        form_2 = PhotoForm()
        return render_to_response(
            'form_review.html',
            {'form_1': form_1, 'form_2': form_2},
            context_instance=RequestContext(request),
        )

Forms.py

class ReviewForm(ModelForm):
    class Meta:
        model = ReviewComments
        fields = ['title', 'comment', 'service_provider', 'receipt_document', ]
        widgets = {
        'title': Textarea(attrs={'cols': 80, 'rows': 1}),
        'comment': Textarea(attrs={'cols': 80, 'rows': 10}),
        }
        ordering = ['service_provider', ]


class PhotoForm(ModelForm):
    class Meta:
        model = ReviewPhoto
        fields = ['photo_description', 'photo', ]

但是,我无法将表格发布为" review_comment" ReviewPhoto中的字段不会自动获取" comment_id" ReviewComments中的字段。有没有解决这个问题的方法?

1 个答案:

答案 0 :(得分:1)

您应该发布表单。但我认为这就是你想要的:

if form_1.is_valid() and form_2.is_valid():
    review = form_1.save()
    photo = form_2.save(commit=False)
    photo.review_comments = review
    photo.save()

还要考虑使用比form_1form_2更具描述性的名称。