Django- User Profile Management Django by Ravinder Nath Rajotiya - January 13, 2022January 20, 20220 Share on Facebook Share Send email Mail Print Print Table of Contents Toggle User Profile Managementstep-1 : create a new user profile model Create Models.py inside users appStep-2: do migrations commanda) run makemigrations.b) Run django migrate commandNow run migrate command which will apply the changes to the database.step-3 : Register the Profile modelStep-4: Working with image from Django shallstep-5: update settings.pystep-6: DISPLAY all this in our profile pagestep-7: add media url to urlpattern of project folderstep-8: Final TouchStep-10: Test in Browser User Profile Management In the previous tutorial Django-User Login and Logout users able to login and logout. There was no user profile when they login. We need to have a user profile. Default Django view model does not have a feature to add user profile picture, We can do it by extending the user model to add more fields, In this tutorial we’ll learn how to use Django signals to run specific functions after certain actions which can be extremely useful for this type of work. We will extend user profile and create a profile model that will have a one-to-one relationship with the user. One-to-one relationship means that one user can have one profile and one profile will be associated with one user. To do this we will make use of following steps- step-1 : create a new user profile model Create Models.py inside users app from django.db import models from django.contrib.auth.models import User class profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE ) here the second argument is on-delete which tells django what to do with profile if user is deleted. models.CASCADE means if user is deleted then delete the profile as well. But if the Profile is deleted, the user will not be deleted. So, it is a one way. This simply means, if we delete a user from the database, then there is no reason to have the images or any other stuff etc, that will also delete. But if the profile is deleted, user should be able to update the profile at any time. With the above code, now we have a user associated with this profile, we can create any field like image for the . Let us create a filed ‘image’profile image = models.ImageField(default=’default.jpg’, upload_to = ‘profile_pic’) this will upload an image to the ‘profile_pic’ folder. Django will a default image if not provided by user. Let us also create dunder/or magic function so that when we print this it will display how we want it to be displayed. def __str__(self): return f’{self.user.username}Profile’ It will print username when this function return the Profile. When we make any change to profile, it will also make the same changes to the database. Step-2: do migrations command We have to run migrations for changes in database. So bring up the terminal and run migrations as: a) run makemigrations. On ubuntu 20.04 system, makemigrations command was a success, but on windows system we get an error when we run makemigrations. Pillow is a library for working with images in Python. We need to install Pillow. You can now run the migrations command. b) Run django migrate command Now run migrate command which will apply the changes to the database. Now when you open the admin page, you won’t be able to see this profile on the admin page. The solution is to register the profile model on the admin.py file in our users app. step-3 : Register the Profile model Inside the admin.py update from django.contrib import admin from .models import Profile admin.site.ragister(Profile) Now run the server, open the admin page and then click on add profile You can now add profile pictures for all user As an exercise, add image to admin profile and leave default for others. Let us now see how we can pull these profiles. Step-4: Working with image from Django shall >>> from django.contrib.auth.models import User >>> user = user.objects.filter(user=’username’).first() >>> user <user : ravinder> # will display whatever username is in profile for User #now access profile for user >>> user.profile <profile : username Profile> >>> user.profile.image <ImageFieldFile : profile_pic/picname.jpg> #it is in profile_pic folder # we can also access the attribute of the image such as: >>>user.profile.image.width 1536 # like wise we can access height etc # for location we can use url attribute of image >>> user.profile.image.url ‘profile_pic/pic.jpg’ We can also upload image for any other user, but we need to first select the user as >>> user = user.objects.filter(username = ‘baibhav’).first() >>>user <user: baibhav> # we find that user exist in database, so let us see profile image >>>user.profile.image <ImageFieldFile : default.jpg> # there is a default image set in profile Let us start the development server, you can check in the project folder there is a directory profile_pic, we use this directory to upload image. But this is not a good place as images but multiple models may get jumbled up in image root directory. step-5: update settings.py So we change the settings for where these images are saved for multiple users/models. So that our website find these images when we open different profiles Go to settings.py and scroll down to the end #static files and append #MEDIA_ROOT is where we want Django to store uploaded file. #For performance reasons these files are saved in file system and not in the database. MEDIA_ROOT is uploaded directory where uploaded files will be saved, so let us keep in the base directory of our project and put it in a directory say MEDIA. So profile_pic directory will be created inside directory in media directory which is created in the base folder of project, so let us do it as: MEDIA_ROOT = os.path.join(BASE_DIR, ‘media’), argument BASE_DIR is created by Django which specify the project base directory MEDIA_URL is the public path of that directory, this is how we access the media through the browser We set MEDIA_URL =’/media/’ Go to admin page and delete previous profiles created if any, add profile again for users and save You can now check and verify the directory created in the base project folder Delete old profile_pic directory that was created earlier inside project base folder step-6: DISPLAY all this in our profile page We want the user profile page profile.html to display username, email, profile pic, …..so on for a user # paste profile snippet here which is as typed below {% extends ‘blog/base.html %} {% block contents %} <div class=” content-section”> <div class=” media”> <img class=”rounded-circle account-img” src = “{{ user.profile.image.url }}” > <div class=”media-body”> <h2 class =”account-heading”>{{ user.username }}</h2> <p class= ”text-secondary”>{{ user.email }}</p> </div> </div> </div> {% endblock content %} step-7: add media url to urlpattern of project folder Verify how to do as given in django online documentation – Serving files uploaded by a user during development from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # … the rest of your URLconf goes here … ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) We can add as it is in our file OR as we in debug mode, we as an alternate can also do as: urlpatterns = [ # … the rest of your URLconf goes here … ] if settings.DEBUG: urlpatterns+= static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) This will allow media to work in our browser This will work fine. But for users with default image, you also have to upload the default image also in the media folder You can just copy paste a default.jpg in the media folder inside your project. That will do. Now the main project folder should have the media as : step-8: Final Touch We now want that whenever a new user is created they automatically get a new default picture in their view Right now, we have to go the admin page and create the profile of the users, but that should not be the way of doing it: Let us do it: For this wat all we need it to : add a Django signal, create a new file in our users app called signals.py from django.db.models.signals import post_save # import built in User model and the user model here will be sender and the sender will be one who is sending the signals and we also need to create a receiver one that is functions who is going to be the signal that will perform some function from django.contrib.auth.models import User from django.dispatch import receiver # import profile from .models import Profile # let us now write a function Profile @receiver(post_save, sender=User) #means when a user is saved, send a signal and that signal will be received by the receiver. # the receiver is the create_profile function def create_profile(sender, instance, created,**kwargs): If created: Profile.objects.create(user=instance) # to tie the functionality together, so at top of function add. This profile function will run every time a user is created # let us also create a receiver @receiver(post_save, sender=User) def save_profile(sender, instance, ,**kwargs): instance.profile.save() last step is import our signal inside the ready() function in users apps.py file from django.apps import AppConfig class userConfig(AppConfig): name=’users’ def ready(self): import users.signals Step-10: Test in Browser Now let us pull our browse Create new user, sign up Login as a new user. Go to profile of the user and you can see the default image of the user in place Share on Facebook Share Send email Mail Print Print