Django Bootstrap3 Example

Bootstrap is the most popular front-end framework for web page development. It provides a lot of CSS classes and javascript functions for you to make your web page beautiful and consistent. Django is the most popular web framework written in Python. It makes dynamic website creation easy and faster. This example will show you how to use Bootstrap3 and Django framework to develop a dynamic website.

The example website contains three parts.

  1. User management part: This part will invoke the Django project’s built-in authentication module to add or delete users.
  2. Department management part: This part provides a method to add or delete departments.
  3. Employee management part: You can add or delete an employee in this part. To add an employee, select a user from the user list and a department from the department list, then input employee salary and mobile, then click add to add it.

1. Install Django-bootstrap3 Library In PyCharm.

Django-bootstrap3 library integrates bootstrap3 into Django, when you install this library, you can use bootstrap3 directly in your Django project as a Django application. Follow the below steps to install it.

  1. Install Django-bootstrap3 library in PyCharm, you can refer article PyCharm Project Add External Library (PyMySQL) Path Example to learn how to do it.
  2. Then add bootstrap3 library as a Django project application in project settings.py file INSTALLED_APPS section. Now you can use bootstrap3 in your Django applications.
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'bootstrap3',
        'dept_emp',
    ]

2. Create Department Employee Application In Django Project.

  1. Go to Django project root folder, then run python3 manage.py startapp dept_emp in a terminal.
  2. If you use PyCharm, click Tools —> Run manage.py Tasks menu item, then input startapp dept_emp in the bottom console window.
  3. Now add the app dept_emp in the project settings.py file INSTALLED_APPS section also.
  4. Before diving into source code, let us look at the example demo video.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/pGr3nuPuZJM

3. Django Bootstrap3 Example Source Code.

3.1 DjangoHelloWorld / DjangoHelloWorld / settings.py.

  1. Add bootstrap3, dept_emp in INSTALLED_APPS section.
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'bootstrap3',
        'dept_emp',
        #'my_hello_world',
        #'user_register_login',
    ]
  2. Add LOGIN_URL at the end of settings.py. Because the example’s views function has been decorated with @login_required() decorator, so when the user does not log in and access the view function, it will show the web page http://127.0.0.1:8000/dept_emp/ to let the user login first. Please refer article Django Custom Login Page Use login_required Decorator to learn more.
    LOGIN_URL = '/dept_emp'

3.2 DjangoHelloWorld / DjangoHelloWorld / urls.py.

  1. This is project urls.py.
    from django.contrib import admin
    from django.urls import path, include
    from django.conf.urls import url
    
    urlpatterns = [
        path('admin/', admin.site.urls),
    
        # if do not provide namespace attribute, then an 'dept_emp' is not a registered namespace error will be thrown,
        # you can get the error when browse url http://127.0.0.1:8000/dept_emp/
    
        # if do not provide a tuple as include first argument, an Specifying a namespace in include() without providing an app_name is not supported error will be thrown
        # the second element in the tuple is the app_name.
        url(r'^dept_emp/', include(('dept_emp.urls','dept_emp'),namespace='dept_emp')),
    ]
  2. Please note the last URL pattern settings, if do not provide namespace and app name, the example will throw a ‘dept_emp is not a registered namespace’ error during the template rendering process.

3.3 DjangoHelloWorld / dept_emp / admin.py.

  1. admin.py.
    from django.contrib import admin
    
    # the module name is app_name.models
    from dept_emp.models import Department, Employee
    
    # this class defines which department columns will be shown on the department admin website.
    class DepartmentAdmin(admin.ModelAdmin):
        # a list of displayed columns name.
        list_display = ['id', 'dept_name', 'dept_desc']
        # define search columns list, then a search box will be added at the top of Department list page.
        search_fields = ['dept_name', 'dept_desc']
        # define filter columns list, then a filter widget will be shown at right side of Department list page.
        list_filter = ['dept_name']
    
    # this class defines employee columns that will be shown on the employee admin website. Note the foreign key value will be displayed automatically.
    # the foreign key is user and dept which reference other models, so the user or department model's __str__(self) method will be called and the return value will be displayed.
    class EmployeeAdmin(admin.ModelAdmin):
        # a list of displayed columns name, the user and dept foreign key will display related model's __str__(self) method returned string value.
        list_display = ['id', 'user', 'dept', 'emp_mobile','emp_salary','emp_onboard_date']
    
    # Register your models to admin site, then you can add, edit, delete and search your models in Django admin site.
    admin.site.register(Department, DepartmentAdmin)
    admin.site.register(Employee, EmployeeAdmin)

