Django - get_context_data() 缺少 1 个必需的位置参数:'form'



我正在尝试将inlineformset添加到Django博客项目中。我得到了帖子,我想通过基于类的视图将多个图像添加到帖子中。但当我尝试获取_context_data时,我收到了以下错误:

get_context_data((缺少1个必需的位置参数:"form">

Models.py:

class Post(models.Model):
title = models.CharField(max_length=100)
content = RichTextField(blank=True, null=True)
class PostImage(models.Model):
post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE)
image = models.ImageField(upload_to='gallery/')
description = models.CharField(max_length=300, blank=True)

Forms.py

class CreatePostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title' , 'content' ]
PostImageFormSet = inlineformset_factory(Post, PostImage, fields=['image', 'description'], exclude=['post'] , max_num=30, extra=3)

Views.py

class PostCreateView(LoginRequiredMixin, CreateView):
form_class = CreatePostForm
template_name = 'blog/post_form.html'
def get_context_data(self, form):
context = super(PostCreateView. self).get_context_data(**kwargs)
if self.request.POST:
context['post_images'] = PostImageFormSet(self.request.POST)
else:
context['post_images'] = PostImageFormSet()
return context
def form_valid(self, form):
context = self.get_context_data(form=form)
formset = context['post_images']
form.instance.author = self.request.user
if formset.is_valid():
response = super().form_valid(form)
formset.instance = self.object
formset.save()
return response
else:
return super().form_invalid(form)

知道我为什么会收到这种错误吗?非常感谢。

您应该删除form参数。无论如何,该表单从未在get_context_data中使用:

class PostCreateView(LoginRequiredMixin, CreateView):
form_class = CreatePostForm
template_name = 'blog/post_form.html'
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
if self.request.POST:
context['post_images'] = PostImageFormSet(self.request.POST)
else:
context['post_images'] = PostImageFormSet()
return context
def form_valid(self, form):
context = self.get_context_data()
formset = context['post_images']
form.instance.author = self.request.user
if formset.is_valid():
response = super().form_valid(form)
formset.instance = self.object
formset.save()
return response
else:
return super().form_invalid(form)

相关内容

  • 没有找到相关文章

最新更新