Django #4

You can test the application by creating a free account here.
You can get the source code from GitHub here.

In this post I will present views responsible for car management and repairs.

▣ I will start with the main view showing the cars entered by the user.

The maximum number of entries per page is 10 cars.

After clicking on a particular car, the repairs of a given car are displayed.

Both car and repair entries are sorted by date, i.e. the newest entries are displayed first.

The view class displaying cars inherits from the ListView class and the LoginRequiredMixin class (so that access is only possible for logged in users).

First, I define all the class attributes, i.e. the model used – Car, the template used – cars.html, the name of the object under which the data in the context is available – context_object_name – ‘cars’, and the number of entries on the page – 10 vehicles.

In this class, I override two methods – get_queryset (), which is responsible for filtering data, and get_context_data (), in which I complete the context data with data from the search field.

CarListView () class source code:

class CarsListView(LoginRequiredMixin, ListView):
    model = Car
    template_name = 'cars/cars.html'
    context_object_name = 'cars'
    paginate_by = 10

    def get_queryset(self):
        if self.request.GET.get('q'):
            q = self.request.GET.get('q')
            make_results = self.model.objects.filter(
                user=self.request.user, make=q).order_by('-pk')
            model_results = self.model.objects.filter(
                user=self.request.user, model=q).order_by('-pk')
            if make_results.exists():
                return make_results
            elif model_results.exists():
                return model_results
            else:
                return self.model.objects.none()
        return self.model.objects.filter(user=self.request.user).order_by('-pk')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['q'] = self.request.GET.get('q', '')
        return context

The get_queryset() method lists all of the user’s vehicles. The last added car is visible first (sort ‘-pk’). If the make or model of the vehicle (s) was entered in the search field, only these vehicles will be displayed.

The get_context_data() method adds an entry from the search field to the context, thanks to which the data about car repairs is displayed correctly when dividing cars into individual pages.

▣ Adding a vehicle is done by pressing the Add Car button in the application menu.

The view that handles adding a car is the AddCarView () class, and the template that displays the add car form is car_form.html (the same template also supports updating auto data).

The AddCarView () class inherits the functionality from the CreateView () and LoginRequiredMixin class (only logged in users can create a new vehicle).

I define the following view class attributes: model that the class uses – Car, fields – the form fields to be visible, and success_url – the url that will be loaded after successfully completing the form.

I override the form_valid() method, which adds the user who created the new car (the Car model requires a user attribute to be defined).

The source code for the AddCarView class :

class AddCarView(LoginRequiredMixin, CreateView):
    model = Car
    fields = ['make', 'model', 'vrn', 'year']
    success_url = '/'

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

▣ Removing the car is done using the DeleteCarView () view class, and the template that prompts you to delete the auto is the car_confirm_delete.html file (displays the Delete button that deletes the auto and the Cancel button that returns to the previous page).

DeleteCarView () class inherits functionality from DeleteView, LoginRequiredMixin class (only logged in user can delete auto) and UserPassesTestMixin (user can delete auto created by himself).

I define the model arguments – the used Car model and success_url – the address to which it will be loaded after the successful removal of the car – in this case, the view showing all the user’s cars.

I am creating a test_func () method which checks if the user who wants to delete the car is the person who created the auto (the user can only delete the cars he created).

I override the delete () method, which additionally displays the message about deleting the car.

The DeleteCarView() class source code:

class DeleteCarView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model = Car
    success_url = '/'

    def test_func(self):
        if self.get_object().user == self.request.user:
            return True
        return False

    def delete(self, request, *args, **kwargs):
        success_message = f'Car {self.get_object()} has been deleted'
        messages.success(self.request, success_message)
        return super().delete(request, *args, **kwargs)

▣ The vehicle data is updated using the UpdateCarView () class, while the template displaying the form for changing this data is car_form.html.

The UpdateCarView () class inherits functionality from the UpdateView class as well as the LoginRequiredMixin classes (only the logged in user can update the data) and UserPassesTestMixin (a function is called to check if the user who wants to modify is the one who created the auto).

I define class attributes: model – specifies the model that is used to change the data – in this case the Car model, fields attribute – specifying which form fields are to be available and success_message – a text message about updating the car data.

Two methods are defined: test_func () and get_success_url ().

The test_func () method checks if the user who wants to modify the car’s data is the one who created the car.

