Nikhil Gupta
Nikhil Gupta

Reputation: 386

How to edit user profile in Django

I'm trying to create an "Edit Profile" form in the fronted. What happens is that my form(i'm not 100% sure) tries to create a user instead of finding the current user and update his profile. So I think that's the issue. Checked many questions here but none was clear enough. The fields I'm trying to edit are email(to be checked if email already exisit), Name, user type, and password.

below is the code for forms.py

class ProfileForm(forms.ModelForm):
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ('full_name', 'active', 'admin','email','user_type')

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super(ProfileForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        # user.active = False # send confirmation email
        if commit:
            user.save()
        return user

code for views.py

def profile(request):
    user = User.objects.filter(email = request.user)
    # form = ProfileForm(user.values().first())
    if request.method == 'POST' :
        form = ProfileForm(request.POST)
        if form.is_valid():
            form.save(commit=True)
    form = ProfileForm(user.values().first())
    # print(user)
    context = {
    'object_list': user,
    'form': form
    }
    return render(request, 'userpanel/profile.html',context)

Thanks in advance

Upvotes: 0

Views: 3131

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47354

You didn't pass instance argument to the form. Without instance it will try to create new object. It should be like this:

form = ProfileForm(request.POST, instance=user)

Also you don't need to query user with this: user = User.objects.filter(email = request.user). Just add login_requred decorator to ensure user is authenticated and use request.user:

from django.contrib.auth.decorators import login_required

@login_required
def profile(request):
    if request.method == 'POST' :
       form = ProfileForm(request.POST, instance=request.user)

Upvotes: 1

Related Questions