Kaleem Qasim
Kaleem Qasim

Reputation: 37

Cant update custom model using custom form in Django

I've two models and I want to update them at the same time with one submit button. The first model is User which is from contrib models and default. Second model is UserProfile which has OneToOneField with the user. I'm making an instance of both and rendering both forms at same time. When I update, one instance (User) is updating, my custom model userprofile is not updating. Sorry, I'm new and have been figuring out what is wrong in my code.

Forms.py

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import UserProfile
from django.contrib.auth.forms import UserChangeForm

class EditProfileForm(UserChangeForm): 
      class Meta:
            model = User
            fields = ('email', 'first_name', 'last_name', 'password')

class EditProfileForm2(forms.ModelForm):
    city = forms.CharField()
    description = forms.CharField()
    phone = forms.IntegerField()

      class Meta:
          model = UserProfile
            fields = ('city','description','phone')

        def save(self, commit=True):
                user = super(EditProfileForm2, self).save(commit=False)
            user.city = self.cleaned_data['city']
            user.description = self.cleaned_data['description']
            user.phone = self.cleaned_data['phone']
            if commit:
                user.save()

            return user

Views.py

from django.shortcuts import render, redirect
from .forms import RegistrationForm, EditProfileForm, EditProfileForm2
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login, logout, authenticate
from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm
from django.contrib.auth import update_session_auth_hash

def edit_profile(request):
    if request.method == 'POST':
        form = EditProfileForm(request.POST, instance=request.user)
    if form.is_valid():
      form.save()

    form1 = EditProfileForm2(request.POST, instance=request.user)
    if form1.is_valid():
      form1.save()
      return redirect('/profile')

    else:
        form = EditProfileForm(instance=request.user)
        form1 = EditProfileForm2(instance=request.user.userprofile)
        return render(request, 'main/edit_profile.html', context={'form':form,'form1':form1})

Upvotes: 1

Views: 161

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599490

You're passing the user, rather than the userprofile, to form2 in the POST block. It should be:

form1 = EditProfileForm2(request.POST, instance=request.user.profile)

Upvotes: 2

Related Questions