[Django]-Django edit user profile

23👍

You are very close. When you are instantiating the form, you need to pass the User object you are modifying as the instance argument.

From the docs:

A subclass of ModelForm can accept an existing model instance as the
keyword argument instance; if this is supplied, save() will update
that instance.

In your code, it would look like:

form = UpdateProfile(request.POST, instance=request.user)
if form.is_valid():
    ...

You can checkout more info here: https://docs.djangoproject.com/en/1.6/topics/forms/modelforms/#the-save-method

9👍

Or if you wanna go the Class Based View way, using the UpdateView, you could do something like this in views.py:

class UpdateProfile(UpdateView):
    model = MyProfile
    fields = ['first_name', 'last_name', 'image', 'url', 'biography', '...'] # Keep listing whatever fields 
    # the combined UserProfile and User exposes.
    template_name = 'user_update.html'
    slug_field = 'username'
    slug_url_kwarg = 'slug'

where you have something like this for MyProfile in models.py:

class MyProfile(AbstractUser):
    image = models.ImageField(upload_to='uploads/profile/')
    url = models.URLField()
    biography = models.CharField(max_length=1000)

and your urls.py like so (assuming you’re using django allauth and wanna honor the url convention):

....
url(r'^accounts/update/(?P<slug>[\-\w]+)/$', views.UpdateProfile.as_view(), name='update_user'),
....

The rest is Django fun! I’ll recommend you write less code if you could for basic CRUD tasks, unless its really necessary to do something custom, of which even you still can get away by extending the Class Based Views.

And in case you’re in for more, see here: Django Docs on Class Based Views

👤KhoPhi

Leave a comment