如何保存外键?

时间:2017-11-22 08:33:38

标签: python django django-uploads

我想上传多张图片。

class IssuePanel(models.Model):
    issue = models.ForeignKey(ComicIssue, on_delete=models.CASCADE)
    panel = models.FileField(upload_to='comic_issues_files/panels/')
    date_uploaded = models.DateTimeField(auto_now_add=True)

在关注github上django-multiupload的存储库上的示例后,我在forms.py上有这个

class PanelsForm(forms.ModelForm):

class Meta:

    model = ComicIssue
    fields = ('issue', 'issue_title', 'issue_cover', 'issue_description', 'issue_cover', 'issue_file')

panels = MultiFileField(min_num=1, max_num=20, max_file_size=2048*2048*5)

def save(self, commit=False):
    instance = super(PanelsForm, self).save()
    for each in self.cleaned_data['panels']:
        IssuePanel.objects.create(panel=each, issue=instance)
    return instance

views.py

class ComicIssueCreate(LoginRequiredMixin, CreateView):
    model = ComicIssue
    slug_field = 'comicseries_id'
    form_class = PanelsForm

    def form_valid(self, form):
        obj = form.save(commit=False)
        obj.title = ComicSeries.objects.get(id=self.kwargs['pk'])
        obj.user = self.request.user
        obj.save()
        return redirect('comics:series_detail', pk=obj.title.id, slug=obj.title.slug)

urls.py

url(r'^comic/issue/(?P<pk>[0-9]+)/add/$', views.ComicIssueCreate.as_view(), name='comic-issue-add'),

但是,我收到此错误 在/ comic / issue / 21 / add /中的IntegrityError NOT NULL约束失败:comics_comicissue.title_id

class ComicIssue(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, 
        null=True, blank=True, verbose_name='Uploaded by: '
    )
title = models.ForeignKey(ComicSeries, on_delete=models.CASCADE, verbose_name='Series Title')
issue = models.CharField(verbose_name='Issue Number', max_length=500)
issue_title = models.CharField(verbose_name='Issue Title', max_length=1000)
issue_cover = models.ImageField(verbose_name='Issue cover', upload_to='comic_issues', height_field=None, width_field=None, max_length=None)
issue_description = models.TextField(verbose_name='Description')
issue_file = models.FileField(verbose_name='Issue file', upload_to='comic_issues_files', max_length=100,
    help_text='File in pdf or as single image', null=True, blank=True
)
date_added = models.DateTimeField(auto_now_add=True, null=True)
is_favorite = models.BooleanField(default=False)
issue_slug = models.SlugField(default='')

class Meta:

    verbose_name = 'Comic Issue'
    verbose_name_plural = 'Comic Issues'

def __str__(self):
    return '{}: {} issue number - {}'.format(self.title.title, self.issue_title, self.issue)

def save(self, *args, **kwargs):
    self.issue_slug = slugify(self.issue_title)
    super(ComicIssue, self).save(*args, **kwargs)

def get_absolute_url(self):
    return reverse('comics:issue_detail', kwargs={'issue_slug':self.issue_slug,'pk': self.pk})

ComicIssue模型中的此功能是否会成为问题,因为它也会在错误页面上突出显示:

def save(self, commit=False, *args, **kwargs):
        self.issue_slug = slugify(self.issue_title)
        super(ComicIssue, self).save(*args, **kwargs)

我从网址传递了title_id。它正在研究其他型号而不是这个。如何保存外键?

1 个答案:

答案 0 :(得分:0)

无论save值如何,您都会使用表单的commit方法保存表单。第一行是instance = super(PanelsForm, self).save(),它会尝试保存ComicIssue个实例,即使您在视图中写了obj = form.save(commit=False)

您可以做两件事:在初始化时将titleuser传递给您的表单,以便表单可以在保存期间处理这些内容。或者将表单的save方法更改为:

def save(self, commit=False):
    instance = super(PanelsForm, self).save(commit=commit)
    if commit:
        for each in self.cleaned_data['panels']:
            IssuePanel.objects.create(panel=each, issue=instance)
    return instance

然后您的观点需要两次调用表单的save()方法(请注意,表单的instance是通过引用传递的,因此在视图中更改它也会更改表单的instance) :

def form_valid(self, form):
    obj = form.save(commit=False)
    obj.title = ComicSeries.objects.get(id=self.kwargs['pk'])
    obj.user = self.request.user
    form.save()
    return redirect('comics:series_detail', pk=obj.title.id, slug=obj.title.slug)