3.4 DjangoHelloWorld / dept_emp / models.py.

  1. There are two custom-defined models, Department and Employee.
    from django.db import models
    from django.contrib.auth.models import User
    
    # create Department model, this model will be mapped to table user_register_login_department in sqlite db.
    class Department(models.Model):
        # define department name and description columns, the id column will be added automatically.
        dept_name = models.CharField(max_length=1000)
        dept_desc = models.CharField(max_length=1000)
    
        # this function will be invoked when this model object is foreign key of other model(for example Employee model.).
        def __str__(self):
            ret = self.dept_name + ',' + self.dept_desc
            return ret
    
        # this is an inner class that is used to define unique index columns. You can specify multiple columns in a list or tuple.
        class Meta:
            unique_together = ['dept_name']
    
    # create Employee model, this model will be mapped to table user_register_login_employee in sqlite db.
    class Employee(models.Model):
        # Employee has two foreign key, user(Django built-in auth_user table) and department.
        user = models.ForeignKey(User, on_delete=models.CASCADE,)
        dept = models.ForeignKey(Department, on_delete=models.CASCADE,)
        emp_mobile = models.CharField(max_length=100)
        # should add the () after IntegerField, otherwise the emp_salary column will not be created.
        emp_salary = models.IntegerField()
        # if do not specify the auto_now=True attribute with value then this field can not be created.
        emp_onboard_date = models.DateTimeField(auto_now=True)
    
        # this method will be called when other model reference Employee model as foreign key.
        def __str__(self):
            return self.user.username + ',' + str(self.emp_salary) + ',' + str(self.emp_mobile)
    
        class Meta:
            unique_together = ['emp_mobile']

3.5 DjangoHelloWorld / dept_emp / urls.py.

  1. This is dept_emp application urls.py.
    from django.conf.urls import url
    from django.urls import path
    # import views from local directory.
    from . import views
    
    urlpatterns = [
    
        # do not use an empty string in the url request path, it will intercept all request url with all request path values.
        # url(r'', views.home_page, name='home_page'),
    
        # if you want to intercept the django app root path request just use url path r'^$' to map it.
        # Then following url mapping will handle request http://127.0.0.1:8000/ with view function home_page.
        url(r'^$', views.home_page, name='home_page'),
    
        # request http://127.0.0.1:8000/dept_emp/user_list will invoke the user_list function defined in views.py.
        url(r'^user_list/', views.user_list, name='user_list'),
    
        # request http://127.0.0.1:8000/dept_emp/user_pre_add will invoke the user_pre_add function defined in views.py.
        url(r'^user_pre_add/', views.user_pre_add, name='user_pre_add'),
    
        # request http://127.0.0.1:8000/dept_emp/user_add will invoke the user_add function defined in views.py.
        url(r'^user_add/', views.user_add, name='user_add'),
    
        # request http://127.0.0.1:8000/dept_emp/user_delete/ will invoke the user_delete function defined in views.py.
        url(r'^user_delete/', views.user_delete, name='user_delete'),
    
        # request http://127.0.0.1:8000/dept_emp/user_login will invoke the user_login function defined in views.py.
        url(r'^user_login/', views.user_login, name='user_login'),
    
        # request http://127.0.0.1:8000/dept_emp/user_logout will invoke the user_logout function defined in views.py.
        url(r'^user_logout/', views.user_logout, name='user_logout'),
    
    
    
    
        # request http://127.0.0.1:8000/dept_emp/dept_list will invoke the dept_list function defined in views.py.
        url(r'^dept_list/', views.dept_list, name='dept_list'),
    
        # request http://127.0.0.1:8000/dept_emp/dept_pre_add will invoke the dept_pre_add function defined in views.py.
        url(r'^dept_pre_add/', views.dept_pre_add, name='dept_pre_add'),
    
        # request http://127.0.0.1:8000/dept_emp/dept_add will invoke the dept_add function defined in views.py.
        url(r'^dept_add/', views.dept_add, name='dept_add'),
    
        # request http://127.0.0.1:8000/dept_emp/dept_delete/ will invoke the dept_delete function defined in views.py.
        url(r'^dept_delete/', views.dept_delete, name='dept_delete'),
    
    
    
    
        # request http://127.0.0.1:8000/dept_emp/emp_list will invoke the emp_list function defined in views.py.
        url(r'^emp_list/$', views.emp_list, name='emp_list'),
    
        # request http://127.0.0.1:8000/dept_emp/emp_pre_add will invoke the emp_pre_add function defined in views.py.
        url(r'^emp_pre_add/', views.emp_pre_add, name='emp_pre_add'),
    
        # request http://127.0.0.1:8000/dept_emp/emp_add will invoke the emp_add function defined in views.py.
        url(r'^emp_add/', views.emp_add, name='emp_add'),
    
        # request http://127.0.0.1:8000/dept_emp/emp_delete will invoke the emp_delete function defined in views.py.
        url(r'^emp_delete/', views.emp_delete, name='emp_delete'),
    ]
    

