A Django Blog In VS Code — Update & Resize Picture

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():
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

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:

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',
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:

Everything is fine…the image was resized to fit to 150×150……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