如何保存外键?
How do I save the foreign key?
我想上传多张图片。
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/ 处的完整性错误
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)
我正在从 url 传递 title_id。它适用于其他型号,但不适用于此型号。如何保存外键?
无论 commit
值如何,您都在表单的 save
方法中保存表单。第一行是 instance = super(PanelsForm, self).save()
,它将尝试保存一个 ComicIssue
实例,即使在您看来,您写了 obj = form.save(commit=False)
。
您可以做两件事:在初始化时将 title
和 user
传递给您的表单,这样表单就可以在保存期间处理这些分配。或者将表单的 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)
我想上传多张图片。
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/ 处的完整性错误 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)
我正在从 url 传递 title_id。它适用于其他型号,但不适用于此型号。如何保存外键?
无论 commit
值如何,您都在表单的 save
方法中保存表单。第一行是 instance = super(PanelsForm, self).save()
,它将尝试保存一个 ComicIssue
实例,即使在您看来,您写了 obj = form.save(commit=False)
。
您可以做两件事:在初始化时将 title
和 user
传递给您的表单,这样表单就可以在保存期间处理这些分配。或者将表单的 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)