3.6 DjangoHelloWorld / dept_emp / views.py.

  1. views.py
    from django.shortcuts import render
    
    from dept_emp.models import Department, Employee
    
    from django.contrib.auth.models import User
    
    from django.contrib import auth
    
    from django.contrib.auth.decorators import login_required
    
    
    def home_page(request):
        return render(request, 'dept_emp/home_page.html')
    
    def user_login(request):
        username = request.POST.get('username', '').strip()
        password = request.POST.get('password', '').strip()
    
        error_message_login_user_name = ''
    
        error_message_login_password = ''
    
        if len(username) == 0:
            error_message_login_user_name = 'User name can not be empty.'
    
        if len(password) == 0:
            error_message_login_password = 'Password can not be empty.'
    
        if len(username) == 0 or len(password) == 0:
            return render(request, 'dept_emp/home_page.html', {'error_message_login_user_name': error_message_login_user_name, 'error_message_login_password':error_message_login_password})
        else:
            user = auth.authenticate(request, username=username, password=password)
            if user is not None:
                # login user account.
                auth.login(request, user)
    
                if user.is_superuser:
                    return user_list(request)
                else:
                    user.password = password
                    return render(request, 'dept_emp/home_page.html',
                                  {'error_message_login_user_name': 'This user is not superuser, access is denied.', 'user':user})
            else:
                user = User()
                user.username = username
                user.password = password
                error_json = {'error_message': 'User name or password is not correct.', 'user':user}
                return render(request, 'dept_emp/home_page.html', error_json)
            '''
            # get user by username
            user_list = User.objects.filter(username=username)
            if len(user_list) == 0:
                return render(request, 'dept_emp/home_page.html',{'error_message_login_user_name': 'User name do not exist.'})
            else:
                for user in user_list:
                    if user.password == password:
                        if user.is_superuser:
                            return user_list(request)
                        else:
                            return render(request, 'dept_emp/home_page.html',
                                          {'error_message_login_user_name': 'This user is not superuser, access is denied.'})
                    else:
                        return render(request, 'dept_emp/home_page.html',
                                      {'error_message_login_password': 'Password is not correct.'})
            '''
    
    def user_logout(request):
        auth.logout(request)
        return render(request, 'dept_emp/home_page.html')
    
    @login_required()
    def user_list(request):
        # list all users.
        user_list = User.objects.all()
        return render(request, 'dept_emp/user_list.html',
                          {'user_list': user_list})
    
    @login_required()
    def user_pre_add(request):
        return render(request, 'dept_emp/user_pre_add.html')
    
    @login_required()
    def user_add(request):
        name = request.POST.get('name','').strip()
        password = request.POST.get('password', '').strip()
        email = request.POST.get('email', '').strip()
    
        user = User()
        user.username = name
        user.password = password
        user.email = email
    
        error_message_username = ''
        error_message_password = ''
        error_message_email = ''
    
        if len(name) == 0:
            error_message_username += 'User name can not be empty.'
    
        if len(password) == 0:
            error_message_password += 'Password can not be empty.'
    
        if len(email) == 0:
            error_message_email += 'Email can not be empty.'
    
        if len(error_message_username) > 0 or len(error_message_password) > 0 or len(error_message_email) > 0:
            return render(request, 'dept_emp/user_pre_add.html',
                          {'error_message_username': error_message_username, 'error_message_password':error_message_password, 'error_message_email':error_message_email, 'user': user})
        else:
            user_exist_list = User.objects.filter(username=name)
    
            print(len(user_exist_list))
    
            # the user name exist.
            if len(user_exist_list) > 0:
                return render(request, 'dept_emp/user_pre_add.html', {'error_message':'User name exist, please choose another one.', 'user':user})
            else:
                user.is_staff = True
                user.is_active = True
                user.save()
                return user_list(request)
    
    @login_required()
    def user_delete(request):
    
        del_id_list = get_checked_checkbox_value(request, 'user_')
    
        for user_id in del_id_list:
            user = User.objects.get(id=user_id)
            user.delete()
    
        return user_list(request)
    
    
    def get_checked_checkbox_value(request, check_value_prefix):
    
        checked_id_list = list()
    
        for item in request.POST.items():
            print(item)
            if len(item) == 2:
                try:
                    index = item[0].index(check_value_prefix)
                    if index >= 0:
                        checked_id_list.append(item[0][index + len(check_value_prefix)])
                except ValueError as ex:
                    print(ex)
    
        return checked_id_list
    
    
    @login_required()
    def dept_list(request):
        # list all department.
        dept_list = Department.objects.all()
        return render(request, 'dept_emp/dept_list.html',
                          {'dept_list': dept_list})
    
    @login_required()
    def dept_pre_add(request):
        return render(request, 'dept_emp/dept_pre_add.html')
    
    @login_required()
    def dept_add(request):
        dept_name = request.POST.get('dept_name','').strip()
        dept_desc = request.POST.get('dept_desc', '').strip()
    
        dept = Department()
        dept.dept_name = dept_name
        dept.dept_desc = dept_desc
    
        error_message_dept_name = ''
    
        if len(dept_name) == 0:
            error_message_dept_name += 'Department name can not be empty.'
    
        if len(error_message_dept_name) > 0:
            return render(request, 'dept_emp/dept_pre_add.html',
                          {'error_message_dept_name': error_message_dept_name, 'dept': dept})
        else:
            dept_exist_list = Department.objects.filter(dept_name=dept_name)
    
            print(len(dept_exist_list))
    
            # the department name exist.
            if len(dept_exist_list) > 0:
                return render(request, 'dept_emp/dept_pre_add.html', {'error_message':'The department name exist, please choose another one.', 'dept':dept})
            else:
                dept.save()
                return dept_list(request)
    
    
    @login_required()
    def dept_delete(request):
        del_id_list = get_checked_checkbox_value(request, 'dept_')
    
        for dept_id in del_id_list:
            dept = Department.objects.get(id=dept_id)
            dept.delete()
    
        return dept_list(request)
    
    @login_required()
    def emp_list(request, dept_id=-1):
        # list all employee.
        if dept_id == -1:
            emp_list = Employee.objects.all()
            print(emp_list)
            return render(request, 'dept_emp/emp_list.html',
                          {'emp_list': emp_list})
        # list special department employee.
        else:
            # return the employee list of this department.
            emp_list = Employee.objects.filter(dept_id==dept_id)
            return render(request, 'dept_emp/emp_list.html',
                          {'emp_list': emp_list})
    
    
    @login_required()
    def emp_pre_add(request):
    
        user_list = User.objects.all()
    
        dept_list = Department.objects.all()
    
        return render(request, 'dept_emp/emp_pre_add.html', {'user_list':user_list, 'dept_list':dept_list})
    
    
    @login_required()
    def emp_add(request):
        emp_user_id = request.POST.get('emp_user_id','').strip()
        emp_dept_id = request.POST.get('emp_dept_id','').strip()
        emp_mobile = request.POST.get('emp_mobile', '').strip()
        emp_salary = request.POST.get('emp_salary','').strip()
    
        emp_user = User.objects.get(id=emp_user_id)
    
        emp_dept = Department.objects.get(id=emp_dept_id)
    
        emp = Employee()
        emp.user = emp_user
        emp.dept = emp_dept
        emp.emp_mobile = emp_mobile
        emp.emp_salary = emp_salary
    
        error_message_emp_mobile = ''
    
        emp_exist_list = Employee.objects.filter(emp_mobile=emp_mobile)
    
        print(len(emp_exist_list))
    
        # the department name exist.
        if len(emp_exist_list) > 0:
            user_list = User.objects.all()
    
            dept_list = Department.objects.all()
    
            return render(request, 'dept_emp/emp_pre_add.html', {'error_message_emp_mobile':'The mobile number has been used, please use another one.', 'emp':emp, 'user_list':user_list, 'dept_list':dept_list})
        else:
            emp.save()
            return emp_list(request)
    
    
    @login_required()
    def emp_delete(request):
        del_id_list = get_checked_checkbox_value(request, 'emp_')
    
        for emp_id in del_id_list:
            emp = Employee.objects.get(id=emp_id)
            emp.delete()
    
        return emp_list(request)

