Unable to update user profile.

I’m following a YouTube tutorial for making a Twitter clone with Django. This web app has various functionalities exactly similar to Twitter. Just doing it to improve my Django & other skills.
In this project, there is a function in views.py to update the user profile within each individual profile. Posting the function here:

# Updating User Info
def update_user(request):
        if request.user.is_authenticated:
            current_user = User.objects.get(id = request.user.id)
            form = SignUpForm(request.POST or None, instance = current_user)
            if form.is_valid():    # This is where I think I'm facing issue
                form.save()
                messages.success(request, ('Your Profile Is Updated.'))
                return redirect('home')

Then there is a button to save changes which are updated. The changes do not get saved even after I click on that. It prompts A user with this username already exists. I debugged the code in VS Code and I think the problem is with if form.is_valid() condition. Because I’ve observed program always skips this condition. It tempts me to think is there an issue with django.contrib.auth.forms module/library?

As comments under this tutorial on YouTube are saying older version of Django (4.1.4 to be precise) was not having this error so they tell everyone to downgrade Django version. I don’t want that. Can it be solved?

Thank you.

Highly unlikely. This is almost certainly either an error in the tutorial or a mistake in the code that you are runnin.

Please post the complete view and the definition of SignUpForm.

Thanks for answering. Almost all Comments under tutorial were suggesting this. So I thought that might be the case.
By the way, here are my code snippets for your reference.
forms.py for SignUpForm:

class SignUpForm(UserCreationForm):
    email = forms.EmailField(label='', 
                             widget=forms.TextInput(
                                 attrs={
                                     'class':'form-control',
                                     'placeholder':'Your Valid Email Address',
                                 }))
    first_name = forms.CharField(label='',
                                 max_length=50,
                                 widget=forms.TextInput(
                                     attrs={
                                         'class':'form-control',
                                         'placeholder':'Your First Name',
                                     }))
    last_name = forms.CharField(label='',
                                 max_length=60,
                                 widget=forms.TextInput(
                                     attrs={
                                         'class':'form-control',
                                         'placeholder':'Your Last Name',
                                     }))
    
    class Meta(UserCreationForm.Meta):
        model = User
        fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2']

    def clean(self):     # This method is written as suggested by ChatGPT
        cleaned_data = super().clean()
        instance = getattr(self, 'instance', None)
        if instance and instance.pk:
            username = cleaned_data.get('username')
            if username == instance.username:
                del cleaned_data['username']
    
        return cleaned_data

I also saw one comment or two suggesting to change UserCreationForm to UserChangeForm. Doing that also rose issues.
And,
Here is complete snippet for update_user() method:

def update_user(request):
        if request.user.is_authenticated:
            current_user = User.objects.get(id = request.user.id)
            print(current_user)
            form = SignUpForm(request.POST or None, instance = current_user)
            if form.is_valid():
                form.save()
                login(request, current_user)
                messages.success(request, ('Your Profile Is Updated.'))
                return redirect('home')

            print(form.errors)
            return render(request, 'update_user.html', {'form':form})
        else:
            messages.success(request, ('You must login to proceed.'))
            return redirect('home')

If there are some problems, please do tell.

Ok, let’s take a step back here for a moment.

What exactly are you looking for this view to do?

You wrote:

But the code being used here appears to be attempting to modify the User, not a user’s profile. (Side note: The word “profile” has a very specific meaning within Django - see Customizing authentication in Django | Django documentation | Django)

If you’re just trying to update the data fields within an existing user, then you should be using UserChangeForm and not UserCreationForm.

You then wrote:

Which just means that those issues need to be addressed.

Finally, whenever you’re looking for tutorials or other educational material for Django, use GitHub - wsvincent/awesome-django: A curated list of awesome things related to Django as a resource to find resources. Don’t just rely upon what you find on the internet as being any good. In particular, you especially want to pay attention to when the material was prepared. The older the blog, book, or video, the more likely it’s going to contain information that is invalid. You really need to be finding current information.

Alright. It worked!
I defined a new class for updating the user info namely UpdateUserForm(UserChangeForm) instead of using SignUpForm() (& messing the code up as well) class with the new class body almost as same as latter. Now it’s working correctly.
Thank you so much for valuable time & wisdom.

1 Like