[Python] Django view doesn't save form changes

Discussão em 'Python' iniciado por Stack, Maio 15, 2025.

  1. Stack

    Stack Membro Participativo

    Django 5.2, python 3.12.5 . I'm using in-built user model and no errors appear when I press the submit button. I created a view based on UpdateView and use the built-in UserChangeForm. The form actually returns 200 response code. I suspect something is wrong with how the form is bound or saved, but I see no errors or warnings. Urls are okay. My other login/register forms work well.

    views.py

    from django.views import generic
    from django.contrib.auth import login
    from django.contrib.auth.forms import AuthenticationForm, UserCreationForm, UserChangeForm
    from django.contrib.auth.mixins import LoginRequiredMixin
    from django.contrib.auth.models import User

    class ProfileView(generic.edit.UpdateView, LoginRequiredMixin):
    template_name = 'users/profile.html'
    form_class = UserChangeForm
    success_url = '/profile/'
    model = User

    def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['title'] = 'Profile | Jotter'
    return context

    def form_valid(self, form):
    form.save()
    return super().form_valid(form)

    def get_form_kwargs(self):
    kwargs = super().get_form_kwargs()
    kwargs['instance'] = self.request.user
    return kwargs

    def get_object(self):
    return self.request.user


    profile.html

    {% extends "base.html" %}

    {% block content %}
    <main class="py-5">
    <div class="container">
    <div class="row">

    <form action="" method="post" class="col-md-6 mx-auto">
    {% csrf_token %}

    <h2 class="mb-5">Account details</h2>


    <div class="row mb-4">

    <div class="col-md-4 mx-2">
    <label for="username_label" class="form-label">Username</label>
    <input type="text" class="form-control" style="background: #dfdfdf;" id="username_label" name="username" value="{{form.username.value}}" readonly>
    </div>

    </div>


    <div class="row mb-5">

    <div class="col-md-4 mx-2">
    <label for="first_name_label" class="form-label">First name</label>
    <input type="text" class="form-control" id="first_name_label" name="first_name" value="{{form.first_name.value}}">
    </div>

    <div class="col-md-4 mx-2">
    <label for="last_name_label" class="form-label">Last name</label>
    <input type="text" class="form-control" id="last_name_label" name="last_name" value="{{form.last_name.value}}">
    </div>

    </div>


    <div class="row">

    <div class="col-md-4 mx-2">
    <button type="submit" class="btn btn-primary">Save changes</button>
    </div>

    </div>

    </form>
    </div>
    </div>
    </main>
    {% endblock content %}


    Honestly, no clue.

    Continue reading...

Compartilhe esta Página