3.7 DjangoHelloWorld / templates / dept_emp / base.html.

  1. This file will be extended by other Html files.
    <style>
    
        .margin-top-navbar{
            margin-top:30px;
        }
    
        .margin-top-navbar-large{
            margin-top:80px;
        }
    
        @media (min-width: 1200px) {
        .container{
            max-width: 670px;
        }
    }
    
    </style>
    
    <!-- add below Django command to use bootstrap3 in web page.  -->
    {% load bootstrap3 %}
    {% bootstrap_css %}
    {% bootstrap_javascript %}
    
    <div class="container">
       <div class="row">
           <nav class="navbar navbar-inverse navbar-fixed-top">
              <div class="container">
                <div class="navbar-header">
                  <a class="navbar-brand" href="{% url 'dept_emp:home_page' %}">Home Page</a>
                </div>
                <div id="navbar" class="collapse navbar-collapse">
                  <ul class="nav navbar-nav">
                      <li><a href="{% url 'dept_emp:user_list' %}">User</a></li>
                      <li><a href="{% url 'dept_emp:dept_list' %}">Department</a></li>
                      <li><a href="{% url 'dept_emp:emp_list' %}">Employee</a></li>
                  </ul>
                  <ul class="nav navbar-nav navbar-right">
                   <li><a href="{% url 'dept_emp:user_logout' %}">Log Out</a></li>
                 </ul>
                </div>
              </div>
           </nav>
       </div>
    {% block content %}
    
    {% endblock %}
    
    </div>

