Django ModelForm with extra fields that are not in the model

后端 未结 7 482
甜味超标
甜味超标 2021-01-31 02:00

I have done a ModelForm adding some extra fields that are not in the model. I use these fields for some calcualtions when saving the form.

The extra fie

7条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-31 02:41

    It's possible to extend Django ModelForm with extra fields. Imagine you have a custom User model and this ModelForm:

    class ProfileForm(forms.ModelForm):
    
        class Meta:
            model = User
            fields = ['username', 'country', 'website', 'biography']
    

    Now, imagine you want to include an extra field (not present in your User model, lets say an image avatar). Extend your form by doing this:

    from django import forms
    
    class AvatarProfileForm(ProfileForm):
    
        profile_avatar = forms.ImageField()
    
        class Meta(ProfileForm.Meta):
            fields = ProfileForm.Meta.fields + ('profile_avatar',)
    

    Finally (given that the form has an ImageField), remember to include request.FILES when instantiating the form in your view:

    # (view.py)
    
    def edit_profile(request):
        ...
        form = AvatarProfileForm(
            request.POST or None, 
            request.FILES or None, 
            instance=request.user
        )
        ...
    

    Hope it helps. Good luck!

    EDIT:

    I was getting a "can only concatenate tuple (not "list") to tuple" error in AvatarProfileForm.Meta.fields attribute. Changed it to a tuple and it worked.

提交回复
热议问题