Reputation: 3272
I try to configure the project in such a way that the user goes through the primary registration, then logged in and from the personal cabinet could add additional information about himself. There are no problems with the initial registration, but when you try to change and supplement the information, there are no changes.
My UserProfile model: models.py
from customuser.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=50, blank=True)
surname = models.CharField(max_length=50, blank=True, default = None)
avatar = models.ImageField(upload_to = 'images/profile/%Y/%m/%d/', blank=True, null=True)
position = models.ForeignKey('Position',blank=True, default=None)
role = models.ForeignKey('Role', blank=True, default=None)
company = models.ForeignKey('Company',blank=True, default=None)
status = models.ForeignKey('Status', blank=True, default=None)
@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
instance.profile.save()
forms.py
from django import forms
from django.forms import ModelForm
from client.models import Profile
class UserProfileForm(ModelForm):
class Meta:
model = Profile
exclude = ['user']
views.py
from customuser.models import User
from client.models import Profile
from .forms import UserProfileForm
def edit_user(request, pk):
user = User.objects.get(pk=pk)
form = UserProfileForm(instance=user)
if request.user.is_authenticated() and request.user.id == user.id:
if request.method == "POST":
form = UserProfileForm(request.POST, request.FILES, instance=user)
if form.is_valid():
update = form.save(commit=False)
update.user = user
update.save()
return HttpResponse('Confirm')
else:
form = UserProfileForm(instance=user)
return render(request, 'client/edit.html', {'form': form})
Upvotes: 0
Views: 2302
Reputation: 47374
UserProfileForm
is form for Profile
model, so instance passed to the form should be profile, not user. You shoud do something like this:
def edit_user(request, pk):
user = User.objects.get(pk=pk)
profile = user.profile
form = UserProfileForm(instance=profile)
if request.user.is_authenticated() and request.user.id == user.id:
if request.method == "POST":
form = UserProfileForm(request.POST, request.FILES, instance=profile)
Upvotes: 1