Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

EditUserForm() create a new user insted of editing the correct one in Django

I’m new to Django and I’m building my first website. I’m now in the phase of creating the register/edit profile pages.

I have correctly created my register page but I’m having a hard time creating the edit profile page. My profile has the classic fields username, first name, last name, email, password. On my edit page, I would like to be able to modify only the email field.

For some reason, instead of editing the current user, my edit profile page creates a new user with every field blank except for the one I’ve edited.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My code can be found below.

urls.py

urlpatterns = [
    path('register', views.register_user, name="register"),
    path('account', views.account_user, name="account"),
]

views.py

@unauthenticated_user
def register_user(request):
    if request.method == "POST":
        form = RegisterUserForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data['username']
            password = form.cleaned_data['password1']
            user = authenticate(username=username, password=password)
            login(request, user)
            messages.success(request, "Registration Succesfully")
            # ogni utente è associato ad un gruppo univoco
            Group.objects.get_or_create(name=username)
            group = Group.objects.get(name=username)
            group.user_set.add(user)
            user.save()
        else:
            pass
    else:
        form = RegisterUserForm()
    return render(request, 'authenticate/register_user.html', {
        'form': form,
    })

@authenticated_user
def account_user(request):
    if request.method == "POST":
        form = EditUserForm(request.POST)
        if form.is_valid():
            form.save()
        else:
            pass
    else:
        form = EditUserForm()
    return render(request, 'authenticate/account.html', {
        'form_edit': form,
    })

forms.py

class RegisterUserForm(UserCreationForm):
    email = forms.EmailField(widget=forms.EmailInput(attrs={
        'class':'form-control'
    }))
    first_name = forms.CharField(max_length=25, widget=forms.TextInput(attrs={
        'class':'form-control'
    }))
    last_name = forms.CharField(max_length=30, widget=forms.TextInput(attrs={
        'class':'form-control'
    }))

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2')

    def __init__(self, *args, **kwargs):
        super(RegisterUserForm, self).__init__(*args, **kwargs)

        self.fields['username'].widget.attrs['class'] = 'form-control'
        self.fields['password1'].widget.attrs['class'] = 'form-control'
        self.fields['password2'].widget.attrs['class'] = 'form-control'


class EditUserForm(UserChangeForm):
    password = None
    username = None

    email = forms.EmailField(widget=forms.EmailInput(attrs={
        'class': 'form-control'
    }))

    class Meta:
        model = User

        # select the fields that you want to display
        fields = ('email',)

register.html

<div class="shadow p-3 mb-5 bg-body rounded">
    {% if form.errors %}
        <svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
          <symbol id="exclamation-triangle-fill" fill="currentColor" viewBox="0 0 16 16">
            <path d="M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0-2z"/>
          </symbol>
        </svg>
        <div class="alert alert-danger d-flex align-items-center" role="alert">
          <svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-label="Danger:"><use xlink:href="#exclamation-triangle-fill"/></svg>
          <div>
            There was an error with your form...
          </div>
        </div>
    {% endif %}

<form action="{% url 'register' %}" method=POST>
{% csrf_token %}
{{ form }}
    <br><br>
<input type="submit" class="btn btn-secondary">
</form>
</div>

edit.html

<div class="shadow p-3 mb-5 bg-body rounded">
    {% if form.errors %}
        <svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
          <symbol id="exclamation-triangle-fill" fill="currentColor" viewBox="0 0 16 16">
            <path d="M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0-2z"/>
          </symbol>
        </svg>
        <div class="alert alert-danger d-flex align-items-center" role="alert">
          <svg class="bi flex-shrink-0 me-2" width="24" height="24" role="img" aria-label="Danger:"><use xlink:href="#exclamation-triangle-fill"/></svg>
          <div>
            There was an error with your form...
          </div>
        </div>
    {% endif %}

<form action="{% url 'account' %}" method=POST>
{% csrf_token %}
{{ form_edit }}
    <br><br>
<input type="submit" class="btn btn-secondary">
</form>
</div>

>Solution :

You’ve to pass instance of your object to edit it like this

@authenticated_user
def account_user(request):
    if request.method == "POST":
        form = EditUserForm(request.POST, instance=request.user)
        if form.is_valid():
            form.save()
        else:
            pass
    else:
        form = EditUserForm(instance=request.user)
    return render(request, 'authenticate/account.html', {
        'form_edit': form,
    })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading