如何预填充纯ImageFields的内联formset?

时间:2017-11-08 08:03:01

标签: django django-models django-forms django-templates django-views

我有两个模型:ProfileCredentialImage

我已经实现了inlineformsets,允许Profile上传最多5张图片(CredentialImage)。

目前,图像会保存到数据库,但是当我重新访问更新表单时它们不会预先填充,从而允许用户一次上传无限量的照片5。理想情况下,保存到数据库的相同图像将预填充在表单上,​​以限制配置文件一次只拥有和编辑5张照片。

根据我的理解,我需要将对象传递给页面以预先填充信息,我相信我通过定义get_object来做到这一点。

以下是两种模式:

class Profile(models.Model):
    ...
    def get_absolute_url(self):
        return reverse("profile:profile_detail",
                       kwargs={"username": self.user})

class CredentialImage(models.Model):
    profile = models.ForeignKey(Profile, default=None, 
        related_name='credentialimage')
    image = models.ImageField(upload_to=credential_photo_upload_loc)  

informformset_factory的模型形式+初始化:

from django.forms.models import inlineformset_factory

class ProfileUpdateForm(ModelForm):
    class Meta:
        model = Profile
        fields = [
            "introduction",
            "biography",
        ]

class CredentialImageForm(ModelForm):
    image = ImageField()

    class Meta:
        model = CredentialImage
        fields = ['image', ]

CredentialImageFormSet = inlineformset_factory(Profile,
    CredentialImage, fields=('image', ), extra=4, max_num=4)  

用于更新个人资料的基于类的UpdateView:

class ProfileUpdateView(LoginRequiredMixin, UpdateView):
    form_class = ProfileUpdateForm
    template_name = 'profile/profile_edit.html'

    def get_context_data(self, **kwargs):
        context = super(ProfileUpdateView, self).get_context_data(**kwargs)
        if self.request.POST:
            context['credential_image'] = CredentialImageFormSet(self.request.POST, self.request.FILES)
        else:
            context['credential_image'] = CredentialImageFormSet()
        return context

    def get_object(self, *args, **kwargs):
        user_profile = self.kwargs.get('username')
        obj = get_object_or_404(Profile, user__username=user_profile)
        return obj

    def form_valid(self, form):    
        data = self.get_context_data()
        formset = data['credential_image']
        if formset.is_valid():
            self.object = form.save()
            formset.instance = self.object
            formset.save()
            return redirect(self.object.get_absolute_url())

        instance = form.save(commit=False)
        instance.user = self.request.user
        return super(ProfileUpdateView, self).form_valid(form)

1 个答案:

答案 0 :(得分:1)

您必须在get_context_data方法中提供实例。

def get_context_data(self, **kwargs):
    context = super(ProfileUpdateView, self).get_context_data(**kwargs)
    if self.request.POST:
        context['credential_image'] = CredentialImageFormSet(self.request.POST, self.request.FILES, instance=self.object)
    else:
        context['credential_image'] = CredentialImageFormSet(instance=self.object)
    return context