3.8 DjangoHelloWorld / templates / dept_emp / dept_list.html.

  1. List all departments on this page.
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>List Department Page</title>
    </head>
    <body>
    {% extends "./base.html" %}
    {% block content %}
    
        <div class="container theme-showcase margin-top-navbar" role="main">
    
          <!-- search department -->
          <div class="page-header">
            <div id="navbar" class="navbar-collapse collapse">
              <form class="navbar-form" method="get" action="/dept_search/">
                <div class="form-group">
                  <input name="name" type="text" placeholder="Department Name" class="form-control">
                </div>
                <button type="submit" class="btn btn-success">Search</button>
              </form>
            </div>
          </div>
    
          <!-- department list-->
          <div class="row">
            <div class="col-md-12">
    
              <form class="container" method="post" action="{% url 'dept_emp:dept_delete' %}">
    
                <!-- avoid CSRF verification failed error. -->
                {% csrf_token %}
    
                  <table class="table table-striped">
                    <thead>
                      <tr>
                        <th></th>
                        <th>id</th>
                        <th>Name</th>
                        <th>Description</th>
                      </tr>
                    </thead>
                    <tbody>
                      {% for dept in dept_list %}
                        <tr>
                          <td><input type="checkbox" id="dept_{{ dept.id }}" name="dept_{{ dept.id }}"></td>
                          <td>{{ dept.id }}</td>
                          <td>{{ dept.dept_name }}</td>
                          <td>{{ dept.dept_desc }}</td>
                        </tr>
                     {% endfor %}
                        <tr>
                            <td colspan="4" align="right">
                               <a class="btn btn-primary" href="{% url 'dept_emp:dept_pre_add' %}">Add</a>
                               <input type="submit" class="btn btn-primary" value="Delete" />
                            </td>
                        </tr>
                    </tbody>
                  </table>
              </form>
            </div>
    
          </div>
    
    
    {% endblock %}
    </body>
    </html>

