如何更新表单集

时间:2020-05-01 12:33:13

标签: django django-class-based-views inline-formset

我用django 2.2创建了一个网络博客,每个帖子都有多个图像,但是当我尝试更新该帖子时,这些图像不会更新 我使用基于类的视图

class Post(models.Model):
    user= models.ForeignKey(Account,on_delete=models.CASCADE)
    title= models.CharField(max_length=100)
    #others

class PostImage(models.Model):
    post= models.ForeignKey(Post,on_delete=models.CASCADE,related_name='images')
    media_files = models.FileField(upload_to=random_url)

这是我的表格。py

class PostImageForm(forms.ModelForm):
    class Meta:
        model = PostImage
        fields = [
            'media_files'
        ]
class PostUpdateForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = [
           'title','description',#and others
        ] 

我的views.py

PostImageFormSet = inlineformset_factory(
Post,PostImage,form=PostImageForm,extra=1,can_delete=True,can_order=False
) 

class PostUpdateView(LoginRequiredMixin,UserPassesTestMixin,UpdateView):
    model = Post
    form_class = PostUpdateForm
    template_name = 'posts/update_post.html'
    def get_context_data(self,**kwargs):
        data = super().get_context_data(**kwargs)
        if self.request.POST:
            data['images'] = PostImageFormSet(self.request.POST or None,self.request.FILES,instance=self.object)
        else:
            data['images'] = PostImageFormSet(instance=self.object)
        return data
    def form_valid(self,form):
        context = self.get_context_data()
        images = context['images']
        with transaction.atomic():
            if form.is_valid() and images.is_valid():
                self.object = form.save()
                images.instance = self.object
                images.save()
        return super().form_valid(form)
    def test_func(self):
        post = self.get_object()
        if self.request.user.username == post.user.username:
            return True
        return False
    def get_success_url(self):
        return reverse_lazy('post:post-detail',kwargs={'slug':self.object.slug})

我的模板

<form enctype="multipart/form-data" method="post" action="">
        {% csrf_token %}
        {{images.management_form }}
        {{ form|crispy }}
        {% for img in images %}
            <label>{{img.media_files.label}}</label>
              {{img.media_files}}
        {% endfor %}
            <button type="submit" class="btn btn-block btn-primary">update</button>
    </form>

它仅保存帖子形式而不保存图像,不影响图像形式 谢谢

1 个答案:

答案 0 :(得分:1)

我认为不是写作:

images.instance = self.object 

请尝试以下操作:

我注意到您使用的表格是有效的,因此它可能略有不同,但是如果您稍作更改,它应该可以使用。

form = PostUpdateForm(request.POST)
if form.is_valid():
    cd = form.cleaned_data
    images = cd.get('images')

或使用您当前的设置(尚未测试)

if form.is_valid()//删除此部分->和images.is_valid():

   if form.is_valid():
        self.object = form.save()
        instance = self.object
        cd = form.cleaned_data
        images = cd.get('images')
        images.save()