Sean Peterson
Sean Peterson

Reputation: 378

Django update already existing user information

OK so I have the registration working where users enter their username, email, first/last name.

My question is how do I then give the user the ability to edit their email, first/last names?

Thanks!

Upvotes: 1

Views: 3268

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174624

There is nothing special about the default django user. In fact, the django auth application is a normal django application that has its own models, views, urls and templates just like any other app you would write.

To update any model instance - you can use the generic UpdateView, which works like this:

  1. You create a template which will show the form that will be used to update the model.
  2. You can (optionally) create your own form class to be used - this is not required.
  3. You pass the model to be updated along with an instance to this view.
  4. The view takes care of the rest of the logic.

Here is how you implement it in practice. In your views.py:

from django.views.generic.edit import UpdateView
from django.core.urlresolvers import reverse_lazy
from django.contrib.auth.models import User

class ProfileUpdate(UpdateView):
    model = User
    template_name = 'user_update.html'
    success_url = reverse_lazy('home') # This is where the user will be 
                                       # redirected once the form
                                       # is successfully filled in

    def get_object(self, queryset=None):
        '''This method will load the object
           that will be used to load the form
           that will be edited'''
        return self.request.user

The user_update.html template is very simple:

<form method="post">
  {% csrf_token %}
  {{ form }}
  <input type="submit" />
</form>

All that's left now is wiring it up in your urls.py:

from .views import ProfileUpdate

urlpatterns = patterns('',
                       # your other url maps
                       url(r'^profile/', ProfileUpdate.as_view(), name='profile'),
)

Upvotes: 1

Related Questions