The get_success_url() method displays a message about the data change and returns to the page with the name: car_detail – displaying repairs for a given car. As additional parameters, they are sent using the GET method: row, p and q that define the row and page of the car in the table and the text string from the search box.

Code of the UpdateCarView() class:

class UpdateCarView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Car
    fields = ['make', 'model', 'vrn', 'year']
    success_message = 'Car info has been updated'

    def get_success_url(self, **kwargs):
        row = self.request.GET.get('row')
        p = self.request.GET.get('p')
        q = self.request.GET.get('q')
        options = '?p=' + p + '&row=' + row
        options += '&q=' + q
        messages.success(self.request, self.success_message)
        return reverse_lazy('car_detail') + options

    def test_func(self):
        if self.get_object().user == self.request.user:
            return True
        return False

▣ Adding a repair note is defined in the AddRepairView() class, and the form is defined in the repair_form.html template.

This class has the following arguments: model – specifying the model used – in this case Repair. The next argument: fields – specifies what the form fields are displayed. The last argument is the success_message string displayed after the repair note was successfully added.

The methods in the AddRepairView() class are: get_context_data(), form_valid(), and get_success_url().

The get_context_data() method adds a Car object to the context, making it visible in the template.

The form_valid () method uses the data from the form to create a new model instance. To properly create an instance of the Repair class, it is necessary to provide a foreign key – a Car object that identifies the vehicle to which a given repair note relates.

The get_success_url () method specifies the address of the page to be displayed when a new note is successfully added. In this case, a page named car_detail as defined in cars / urls.py will be displayed.

class AddRepairView(LoginRequiredMixin, CreateView):
    model = Repair
    fields = ['date', 'description']
    success_message = 'New repair has been added'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['car'] = Car.objects.get(id=self.kwargs['pk'])
        return context

    def form_valid(self, form, **kwargs):
        form.instance.car = Car.objects.get(id=self.kwargs['pk'])
        return super().form_valid(form)

    def get_success_url(self, **kwargs):
        row = self.request.GET.get('row')
        p = self.request.GET.get('p')
        q = self.request.GET.get('q')
        options = '?p=' + p + '&row=' + row
        options += '&q=' + q
        return reverse_lazy('car_detail') + options

to be continued

Django #3

You can see the application deployed on heroku here.
You can get a source code here.

In previous posts, I described user management in the application, i.e. a new user can register – create an account on the site, a registered user can log in, log out or change the password.

Then I’ll describe the main functionality of the app – car and repair records.

For this purpose, in the project urls.py file, I will attach the mapping of addresses related to cars application.

After the changes, the project urls.py file will look like this:

from django.contrib import admin
from django.urls import path, include
from users import views as users_views
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('cars.urls')),
    path('register-user/', users_views.RegisterUser.as_view(
        template_name='users/register-user.html'), name='register_user'),
    path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
    path('change-password/', users_views.ChangePassword.as_view(
        template_name='users/change-password.html'), name='change_password'),
]

The urls.py file created in the cars application also takes into account mapping addresses to appropriate views. The urls.py file from the cars application looks like this:

from django.urls import path
from .views import (
    CarsListView,
    AddCarView,
    RepairsListView,
    UpdateCarView,
    DeleteCarView,
    AddRepairView
)
urlpatterns = [
    path('', CarsListView.as_view(), name='cars'),
    path('add-car/', AddCarView.as_view(), name='add_car'),
    path('car/', RepairsListView.as_view(), name='car_detail'),
    path('car/<int:pk>/update/', UpdateCarView.as_view(), name='update_car'),
    path('car/<int:pk>/delete/', DeleteCarView.as_view(), name='delete_car'),
    path('car/<int:pk>/new-repair/', AddRepairView.as_view(), name='add_repair'),
]

The main view defined in the CarListView class displays all the user’s cars.

Remember to add the application in the project’s settings.py file in the INSTALLED_APPS list, e.g. for cars it will be an element: ‘cars.apps.CarsConfig’.

I used the pre-installed user model in the users application. In the cars application, I created models – objects mapping database tables.

These models will define: vehicle – Car model and repair – Repair model. The models.py file looks like this:

from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from django.core.validators import MaxValueValidator, MinValueValidator


class Car(models.Model):
    make = models.CharField(max_length=10)
    model = models.CharField(max_length=10)
    vrn = models.CharField(max_length=10)
    year = models.IntegerField(default=timezone.now().year,
                               validators=[MinValueValidator(timezone.now().year - 100),
                                           MaxValueValidator(timezone.now().year)])
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return f'{self.make} {self.model}'


