A Django Blog In VS Code — Forms & Validations
How To Create A Blog in VS Code — Part IV — DjangoSeries Episode # 07
In this post we’re gonna continue our #DjangoSeries by learning how to create a front-end forms and also how to validate user input to create a user registration page.
Welcome!
As a user of our website, you’d expect to find a user registration page, login, logout, register pages and all that functionality.
When you’re ready to make an account or write a post you know they provide front-end forms for you to do that kind of stuff.
Let’s get started!
00#Step — This is a continuation of this post; get there and you are ready to fly on your own.
01#Step —Create a brand new app called users_hub
.
The best thing to do here would probably be to create a new app inside of our project where all of that is going to be contained in its own section.
On Terminal
, Ctrl+c, and Type:
python manage.py startapp users_hub
The app users_hub
that will handle all of the user logic for us, will appear on the same level as the blog
app.
Let’s create a user registration page where users can sign up and create accounts from the front end of our website.
But first, let’s go ahead and immediately add it to our installed apps list in our project settings.py
02#Step — Open django_project/Settings.py
and add this to Installed Apps list:
INSTALLED_APPS = ['blog.apps.BlogConfig','users_hub.apps.UsersHubConfig',
...]
03#Step — Create a view inside users_hub/views.py
file, type:
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
def register(request):
form = UserCreationForm()
return render(request, 'users_hub/register.html', {'form': form})
Here we reuse the pre-built UserCreationForm
class to create our form
and pass it as a form variable in the context dictionary to be used by a model
object. Save everything (Ctrl+s
).
Now we need the template.
04#Step — Create this folder structure:
users_hub/templates/users_hub/
Save inside this html
file:
register.html
05#Step — Type inside register.html
Now let’s create a URL pattern that uses our register view.
06#Step — GoTo django_project/urls.py
and add:
from django.contrib import admin
from django.urls import path, include
from users_hub import views as user_viewsurlpatterns = [
path('admin/', admin.site.urls),
path('register/', user_views.register, name='register'),
path('', include('blog.urls')),
]
07#Step — Run the server python manage.py runserver
GoTo http://127.0.0.1:8000/register/
08#Step — Let’s boost our users_hub/views.py
file, type:
09#Step — Update template at blog/templates/blog/base.html
file, and inject this snippet code exactly into the div
that renders each feature sent by the child templates (right above block content
):
10#Step — Installing Django Crispy Forms:
Our validation does not render red, warning errors. Let's fix this:
Django Crispy forms will let you control the rendering behavior of your Django forms in a very elegant and DRY way. Let’s keeping moving on!
In Terminal
, Ctrl+c, type:
pip install django-crispy-forms
Once installed add crispy_forms
to your INSTALLED_APPS
in settings.py:
GoTo django_project/settings.py
INSTALLED_APPS = (
...
'crispy_forms',
)
You can set your default template pack for your project using the CRISPY_TEMPLATE_PACK
Django settings variable:
At the very end of django_project/settings.py
type:
# Crisp config
CRISPY_TEMPLATE_PACK = 'bootstrap4'
Apply crispy filter at users_hub/templates/users_hub/register.html
Crispy filter lets you render a form or formset using django-crispy-forms elegantly div based fields. Let’s see a usage example:
{% load crispy_forms_tags %}
...<form method="post" class="...">
<fieldset>
<legend class="">...</legend>
{{ form|crispy }}
<fieldset>
</form>
- Add
{% load crispy_forms_tags %}
to the template. - Append the
|crispy
filter to your fieldset context variable. - If you are using
bootstrap4
template pack, don’t forget to add the class bootstrap4 to your form. - Refresh and enjoy!
11#Step —Now here is your register page, not bad, huh?
One problem here, the original form does not bring the user email (we need it for login-logout process).
Let’s create a class based form and inhered from UserCreationForm
class.
Rather than recreating the model definitions in your form, it is easier to use the ModelForm helper class to create the form from your model. This ModelForm
can then be used within your views in exactly the same way as an ordinary Form
.
12#Step — Create a new file forms.py
inside your users_hub
app, type:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationFormclass UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
That’s it! Now, user can register by his/her username and email as well.
Model metadata is “anything that’s not a field”, such as ordering options (ordering
), database table name (db_table
), or human-readable singular and plural names (verbose_name
and verbose_name_plural
). None are required, and adding class Meta
to a model is completely optional. (from Django docs)
13#Step — Modify users_hub/views.py
to:
14#Step — Let’s test it out!
Let’s try to register a userTest2:
That’s all Folks!
In the next #DjangoSeries Episode we will continue to customize registration in Django with Authentications, Login & Logout.
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 (this one :)
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
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
Credits & References
Python Django Tutorial: Full-Featured Web App by Corey Schafer
Alerts — Provide contextual feedback messages for typical user actions with the handful of available and flexible alert messages by bootstrap.com
Crisp Installation —by django-crispy-forms.readthedocs.io
Crisp Filter —by django-crispy-forms.readthedocs.io
Django Tutorial Part 9: Working with forms by developer.mozilla.org.
Cross site request forgery (CSRF) attack by imperva.com
The Meta options — by djangoproject.com
Intermediate Django by openclassrooms.com — free quality online course
The Local Library website — Django Web Framework (Python) by developer.mozilla.org ☜ ☜
Getting started with Django 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!