简体   繁体   中英

Django update user profile

I am facing a lot of problems to update a user profile as customer.

Problems:

  • No errors showing
  • Only Email, Address and Birthday are updating
  • Want to update First name and last name in user

if there is any short way to this kind of update profile, please let me know or please try to help with this code. Thank you.

models.py

from django.db import models
from django.contrib.auth.models import User


class SignupUser(models.Model):
    user = models.OneToOneField(User)
    address = models.CharField(blank=False, max_length=200)
    birthday = models.DateTimeField('Birthday')

    def __str__(self):
        return self.address


User.profile = property(lambda u: SignupUser.objects.get_or_create(user=u)[0])

forms.py

from django import forms
from django.contrib.auth.models import User
from signup.models import SignupUser

class UpdateProfile(forms.ModelForm):
    class Meta:
        model = SignupUser
        fields = ['address', 'birthday']


class UpdateUser(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'email']


    def clean_email(self):
        email = self.cleaned_data['email']
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError('This is not your email')

        return email

views.py

def editprofile(request):
    if request.method == 'POST':
        profileup = UpdateProfile(request.POST or None, instance=request.user.profile)
        if profileup.is_valid():
            profileup.save()
            userup = UpdateUser(request.POST or None, instance=request.user)
            if userup.is_valid():
                user = userup.save(commit=False)
                user.first_name == request.POST['first_name']
                user.save()
            return HttpResponseRedirect('/authority/editprofile/')
    else:
        user = request.user
        profile = user.profile
        userup = UpdateUser(instance=user)
        profileup = UpdateProfile(instance=profile)

    args = {
        'userup': userup,
        'profileup': profileup, 
    }
    return render(request, 'auth/editprofile.html', args)

Try add else clause after if userup.is_valid() to get more info for the error. But i suggest you use class based view UpdateView

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM