Django - allow user to edit profile and then show updated profile fields

I have a form filling out user profile information, but when I click Save, it doesn't actually update.

Any hints / hints as to which part I need to change would be greatly appreciated.

Thanks in advance!

def profile_view(request):
    user = request.user
    form = EditProfileForm(initial={'first_name':user.first_name, 'last_name':user.last_name})
    context = {
        "form": form
    return render(request, 'profile.html', context)

def edit_profile(request):

    user = request.user
    form = EditProfileForm(request.POST or None, initial={'first_name':user.first_name, 'last_name':user.last_name})
    if request.method == 'POST':
        if form.is_valid():

            user.first_name = request.POST['first_name']
            user.last_name = request.POST['last_name']

            return HttpResponseRedirect('%s'%(reverse('profile')))

    context = {
        "form": form

    return render(request, "edit_profile.html", context)

class EditProfileForm(forms.ModelForm):

    first_name = forms.CharField(label='First Name')
    last_name = forms.CharField(label='Last Name') 

    class Meta:
        model = User
        fields = ['first_name', 'last_name']



{% extends "base_site.html" %}

{% block content %}

<h1>Edit Profile</h1>

<form method="POST" action="/accounts/profile/" class="" />
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Save</button>

{% endblock %}

from django.conf.urls import url
from . import views

urlpatterns = [

    url(r'^register/$', 'accounts.views.registration_view', name='auth_register'),
    url(r'^login/$', 'accounts.views.login_view', name='auth_login'),
    url(r'^logout/$', 'accounts.views.logout_view', name='auth_logout'),
    url(r'^profile/$', 'accounts.views.profile_view', name='profile'),
    url(r'^profile/edit/$', 'accounts.views.edit_profile', name='edit_profile'),



source to share

1 answer

The action in your form is POST

ing profile_view

, not edit_profile

, and your forms get closed, so they are not correct POST


Change this:

<form method="POST" action="/accounts/profile/" class="" />


For this:

<form method="POST" action="/accounts/profile/edit" class="" >


Or even better, use the django url template tag :

<form method="POST" action="{% url 'edit_profile' %}" class="" >




All Articles