A Django Blog In VS Code — Upload Profile Picture
How To Create A Blog in VS Code — Part VI— DjangoSeries Episode # 09
Hi, in this post we’re going to be learning how to add the ability to upload profile picture for our users.
Let’s go ahead and get started!
00#Step — This is a continuation of this post.
In the previous episode we saw how to create an authentication system for our Django application so that users can log in log out.
Here is WHAT WE PLAN TO DO IN THIS POST:
The first thing we need to do is extending the user model that we currently have to add more fields.
The User default models that Django provides to us does not include picture.
How can we can add more fields to User model?
Answer: we going to extend the User model and create a one to one relationship with the user.
01#Step —Let’s create our users_hub/model.py
file, type:
from django.db import models
from django.contrib.auth.models import Userclass Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg',
upload_to='profile_pics') def __str__(self):
return f'{self.user.username} Profile'
02#Step —To deal with images we need Pillow. What is it?
GoTo Terminal, and type:
pip install Pillow(djangoEnv) C:\Users\giljr\new_django\django_project>pip install Pillow
Collecting Pillow
Downloading Pillow-9.0.1-cp39-cp39-win_amd64.whl (3.2 MB)
|████████████████████████████████| 3.2 MB 547 kB/s
Installing collected packages: Pillow
Successfully installed Pillow-9.0.1[optional]
pip install --upgrade pip
03#Step — Let’s migrate our Profile table.
In Terminal, type:
python manage.py makemigrationsMigrations for 'users_hub':
users_hub\migrations\0001_initial.py
- Create model Profilepython manage.py migrateOperations to perform:
Apply all migrations: admin, auth, blog, contenttypes, sessions, users_hub
Running migrations:
Applying users_hub.0001_initial... OK
04#Step — GoTo DB Browser for SQLite and confirm user_hub_profile
table was created:
python manage.py sqlmigrate users_hub 0001 BEGIN;
--
-- Create model Profile
--
CREATE TABLE "users_hub_profile" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "image" varchar(100) NOT NULL, "user_id" integer NOT NULL UNIQUE REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED);
COMMIT;
05#Step — Now let’s register our new model to our admin
dashboard:
users_hub/admin.py
, type:
from django.contrib import admin
from users_hub.models import Profileadmin.site.register(Profile)
06#Step — Now, to test, in your Terminal, type:
python manage.py runserver
07#Step — Open /admin
dashboard route, and add 2 profiles:
One for j3
user by adding a pic:
And the other to UserTest2
with no pic:
08#Step — Now stop the server and run the Django Shell
:
python manage.py shell Python 3.9.7 (default, Sep 16 2021, 16:59:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth.models import User
>>> user=User.objects.filter(username='j3').first()
>>> user.profile
<Profile: j3 Profile>
>>> user.profile.image
<ImageFieldFile: profile_pics/logo.jpg>
>>> user.profile.image.width
149
>>> user.profile.image.height
138
>>> user.profile.image.size
12031
>>> user.profile.image.url
'/profile_pics/logo.jpg'
>>> user=User.objects.filter(username='userTest2').first()
>>> user
<User: userTest2>
>>> user.profile.image
<ImageFieldFile: default.jpg>
>>> exit()
Here we can see that the user
and profile
models have a relationship. See that the user j3
(/profile_pics/logo.jpg
) has a pic associated with and the userTest2
has a default.jpg
.
I don't think this is a good location to image, because it will clattered up our root directory.
Let’s change some settings so that we can change location where the images will be actually saved. We can change this default pics save location to media directory. Let’s go ahead…
How can we change location of the pics? Open settings.py
!
09#Step — GoTo django_project/settings.py
type at the very end of the file:
...
STATIC_URL = ''import osMEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
10#Step —Run the server, and return to Admin
dashboard, and delete the 2 profile added at step #07
and repeat the procedure and add the 2 profiles again so that the change will take effect.
11#Step — Now GoTo django_project/media
and confirm the new directory was created successfully: media/profile_pics/logo.jpg
12#Step — Now Modify users_hub/templates/users_hub/profile.html
to:
Just one more thing we need to do to provide the correct location of the image: add the media routes in our patterns configs.
Go to this link to more official info about static files:
# Static files (CSS, JavaScript, Images)https://docs.djangoproject.com/en/4.0/howto/static-files/
13#Step —Modify your django_project\urls.py
file to:
14#Step — Log in to j3
profile and you see the new brand profile page:
But if you logout from j3
and login as userTest2
you will see this:
15#Step — Save an default image .jpg
inside the claimed directory:
django_project/media/default.jpg
Reload the page:
16#Step —Every time a User
is created let’s create a Profile
. For this, create users_hub/signals.py
file, and paste it:
Signals are basically comprised of senders and receivers that send out some information to a receiver or whenever something has occurred.
Here we are introducing you to the concept of Django Signals and show you how signals can really help simplify a lot of our code whenever we have multiple bits of code interested in the same event.
So every single User is created in my system it is going to have a Profile so every single time a User is created or updated I want a sender to be sent out and either create or update the profile also.
17#Step — Modify users_hub/apps.py
:
18#Step —Let’s create another userTest4
:
19#Step — Using tailwind CSS , as a final detail to modify our blog\templates\blog\base.html
{% if user.is_authenticated %}
<ul>
<li class="nav-item">
<img class="w-8 h-8 md:h-auto rounded-full mx-auto"
src="{{ user.profile.image.url }}">
</li>
</ul>
{% endif %}
20#Step — And there you have it! as we have planned \o/
That’s all Folks!
In the next #DjangoSeries Episode we will Update & Resize Picture.
See you around. Bye!
👉 git
Related Posts
00#Episode — DjangoSerie — Django Intro — How To Build your First App in Python Django Framework — DjangoSeries
01#Episode — DjangoSerie — Django MTV In VS Code — How To Install Django Inside Virtual VS Code
02#Episode — DjangoSerie — Can You Solve This in Python? — Here is A Basic Python Question!
03#Episode — DjangoSerie — JUNGLE-DJANGO Webpage! This Is My New Django Netflix Clone Page!
04#Episode — DjangoSerie — A Django Blog In VS Code — Quick Start! — Part_I
05#Episode — DjangoSerie — A Django Blog In VS Code — Database, Migrations & Queries — Part_II
06#Episode — DjangoSerie — A Django Blog In VS Code — Bootstrap, Tailwind CSS — Part_III
07#Episode — DjangoSerie — A Django Blog In VS Code — Forms & Validations — Part_IV
08#Episode — DjangoSerie — A Django Blog In VS Code — Login & Logout — Part_V
09#Episode — DjangoSerie — A Django Blog In VS Code — Upload Profile Picture — Part_VI (this one :)
10#Episode — DjangoSerie — A Django Blog In VS Code — Update & Resize Picture — Part_VII
11#Episode — DjangoSerie — A Django Blog In VS Code — Class-Based-View & CRUD — Part_VIII
12#Episode — DjangoSerie — A Django Blog In VS Code — Posts Pagination & Quick DB Population — Part_IX
13#Episode — DjangoSerie — A Django Blog In VS Code — Self-Service Django Password Reset — Part_X
14#Episode — DjangoSerie — A Django Blog In VS Code — Heroku Deploy — How To Push Your Site To Productio — Part_XI (this last one…whew!)
Credits & References
Python Django Tutorial: Full-Featured Web App by Corey Schafer
Signals by djangoproject.com
HowTo Run this Tutorial - From the Scratch - In your Machine:)Annotations: Quick Start - video #TakeTheFirstStepToLearnDjango0 - Download DJG_<previous>/Django_project from my git repo;
1 - On your desktop, create a dir and named it as Tutorial_#;
2 - Inside this paste the previous Django_project file;
3 - GoTo vscode Terminal (command prompt) and ...
4 - Run this quick_script
(copy/paste inside you terminal and hit enter and wait until
Pillow is up and running...):python -m venv djangoEnv
djangoEnv\Scripts\activate
python -m pip install --upgrade pip
python -m pip install django
python -m django --version
pip install django-crispy-forms
pip install Pillow5- GoTo Step#01 of this tutorial.And you are good to go!