Published in


A Django Blog In VS Code — Update & Resize Picture

How To Create A Blog in VS Code — Part VII— DjangoSeries Episode # 10

In this Post we’ll:

- Update User Profile;
- Finishing up our user profile page;
- Making it so that users can update their information from this page, such as:
- Upload a new profile picture;
- Automatically resized the picture when the user upload it so that way you can improve page speed and its overall system performance.

Let's get Started!

00#Step — This is a continuation of this post.

In the previous episode we saw how to create a user profile page.

This time we will improve it:

Django is MTV. In this post we will update User /profile/ page by inserting forms to save and update its own information. Forms are basically used for taking input from the user in some manner and using that information for logical operations on databases. For example, Registering a user by taking input as his name, email, password, etc. Django maps the fields defined in Django forms into HTML input fields (templates)

01#Step —Open users_hub\forms.py, and add these lines:

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from users_hub.models import Profile
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email']
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image']

Okay so now we have two forms here.

A user update form and a profile update form.

The user form will allow us to update our user name and email and the profile form will allow us to update our image but whenever we actually put this on the template it’s going to look like just one form.

Okay so with those forms created let’s open up our views so that we can add these forms to our profile view.

02#Step — GoTo users_hub\views.py, and add these lines:

from multiprocessing import context
from django.shortcuts import render, redirect
# from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
from users_hub.forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
from django.contrib.auth.decorators import login_required

def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
messages.success(request, f'Hi {username}! Your account has
been created! Now login!')
return redirect('login')
form = UserRegisterForm()
return render(request, 'users_hub/register.html', {'form': form})

def profile(request):
u_form = UserUpdateForm()
p_form = ProfileUpdateForm()
context = {
'u_form': u_form,
'p_form': p_form
return render(request, 'users_hub/profile.html', context)

Here we are just passing the forms objects to the template, profile.html.

03#Step — go to users_hub/templates/users_hub/profile.html , and copy/paste this html to it:

Just be aware of these points:

1 -<form method=”POST” enctype=’’multipart/form-data”>

Do not forget that! if you leave that out then it can look like your form is working but it all that won’t actually be saving the image in the background.

2- {{ u_form|crispy }} {{ p_form|crispy }}

Two forms will be rendered at the same time. For user, it will appears as one form.

So far, so good! so with those changes made let’s see what this looks like in our browser.

04#Step — run the server:

python manage.py runserver
And route to /profile page…and There you have it! Awesome! Fantastic! Just Fine!

You see that we do not pre-populate the form. Let’s fix it!

05#Step — Copy And Paste this code inside your old users_hub\views.py, and you are good to go!

The bulk modification was on def profile() method. We just import each forms, instantiate it, validate it (we only allow our code to continue if the submitted form is valid) and pass all to the context then they will show up when Django render them.

Just be aware of these points:

1-In p_form we are passing to template the text and files are included for the data to populate the user profile; Whereas in u_formthere is only text.

2- as soon we validate it, we redirect as a GET method to profile page. This is called the Post-Get Redirect Pattern (pgrp). Now you might not know what that is but most of you have probably seen it before so if you’ve ever reloaded your browser after submitting a form and then a weird message comes up that says are you sure… it sucks...

This forced redirection (return redirect('profile') will cause the browser to make a GET request instead of POST request. No weird message again \o/

06#Step — Reload the page:

And there you have it! As you can see you can submit two forms on the same page… but the action that each form calls will be different (i.e.UserUpdateForm will handle the fields username and email while ProfileUpdateForm will deal with the image)

We can see that it filled in our current username and email so that’s good and our current profile picture too.

Now let’s change some information around…and see whether the code is working or not…

07#Step — Let’s recast our usertest2 profile to make sure that the code works correctly:

Username: userTest2_recast
Email: ut2_recast@company.com
Image* Currently: profile_pics/female-avatar_XyS8Fcd.jpg

And here is the result:

It seems to be working fine.

08#Step — Now we want to go into the admin section and make sure all of this looks good:

There you have it! Everything is looking fine! We have no clue about UserTest2, but remains info about Usertest2_recast. and This Is What We Want \o/
Please also check the profiles here so if we go into profiles we can be sure we no longer have userTest2 but userTes2_recast! This confirms correctness of our code. Let’s go ahead!

Large image issue :/ How to deal with it?

We want to show you how you can automatically resize images when you upload them. This will Improve server response. for sure

09#Step — Let’s resize our image. Modify users_hub\models.py to:

from django.db import models
from django.contrib.auth.models import User
from PIL import Image
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg',
def __str__(self):
return f'{self.user.username} Profile'

def save(self):
img = Image.open(self.image.path)
if img.height > 150 or img.width > 150:
output_size = (150, 150)

10#Step — Now let’s load a new image to usertTest4 and see if it working...

Here is the result:

Everything is fine…the image was resized to fit to 150x150…
…we can you can quickly check the size…just fine!

The last modification is in the home page. Let’s put the image logo at each post so people can recognize your business when they visit your post.

11#Step —For this, modify blog/templates/blog/home.html to:

The only modification was <img> tag. See that each Post has a author, which Profile has an Image, which Image has an url…

Here is the final result:

The Profile page is good enough!
Each post is identify by authors logo image. Awesome! Thanks for reading this! See you in the next episode…

That’s all Folks!

In the next #DjangoSeries Episode we will see about Class-Based-View & CRUD.

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

10#Episode — DjangoSerie — A Django Blog In VS Code — Update & Resize Picture — Part_VII (this one :)

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

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
python -m pip install --upgrade pip
python -m pip install django
python -m django --version
pip install django-crispy-forms
pip install Pillow
5- GoTo Step#01 of this tutorial.And you are good to go!




J of Jungle + 3 Plats Arduino/RPi/Pic = J3

Recommended from Medium

Get Historical Chart For Currency Exchange Rates With An API

My Disability Is Dynamic

Gaka-chu. The Robot-artist. Part 3: the sequence of tasks execution on the manipulator


This Global IP Database API Catches Area Location Quickly

Guide to Resources

Merge Data In Realm ( IOS Development )

Contributing limited/specific amount of storage as a slave to the Hadoop Cluster!!

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


Hi, Guys o/ I am J3! I am just a hobby-dev, playing around with Python, Django, Lego, Arduino, Raspy, PIC, AI… Welcome! Join us!

More from Medium

A Django Blog In VS Code — Upload Profile Picture

Set up and Run Django First Application

How to integrate Stripe in Django

Get start Django project, and its files and directories structure