class Repair(models.Model):
    date = models.DateField(default=timezone.now)
    description = models.TextField()
    car = models.ForeignKey(Car, on_delete=models.CASCADE)

    def __str__(self):
        lead = self.description[:10] + '...'
        return lead

The Car model contains make, model, vrn, year, and user attributes that describe the vehicle make, model, vehicle registration number, and year of manufacture, as well as a foreign key containing the user object that created the vehicle entry.

The year field has validators that make it impossible to enter a car with a production year 100 years older than the current date and newer than the current year.

The on_delete option of the user attribute has the default value CASCADE, ie deleting a user will also delete all his cars.

The Repair model includes the attributes: date – repair date, description – repair details and a foreign key car – which car the repair concerns.

The __str__() method prints the header that is the beginning of the repair description (leading 10 characters).

To be able to edit entries of both models from the administration panel, you need to add both models to the admin.py file of the cars application, i.e.

from django.contrib import admin
from .models import Car, Repair

admin.site.register(Car)
admin.site.register(Repair)

In the next post, I will describe the views that define individual functionalities, i.e. displaying cars belonging to the user, adding repairs, and searching for cars using the search box on the website.

Django #2

The login and logout views are predefined as LoginView and LogoutView classes, so you only need to put the appropriate entries in the urls.py file (as described in part 1) and create template files, i.e.

login.html template:

{% extends 'cars/base.html' %}
{% load crispy_forms_tags %}


{% block content %}
  <div class="row justify-content-center">
    <div class="col-4">
      <form method="POST" class="form-control-sm">
       {% csrf_token %}
       <fieldset class="form-group">
         <legend class="border-bottom text-primary">
            Log In
          </legend>
          {{ form|crispy }}
        </fieldset>
        <button class="btn btn-secondary" type="submit">Login</button>
        <p class="text-muted text-small mt-5 ml-2">Need an Account? <a href="{% url 'register_user' %}">Sign up</a></p>
        </form>
      </div>
    </div>
{% endblock %}
login.html template

logout.html template:

{% extends 'cars/base.html' %}

{% block content %}
 <div class="row justify-content-center mb-5">
    <div class="col-4">
	   <h4 class="border-bottom text-primary mt-2">You're logged out now</h4>	
  <div class="text-muted text-small ml-2 mt-5">Back to: <a href="{% url 'login' %}">login page</a></div>
  </div>
 </div>
{% endblock %}

It still remains to create a view responsible for changing the password. The view class will inherit from the CreateView class as well as the LoginRequiredMixin class. The LoginRequiredMixin class adds the functionality that only the logged in user can change the password.

ChangePassword () view class code:

class ChangePassword(LoginRequiredMixin, CreateView):
    form_class = PasswordChangeForm

    def get(self, request, *args, **kwargs):
        form = PasswordChangeForm(request.user)
        return render(request, 'users/change-password.html', {'form': form})

    def post(self, request, *args, **kwargs):
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)
            messages.success(request, 'Password changed!')
            return redirect('cars')
        return render(request, 'users/change-password.html', {'form': form})

In the class above, I override the get() and post() methods.

When the page is displayed using the get() method, an empty password change form is displayed for the user.

When the page is displayed using the post () method, the submitted data is validated and, if correct, the changed password is saved, a password change message is displayed and redirected to a page named cars.

It remains to add the template file, ie change-password.html.

{% extends 'cars/base.html' %}
{% load crispy_forms_tags %}


{% block content %}
  <div class="row justify-content-center">
   <div class="col-4">
	  <form method="POST" class="form-control-sm">
      {% csrf_token %}
      <fieldset class="form-group">
        <legend class="border-bottom text-primary">
            New Password Settings
        </legend>
        {{ form|crispy }}
      </fieldset>
      <button class="btn btn-secondary" type="submit">Save</button>
    </form>
   </div>
  </div>
{% endblock %}
change-password.html template

to be continued….

Django #1

Below is a listing of the required packages for the project:

asgiref==3.2.5
Django==3.0.4
django-crispy-forms==1.9.0
pytz==2019.3
sqlparse==0.3.1

I recommend creating a separate virtual environment for the project (how to create a virtual environment I described here).

All packages except django-crispy-forms are installed when the django package is installed.

In the directory containing the venv subdirectory, create a project with the command: django-admin startproject project_name

