Creating Web Application Python Django on FreeBSD | Restaurant and weather application

When talking about back-end website development, there are many alternative programs that can be used, ranging from Java, PHP, GoLang, Ruby and C#. The Python programming language also has many options for implementing website application services that you can try. One of the most widely used web frameworks in the Python environment is Django.

Django provides a full-featured, modern website development framework and has automated utilities for hands-on development. Python and Django bring stability to website creation. Even for those of you who are just learning website development, Django is very tempting to try and use.

In this article, we'll create a basic, full-featured web application using Python and Django, with the most common features for any website application.

Before we get into the nitty-gritty of learning, it's important for you to understand that when developing website applications using Django, you must master the Django website project structure. Django follows a convention-over-configuration approach, which means implementing project-specific layouts to improve consistency and maintainability.

In its use, Django uses the concepts of Projects and applications to manage code and present it in a format that can be read by many people. A Django project contains one or more applications in it, which perform work simultaneously to provide a smooth flow of website applications.

The Django project framework is based on four main components:
  1. Models: Used to interact with the database and get information that needs to be displayed in the browser.
  2. Views: Will process the request and access the model, telling the model what information it needs to retrieve from the database.
  3. Templates: Used to quickly and precisely show how to display information received from a database.
  4. URL Routes: This function is very important because it will redirect HTTP requests from the browser to the website display

1. Create Web Application Form

Before continuing with the contents of this article, you must first read the previous article.

If you don't read the article, it will be difficult for you to learn the contents of this article, because the article above is the basis for installing Djnago on a FreeBSD server.

In this section we will try creating a web form, a method of sending information from the browser to the Django web server. You'll learn the difference between sending form data in an HTTP GET request and sending it in an HTTP POST request, and how to choose which to use.

The first step you have to do is enter the Python virtual environment.
root@ns3:~ # cd /tmp/Django/DjangoProject
root@ns3:/tmp/Django/DjangoProject # source bin/activate.csh
(DjangoProject) root@ns3:/tmp/Django/DjangoProject # django-admin startproject FreeBSD_Form
(DjangoProject) root@ns3:/tmp/Django/DjangoProject # cd FreeBSD_Form
(DjangoProject) root@ns3:/tmp/Django/DjangoProject/FreeBSD_Form #
The above command is used to create a Django working project named "FreeBSD_Form", which resides in the Python virtual environment. After that, you run the SQLite3 database creation command.
(DjangoProject) root@ns3:/tmp/Django/DjangoProject/FreeBSD_Form # python migrate
Create a Django user and password.
(DjangoProject) root@ns3:/tmp/Django/DjangoProject/FreeBSD_Form # python createsuperuser
Create a form_project application.
(DjangoProject) root@ns3:/tmp/Django/DjangoProject/FreeBSD_Form # python startapp form_project
In the form_project folder, create a new folder called "templates".
(DjangoProject) root@ns3:/tmp/Django/DjangoProject/FreeBSD_Form # cd form_project
(DjangoProject) root@ns3:/tmp/Django/DjangoProject/FreeBSD_Form/form_project # mkdir -p templates
In the "templates" folder, create a file called "form_project.html".
(DjangoProject) root@ns3:/tmp/Django/DjangoProject/FreeBSD_Form/form_project # cd templates
(DjangoProject) root@ns3:/tmp/Django/DjangoProject/FreeBSD_Form/form_project/templates # touch project-form.html
Type the script below in the "/tmp/Django/DjangoProject/FreeBSD_Form/form_project/templates/project-form.html" file.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>FreeBSD Django Form</title>
<h4>Method: {{ method }}</h4>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
        <input type="submit" name="submit_input" value="Submit Input">
        <button type="submit" name="button_element" value="Button Element">
            Button With <strong>Styled</strong> Text

In the "/tmp/Django/DjangoProject/FreeBSD_Form/form_project/" file, type the script below.

from django.shortcuts import render
from .forms import ExampleForm

def form_project(request):
    if request.method == "POST":
        form = ExampleForm(request.POST)
        form = ExampleForm()

    if request.method == "POST":
        form = ExampleForm(request.POST)
        if form.is_valid():
            for name, value in form.cleaned_data.items():
                print("{}: ({}) {}".format(name, type(value), value))

    return render(request, "project-form.html", {"method": request.method, "form": form})

In the "/tmp/Django/DjangoProject/FreeBSD_Form/form_project/" file, type the script below.

import re
from unittest import mock

from django import forms
from django.http import HttpRequest, QueryDict
from django.test import Client
from django.test import TestCase

from form_example.forms import ExampleForm, RADIO_CHOICES, BOOK_CHOICES
from form_example.views import form_example

class Exercise5Test(TestCase):
    def test_fields_in_view(self):
        Test that some fields exist in the rendered template, assume that if all the fields exist on the form class
        (there is a separate test for this) then they will all be rendered. There's no reason why only some would be.
        c = Client()
        response = c.get('/form-example/')

        self.assertIsNotNone('<input type="hidden" name="csrfmiddlewaretoken" value="\w+">',

        self.assertIn(b'<p><label for="id_text_input">Text input:</label> <input type="text" name="text_input" '
                      b'maxlength="3" required id="id_text_input"></p>', response.content)
        self.assertIn(b'<p><label for="id_password_input">Password input:</label> <input type="password" '
                      b'name="password_input" minlength="8" required id="id_password_input"></p>', response.content)
        self.assertIn(b'<p><label for="id_checkbox_on">Checkbox on:</label> <input type="checkbox" '
                      b'name="checkbox_on" required id="id_checkbox_on"></p>', response.content)

        self.assertIn(b'<input type="submit" name="submit_input" value="Submit Input">', response.content)
        self.assertIn(b'<button type="submit" name="button_element" value="Button Element">', response.content)
        self.assertIn(b'Button With <strong>Styled</strong> Text', response.content)
        self.assertIn(b'</button>', response.content)

    def test_method_in_view(self):
        """Test that the method is included in the HTML output"""
        c = Client()
        response = c.get('/form-example/')
        self.assertIn(b'<h4>Method: GET</h4>', response.content)

        response ='/form-example/')
        self.assertIn(b'<h4>Method: POST</h4>', response.content)

    def test_get_debug_output(self, mock_example_form, mock_print):
        """Mock the print() function to test the debug output with GET request (no output)."""
        mock_request = mock.MagicMock(spec=HttpRequest)
        mock_request.method = 'GET'
        mock_request.POST = QueryDict()
        mock_request.META = {}

    def test_post_debug_output(self, mock_print):
        """Mock the print() function to test the debug output with posted data."""
        mock_request = mock.MagicMock(spec=HttpRequest)
        mock_request.method = 'POST'
        mock_request.POST = QueryDict(
        mock_request.META = {}
        mock_print.assert_any_call("text_input: (<class 'str'>) tex")
        mock_print.assert_any_call("password_input: (<class 'str'>) password123")
        mock_print.assert_any_call("checkbox_on: (<class 'bool'>) True")
        mock_print.assert_any_call("radio_input: (<class 'str'>) Value Two")
        mock_print.assert_any_call("favorite_book: (<class 'str'>) 1")
        mock_print.assert_any_call("books_you_own: (<class 'list'>) ['1', '4']")
        mock_print.assert_any_call("text_area: (<class 'str'>) Text")
        mock_print.assert_any_call("integer_input: (<class 'int'>) 10")
        mock_print.assert_any_call("float_input: (<class 'float'>) 3.4")
        mock_print.assert_any_call("decimal_input: (<class 'decimal.Decimal'>) 1.345")
        mock_print.assert_any_call("email_input: (<class 'str'>)")
        mock_print.assert_any_call("date_input: (<class ''>) 2019-12-11")
        mock_print.assert_any_call("hidden_input: (<class 'str'>) Hidden Value")

    def test_example_form(self):
        """Test that the ExampleForm class exists and has the attributes we expect."""
        form = ExampleForm()
        self.assertIsInstance(form.fields['text_input'], forms.CharField)

        self.assertIsInstance(form.fields['password_input'], forms.CharField)
        self.assertIsInstance(form.fields['password_input'].widget, forms.PasswordInput)

        self.assertIsInstance(form.fields['checkbox_on'], forms.BooleanField)

        self.assertIsInstance(form.fields['radio_input'], forms.ChoiceField)
        self.assertIsInstance(form.fields['radio_input'].widget, forms.RadioSelect)
        self.assertEqual(form.fields['radio_input'].choices, list(RADIO_CHOICES))

        self.assertIsInstance(form.fields['favorite_book'], forms.ChoiceField)
        self.assertEqual(form.fields['favorite_book'].choices, list(BOOK_CHOICES))

        self.assertIsInstance(form.fields['books_you_own'], forms.MultipleChoiceField)
        self.assertEqual(form.fields['books_you_own'].choices, list(BOOK_CHOICES))

        self.assertIsInstance(form.fields['text_area'], forms.CharField)
        self.assertIsInstance(form.fields['text_area'].widget, forms.Textarea)

        self.assertIsInstance(form.fields['integer_input'], forms.IntegerField)

        self.assertIsInstance(form.fields['float_input'], forms.FloatField)

        self.assertIsInstance(form.fields['decimal_input'], forms.DecimalField)
        self.assertEqual(form.fields['decimal_input'].max_digits, 5)

        self.assertIsInstance(form.fields['email_input'], forms.EmailField)

        self.assertIsInstance(form.fields['date_input'], forms.DateField)
        self.assertIsInstance(form.fields['date_input'].widget, forms.DateInput)
        self.assertEqual(form.fields['date_input'].widget.input_type, 'date')

        self.assertIsInstance(form.fields['hidden_input'], forms.CharField)
        self.assertEqual(form.fields['hidden_input'].initial, 'Hidden Value')

In the "/tmp/Django/DjangoProject/FreeBSD_Form/form_project" folder, create a file called "".
(DjangoProject) root@ns3:/tmp/Django/DjangoProject/FreeBSD_Form/form_project/templates # cd ..
(DjangoProject) root@ns3:/tmp/Django/DjangoProject/FreeBSD_Form/form_project # touch
In the "/tmp/Django/DjangoProject/FreeBSD_Form/form_project/" file, type the script below.

from django import forms

    ("Value One", "Value One Display"),
    ("Value Two", "Text For Value Two"),
    ("Value Three", "Value Three's Display Text")

        "Non-Fiction", (
            ("1", "Deep Learning with Keras"),
            ("2", "Web Development with Django")
        "Fiction", (
            ("3", "Brave New World"),
            ("4", "The Great Gatsby")

class ExampleForm(forms.Form):
    text_input = forms.CharField(max_length=3)
    password_input = forms.CharField(min_length=8, widget=forms.PasswordInput)
    checkbox_on = forms.BooleanField()
    radio_input = forms.ChoiceField(choices=RADIO_CHOICES, widget=forms.RadioSelect)
    favorite_book = forms.ChoiceField(choices=BOOK_CHOICES)
    books_you_own = forms.MultipleChoiceField(required=False, choices=BOOK_CHOICES)
    text_area = forms.CharField(widget=forms.Textarea)
    integer_input = forms.IntegerField(min_value=1, max_value=10)
    float_input = forms.FloatField()
    decimal_input = forms.DecimalField(max_digits=5, decimal_places=3)
    email_input = forms.EmailField()
    date_input = forms.DateField(widget=forms.DateInput(attrs={"type": "date"}))
    hidden_input = forms.CharField(widget=forms.HiddenInput, initial="Hidden Value")

In the "/tmp/Django/DjangoProject/FreeBSD_Form/FreeBSD_Form/" file, type the script below.

from django.contrib import admin
from django.urls import path
import form_project.views

urlpatterns = [
    path('project-form/', form_project.views.form_project)

In the "/tmp/Django/DjangoProject/FreeBSD_Form/FreeBSD_Form/" file, Change some of the scripts below.


# Application definition


Run the Django server.
(DjangoProject) root@ns3:/tmp/Django/DjangoProject/FreeBSD_Form # python runserver
Once there are no errors, when running the command above, do a test. Open the Google Chrome web browser and type "". You see the display on your monitor screen, a form menu will appear.

2. Django WebApp 1 From Github Repository

Because most people, during the learning process, tinker with scripts in the Github repository, to increase your knowledge we will provide an example of creating a Django WebApp that comes from the Github repository.

The WebApp application that we will demonstrate in this article is a restaurant application. As usual we start in the Python virtual environment, we assume you are already in Python VEnv.
(DjangoProject) root@ns3:/tmp/Django/DjangoProject # django-admin startproject UserAuthapp
(DjangoProject) root@ns3:/tmp/Django/DjangoProject # cd UserAuthapp
(DjangoProject) root@ns3:/tmp/Django/DjangoProject/UserAuthapp # python migrate
The above command is used to create a working directory named "UserAuthapp". After that, you continue by creating a restaurant directory which we will name "home"
(DjangoProject) root@ns3:/tmp/Django/DjangoProject/UserAuthapp # python startapp home
Clone the restaurant application from the Github repository. We will place the cloning results separately in the "/var" folder. We exit the Python virtual environment with the "deactivate" command.
(DjangoProject) root@ns3:/tmp/Django/DjangoProject/UserAuthapp # deactivate
root@ns3:/tmp/Django/DjangoProject/UserAuthapp # cd /var
root@ns3:/var # git clone
Cloning into 'Restaurantly-app-in-django-'...
remote: Enumerating objects: 180, done.
remote: Counting objects: 100% (180/180), done.
remote: Compressing objects: 100% (140/140), done.
remote: Total 180 (delta 36), reused 180 (delta 36), pack-reused 0
Receiving objects: 100% (180/180), 5.92 MiB | 3.06 MiB/s, done.
Resolving deltas: 100% (36/36), done.
root@ns3:/var #
Copy some files and folders from the restaurant application that you cloned from Github to the Django working directory.
root@ns3:/var # cd Restaurantly-app-in-django-
root@ns3:/var/Restaurantly-app-in-django- # cp -R static /tmp/Django/DjangoProject/UserAuthapp
root@ns3:/var/Restaurantly-app-in-django- # cp -R templates /tmp/Django/DjangoProject/UserAuthapp
root@ns3:/var/Restaurantly-app-in-django- # cd home
root@ns3:/var/Restaurantly-app-in-django-/home # cp -R /tmp/Django/DjangoProject/UserAuthapp/home
Copy the "/var/Restaurantly-app-in-django-/UserAuthapp/" and "/var/Restaurantly-app-in-django-/UserAuthapp/", to the Django working directory.
root@ns3:/var/Restaurantly-app-in-django-/home # cp -R /var/Restaurantly-app-in-django-/UserAuthapp/ /tmp/Django/DjangoProject/UserAuthapp/UserAuthapp
root@ns3:/var/Restaurantly-app-in-django-/home # cp -R /var/Restaurantly-app-in-django-/UserAuthapp/ /tmp/Django/DjangoProject/UserAuthapp/UserAuthapp
After that, edit the "/tmp/Django/DjangoProject/UserAuthapp/UserAuthapp/" file, change only a few scripts like the example below.


Create a Django user and password, with the command "python createsuperuser".
root@ns3:/var/Restaurantly-app-in-django-/home # cd /tmp/Django/DjangoProject
root@ns3:/tmp/Django/DjangoProject # source bin/activate.csh
(DjangoProject) root@ns3:/tmp/Django/DjangoProject # cd UserAuthapp
(DjangoProject) root@ns3:/tmp/Django/DjangoProject/UserAuthapp # python createsuperuser
Run the Django server.
(DjangoProject) root@ns3:/tmp/Django/DjangoProject # python runserver
To see the results, open the Google Chrome web browser, type "".

Please log in with the Django password you created above. After you have successfully logged in, the results will be like the image below.

3. Django WebApp 2 From Github Repository

In this section we will demonstrate a weather application. Apart from the method above, we will try another method that is faster and more efficient. Not much different from the method above, you also have to run the weather application in the Python virtual environment.

OK, let's just run the command to clone the application from the Github repository.

root@ns3:~ # cd /tmp/Django/DjangoProject
root@ns3:/tmp/Django/DjangoProject # source bin/activate.csh
(DjangoProject) root@ns3:/tmp/Django/DjangoProject # git clone
Cloning into 'Weather_App-with-Python-Django'...
remote: Enumerating objects: 416, done.
remote: Counting objects: 100% (416/416), done.
remote: Compressing objects: 100% (322/322), done.
remote: Total 416 (delta 123), reused 364 (delta 88), pack-reused 0
Receiving objects: 100% (416/416), 6.88 MiB | 5.59 MiB/s, done.
Resolving deltas: 100% (123/123), done.
(DjangoProject) root@ns3:/tmp/Django/DjangoProject #
After you have successfully cloned the weather application from Github, continue by creating a SQLite3 database.
(DjangoProject) root@ns3:/tmp/Django/DjangoProject # cd Weather_App-with-Python-Django
(DjangoProject) root@ns3:/tmp/Django/DjangoProject/Weather_App-with-Python-Django # python migrate
Don't forget to run the following command to create a Django user and password.
(DjangoProject) root@ns3:/tmp/Django/DjangoProject/Weather_App-with-Python-Django # python createsuperuser
Install dependencies.
(DjangoProject) root@ns3:/tmp/Django/DjangoProject # pip install asgiref certifi chardet idna pytz requests sqlparse urllib3
Edit the "/tmp/Django/DjangoProject/Weather_App-with-Python-Django/WeatherBug/" file, change only a few scripts like the example below.

ALLOWED_HOSTS = [''] is the local IP of your FreeBSD server. Next, you run the Django server.
(DjangoProject) root@ns3:/tmp/Django/DjangoProject/Weather_App-with-Python-Django # python runserver
To see the results, open Google Chrome or Modzilla Firefox, type "". If you follow all the instructions above it will look like the image below.

In this article we have provided several examples of using Python Django for creating web applications. This article is just part of the Django tutorial, you can continue to follow our Blogspot to get the latest Django information.
    Iwan Setiawan

    I Like Adventure: Mahameru Mount, Rinjani Mount I Like Writer FreeBSD

    Post a Comment

    Previous Post Next Post