Part-12

Adding Update Profile Feature:Django

Update user profile

Let’s make the images auto resize when users upload them and add a new feature for the users to update their profile info.

So first create a UserUpdateForm in users/forms.py (as we want to show it on profile page)

This lets our form know that we want to work with username and email fields,and i’ven’t added profile picand bio here, because the model for them is Profile so it’ll be in ProfileUpdateForm.So import the profile model and add this class

UserUpdateForm will allow us to update our username and email and the ProfileUpdateForm will allow us to update our profile image and bio.And now in users/views.py to render it in our templates,import the forms from forms.py and then in profile view, instantiate these forms as

Here we are rendering a form if there was a POST request just like the registration form and the request.POST and request.FILES recieves the data.The instance parameter will populate the forms with the available data and then we check for form validation ,save it and redirects the user to the profile page with a flash message.

NOTE: redirect causes the browser to send a get request instead of post request to avoid the confirm reload page popup

Now we’re going to put the fields for both of these forms into a single HTML form so that the user sees it as one

Note that request.FILES will only contain data if the request method was POST and the <form> that posted the request has the attribute enctype="multipart/form-data". Otherwise, request.POST will be empty.

enctype='multipart/form-data' is an encoding type that allows files to be sent through a POST.

And now, lets resize the uploaded images,

the super().save() runs the save method for Parent class and then we use the Image class {present in the Python Image Library} to open image using Image.open() method by passing the path of the currently uploaded image (using the pic attribute of the class)

the img.mode checks if the palette is RGBA and converts it to RGB and img.thumbnail will resize the image and then img.save(path) saves the image on the same path

You can override the older images with the uploaded using django-cleanup. install django-cleanup and under installed apps add this line of code..
'django_cleanup',
]

Design your profile page with css and bootstrap..

Posting Django Tutorials with Beginner to Advanced Projects

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store