[Django]-Django modelForm, need to save only selected fields

3๐Ÿ‘

โœ…

I solved this finally. No need to changhe save() method.
Here the changes:

def cabinet(request):

    profile_user = CustomUser.objects.filter(pk = request.user.pk)
    profile = CustomUser.objects.get(pk = request.user.pk)


    if request.method == 'POST':
        form = ProfileForm(request.POST, request.FILES or None,     instance=profile)   
        if form.is_valid():
            form.save()
    else:
        form = ProfileForm(instance=profile)

    return render(request, 'cabinet.html', 
    {'form':form, 'profile_user': profile_user, 'rating':rating,}, )

But I still have problem with avatar widget

๐Ÿ‘คIvan Semochkin

3๐Ÿ‘

You just need to remove the additional fields from the cleaned_data before you save it.

Override the save method, and remove them from there an it should work fine.

class ProfileForm(forms.ModelForm):

    # skip initial details

    def save(self, commit=True):
        self.cleaned_data = dict([ (k,v) for k,v in self.cleaned_data.items() if v != "" ])
        return super(ProfileForm, self).save(commit=commit)
๐Ÿ‘คuser764357

Leave a comment