3.9 DjangoHelloWorld / templates / dept_emp / dept_pre_add.html.

  1. Display the add department web page.
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>Add Department Page</title>
    </head>
    <body>
    {% extends "./base.html" %}
    {% block content %}
    
            <form class="container margin-top-navbar-large" method="post" action="{% url 'dept_emp:dept_add' %}">
    
                {% if error_message %}
                    <font color="red">{{ error_message }}</font><br/>
                {% endif %}
    
                <!-- avoid CSRF verification failed error. -->
                {% csrf_token %}
    
                <div class="form-group">
                   <label>Department Name:</label>
    
                    {% if error_message_dept_name %}
                        <font color="red">{{ error_message_dept_name }}</font><br/>
                    {% endif %}
    
                   <input name="dept_name" type="text" placeholder="Department Name" class="form-control" value="{{ dept.dept_name }}">
                </div>
    
                <div class="form-group">
                  <label>Department Description:</label>
                  <input name="dept_desc" type="text" placeholder="Department Description" class="form-control" value="{{ dept.dept_desc }}">
                </div>
    
                <div class="form-group">
                    <button type="submit" class="btn btn-primary pull-right">Add</button>
                </div>
    
            </form>
    
    {% endblock %}
    </body>
    </html>

3.10 DjangoHelloWorld / templates / dept_emp / emp_list.html.

  1. List all employees on this web page.
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>List Employee Page</title>
    </head>
    <body>
    {% extends "./base.html" %}
    {% block content %}
    
        <div class="container theme-showcase margin-top-navbar" role="main">
    
          <!-- employee list-->
          <div class="page-header">
            <div id="navbar" class="navbar-collapse collapse">
              <form class="navbar-form" method="get" action="/emp_search/">
                <div class="form-group">
                  <input name="name" type="text" placeholder="Employee Name" class="form-control">
                </div>
                <button type="submit" class="btn btn-success">Search</button>
              </form>
            </div>
          </div>
    
          <div class="row">
            <div class="col-md-12">
    
               <form class="container" method="post" action="{% url 'dept_emp:emp_delete' %}">
    
                <!-- avoid CSRF verification failed error. -->
                {% csrf_token %}
                  <table class="table table-striped">
                    <thead>
                      <tr>
                        <th></th>
                        <th>id</th>
                        <th>User Name</th>
                        <th>Department</th>
                        <th>Mobile</th>
                        <th>Salary</th>
                        <th>Onboard Date</th>
                      </tr>
                    </thead>
                    <tbody>
                      {% for emp in emp_list %}
                        <tr>
                          <td><input type="checkbox" id="emp_{{ emp.id }}" name="emp_{{ emp.id }}"></td>
                          <td>{{ emp.id }}</td>
                          <td>{{ emp.user.username }}</td>
                          <td>{{ emp.dept.dept_name }}</td>
                          <td>{{ emp.emp_mobile }}</td>
                          <td>{{ emp.emp_salary }}</td>
                          <td>{{ emp.emp_onboard_date }}</td>
                        </tr>
                     {% endfor %}
                        <tr>
                            <td colspan="7" align="right">
                               <a class="btn btn-primary" href="{% url 'dept_emp:emp_pre_add' %}">Add</a>
                               <input type="submit" class="btn btn-primary" value="Delete" />
                            </td>
                        </tr>
                    </tbody>
                  </table>
               </form>
            </div>
    
          </div>
    
    
    {% endblock %}
    </body>
    </html>