Startproject command creates the project’s main directory and a manage.py file for managing the project.

You can then create a project administrator, i.e. a user with maximum administrative privileges, so that you can use the web admin panel. However, first you need to run a migrate: python manage.py migrate thanks to which the appropriate tables are created in the database, e.g. admin, auth etc.

After migration, you can create an administrative account with the command: python manage.py createsuperuser

The project directory contains the following files and directories:

├── project_name
│ ├── asgi.py
│ ├── init.py
│ ├── pycache
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── db.sqlite3
└── manage.py

By default, the data is placed in the sqlite3 database (db.sqlite3 file), which is a good solution when creating a project, and finally you can use a different database (Django includes support for PostgreSQL, MySQL and many others). Changing the default database only requires modifying the data from the DATABASES section of the project’s settings.py file.

In order to separate the individual components of the project, I made two components, i.e. users – responsible for user management and cars for vehicle management. In Django, these are called apps. To create them, type: python manage.py startapp users and python manage.py startapp cars

I will start with the users application, in which new users will be able to create accounts, log in, log out, and change their access password.

To define URL mapping to specific view classes, I modify the project urls.py file, i.e.

from django.contrib import admin
from django.urls import path
from users import views as users_views
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('register-user/', users_views.RegisterUser.as_view(
        template_name='users/register-user.html'), name='register_user'),
    path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
    path('change-password/', users_views.ChangePassword.as_view(
        template_name='users/change-password.html'), name='change_password'),
]

For example, after entering the address ending with: register-user /, the class RegisterUser () is called from the views.py file and the assignment is given a name that we can use in templates.

For a class to be used as a view, its as_view () method must be called. As an argument I have given the template_name argument, in which I give the name of the template that displays the given page. You might as well pass this argument as a class attribute in a view, but for consistency with the rest of the views, I have included it here.

The code of the RegisterUser () class from the views.py file of the users application looks as follows (at the beginning I put the required imports):

from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, PasswordChangeForm
from django.contrib.auth import login, authenticate
from django.views.generic import CreateView
from django.contrib import messages

class RegisterUser(CreateView):
    form_class = UserCreationForm

    def get(self, request, *args, **kwargs):
        return render(request, 'users/register-user.html', {'form': UserCreationForm()})

    def post(self, request, *args, **kwargs):
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=password)
            login(request, user)
            messages.success(request, f'Welcome, {username}!')
            return redirect('cars')
        return render(request, 'users/register-user.html', {'form': form})

The RegisterUser () class inherits from the CreateView class, and the form is defined by the UserCreationForm class.

When the page is displayed using the GET method, an empty form appears, while if some data is already provided in the form, it is passed using the POST method.

To handle GET and POST, I override the get() and post() methods of RegisterUser(), respectively. In the post() method, the form is validated and if the form is correct, then the data from the form is saved, ie the user is created using the save() method. By default, this is a user with no administrative privileges. He is logged in using the data provided during registration. A new message with the tag Success will be displayed after redirecting to an address named cars. The message is displayed only once.

It remains to create the register-user.html template for RegisterUser(). For this purpose, I create a template directory in the users application according to the convention – in the templates directory, create another directory with the name consistent with the name of the application, i.e.

project_name/users/templates/users/register-user.html

The code of register-user.html is part of a larger whole, or more precisely, the base.html file from the cars application, which has not been created yet.

Applications can use their templates, so the look defined in cars in base.html is preserved in register-user.html

The template also enables the use of crispy_forms tags to make the form look better.

Each form must contain csrf_token, thanks to which the website is automatically immune to some forms of attacks (details: here).

Code of register-user.html file:

{% extends 'cars/base.html' %}
{% load crispy_forms_tags %}

{% block content %}
  <div class="row justify-content-center">
    <div class="col-4">
      <form method="POST" class="form-control-sm">
        {% csrf_token %}
        <fieldset class="form-group">
          <legend class="border-bottom text-primary">
            Registration
          </legend>
            {{ form|crispy }}
        </fieldset>
          <button class="btn btn-secondary" type="submit">Register</button>
      </form>
    </div>
  </div>
{% endblock %}

Django – web framework

In this series, I will describe the basics of the Django framework using the example of an application for recording repairs related to your car.

The application is similar to the one described in this posts, but the use of a web framework forced additional functionalities, e.g. user accounts support.

You can create your own account and log in to the application here.

You can download the project code here.