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:
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 Profileclass 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():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Hi {username}! Your account has
been created! Now login!')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users_hub/register.html', {'form': form})
@login_required
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
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!
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_form
there 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:
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:
08#Step — Now we want to go into the admin
section and make sure all of this looks good:
Large image issue :/ How to deal with it?
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 Imageclass 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'
def save(self):
super().save()
img = Image.open(self.image.path)
if img.height > 150 or img.width > 150:
output_size = (150, 150)
img.thumbnail(output_size)
img.save(self.image.path)
10#Step — Now let’s load a new image to usertTest4
and see if it working...
Here is the result:
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:
Here is the final result:
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
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!