3.11 DjangoHelloWorld / templates / dept_emp / emp_pre_add.html.

  1. Add employee page.
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>Add Employee Page</title>
    </head>
    <body>
    {% extends "./base.html" %}
    {% block content %}
    
            <form class="container margin-top-navbar-large" method="post" action="{% url 'dept_emp:emp_add' %}">
    
                <!-- avoid CSRF verification failed error. -->
                {% csrf_token %}
    
                <div class="form-group">
                   <label>User:</label>
                   <select class="form-control" name="emp_user_id" >
                       {% for user in user_list %}
                             <option value="{{ user.id }}"
                             {% if user.id == emp.user.id %}
                                selected
                             {% endif %}
                             >
                                 {{ user.username }}
                             </option>
                       {% endfor %}
                   </select>
                </div>
    
                <div class="form-group">
                   <label>Department:</label>
                   <select class="form-control" name="emp_dept_id">
                       {% for dept in dept_list %}
                          <option value="{{ dept.id }}"
                          {% if dept.id == emp.dept.id %}
                                selected
                             {% endif %}
                          >
                              {{ dept.dept_name }}
                          </option>
                       {% endfor %}
                   </select>
                </div>
    
                <div class="form-group">
                  <label>Employee Mobile:</label>
    
                    {% if error_message_emp_mobile %}
                        <font color="red">{{ error_message_emp_mobile }}</font><br/>
                    {% endif %}
    
                  <input name="emp_mobile" type="text" placeholder="Employee Mobile" class="form-control" value="{{ emp.emp_mobile }}">
                </div>
    
                <div class="form-group">
                  <label>Employee Salary:</label>
                  <input name="emp_salary" type="text" placeholder="Employee Salary" class="form-control" value="{{ emp.emp_salary }}">
                </div>
    
                <div class="form-group">
                    <button type="submit" class="btn btn-primary pull-right">Add</button>
                </div>
    
            </form>
    
    {% endblock %}
    </body>
    </html>

3.12 DjangoHelloWorld / templates / dept_emp / home_page.html.

  1. Display the login web page.
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Django Bootstrap3 Example Home Page</title>
    </head>
    <body>
    {% extends "./base.html" %}
    {% block content %}
        <div class="row">
            <h3 style="margin-top: 80px">
                Login with Django built-in authentication user account and click above menu item to use it.
            </h3>
    
            <form class="container" method="post" action="{% url 'dept_emp:user_login' %}">
    
                {% if error_message %}
                    <font color="red">{{ error_message }}</font><br/>
                {% endif %}
    
                <!-- avoid CSRF verification failed error. -->
                {% csrf_token %}
    
                <div class="form-group">
                   <label>User Name:</label>
    
                    {% if error_message_login_user_name %}
                        <font color="red">{{ error_message_login_user_name }}</font><br/>
                    {% endif %}
    
                   <input name="username" type="text" placeholder="User Name" class="form-control" value="{{ user.username }}">
                </div>
    
                <div class="form-group">
                  <label>Password:</label>
    
                    {% if error_message_login_password %}
                        <font color="red">{{ error_message_login_password }}</font><br/>
                    {% endif %}
    
                  <input name="password" type="password" placeholder="Password" class="form-control" value="{{ user.password }}">
                </div>
    
                <div class="form-group">
                    <button type="submit" class="btn btn-primary pull-right">Login</button>
                </div>
    
            </form>
        </div>
    {% endblock %}
    </body>
    </html>

3.13 DjangoHelloWorld / templates / dept_emp / user_list.html.

  1. Display all added users.
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>List User Page</title>
    </head>
    <body>
    {% extends "./base.html" %}
    {% block content %}
    
        <div class="container theme-showcase margin-top-navbar" role="main">
    
          <!-- search user -->
          <div class="page-header">
            <div id="navbar" class="navbar-collapse collapse">
              <form class="navbar-form" method="get" action="/dept_search/">
                <div class="form-group">
                  <input name="name" type="text" placeholder="User Name" class="form-control">
                </div>
                <button type="submit" class="btn btn-success">Search</button>
              </form>
            </div>
          </div>
    
          <!-- user list-->
          <div class="row">
            <div class="col-md-12">
    
              <form class="container" method="post" action="{% url 'dept_emp:user_delete' %}">
    
                <!-- avoid CSRF verification failed error. -->
                {% csrf_token %}
                  <table class="table table-striped">
                    <thead>
                      <tr>
                        <th></th>
                        <th>id</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Is Staff</th>
                        <th>Is Active</th>
                      </tr>
                    </thead>
                    <tbody>
                      {% for user in user_list %}
                        <tr>
                          <td><input type="checkbox" id="user_{{ user.id }}" name="user_{{ user.id }}"></td>
                          <td>{{ user.id }}</td>
                          <td>{{ user.username }}</td>
                          <td>{{ user.email }}</td>
                          <td>{{ user.is_staff }}</td>
                          <td>{{ user.is_active }}</td>
                        </tr>
                     {% endfor %}
                        <tr>
                            <td colspan="6" align="right">
                               <a class="btn btn-primary" href="{% url 'dept_emp:user_pre_add' %}">Add</a>
                               <input type="submit" class="btn btn-primary" value="Delete" />
                            </td>
                        </tr>
                    </tbody>
                  </table>
              </form>
            </div>
    
          </div>
    
    
    {% endblock %}
    </body>
    </html>

3.14 DjangoHelloWorld / templates / dept_emp / user_pre_add.html.

  1. Add user page.
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>Add User Page</title>
    </head>
    <body>
    {% extends "./base.html" %}
    {% block content %}
    
            <form class="container margin-top-navbar-large" method="post" action="{% url 'dept_emp:user_add' %}">
    
                <!-- avoid CSRF verification failed error. -->
                {% csrf_token %}
    
                <div class="form-group">
                   <label>User Name:</label>
    
                    {% if error_message_username %}
                        <font color="red">{{ error_message_username }}</font><br/>
                    {% endif %}
    
                    {% if error_message %}
                        <font color="red">{{ error_message }}</font><br/>
                    {% endif %}
    
                   <input id="name" name="name" type="text" placeholder="User Name" class="form-control" value="{{ user.username }}">
                </div>
    
                <div class="form-group">
                  <label>Password:</label>
    
                    {% if error_message_password %}
                        <font color="red">{{ error_message_password }}</font><br/>
                    {% endif %}
    
                  <input name="password" type="password" placeholder="Password" class="form-control" value="{{ user.password }}">
                </div>
    
                <div class="form-group">
                  <label>Email:</label>
    
                    {% if error_message_email %}
                        <font color="red">{{ error_message_email }}</font><br/>
                    {% endif %}
    
                  <input name="email" type="text" placeholder="Email" class="form-control" value="{{ user.email }}">
                </div>
    
                <div class="form-group">
                    <button type="submit" class="btn btn-primary pull-right">Add</button>
                </div>
    
            </form>
    
    {% endblock %}
    </body>
    </html>

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.