Django Dialogue App Django.How

Author avatar wrote on 26/05/2022

Create App

1.type python startapp dialogue dialogue is an example of app name

2.go to the file dialogue/ and declare your class

3.Go to your app folder and open then declare your app under INSTALLED_APPS


4.Create the migration, make sure in the terminal you are in the right folder and pipenv shell is running then type python makemigrations dialogue this will create the necessary python files

5.Make the complete migration to create the tables in the datbase by typing python migrate

Configuration Admin Area

Open dialogue/ file and import the new models and register them under admin:

Build Front Facing Page

Open file dialogue/ and Bring the models we need

from django.shortcuts import render
from django.template.loader import render_to_string
from .models import Chat, Message, ChatNotifications

from django.http import JsonResponse

2.Define index page for dialogue:

This function will render page on first load and add new messages on form submiting

3.Create function for ajax requests

This function will receive ajax requests and send back data to display.

Full file

Creating URLs

1.Create file in app folder

2.Add URL rules to this file

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='dialogue'),
    path('reload/',views.reload, name='reload')

3.In the main app folder, oper file and include the file you created

urlpatterns = [
    path('dialogue/', include('dialogue.urls')),

Create HTML Template for this App

1.Create dialogue folder inside templates

2.Create index.html file inside templates/dialogue folder and copy html code in this file

{% extends 'base.html' %}

{% load static %}

{% block content %}

{% if chats %} {% include 'dialogue/parts/_chats.html' %} {% endif %}
{% if chats %} {% if chats.count == 1 %}
{% if chats.0.messages %} {% include 'dialogue/parts/_message.html' %} {% endif %}
{% else %} {% for chat in chats %}
{% if chat.messages %} {% include 'dialogue/parts/_message.html' %} {% endif %}
{% endfor %} {% endif %} {% endif %}
{% csrf_token %}
{% endblock %}

3.Create folder “parts“ in “templates/dialogue“ folder.

Inside this new folder we need to add two new files:


Last thing, we need to add new js file. Go to our static folder and create file “dialogue.js“ with this js code

Do not forget to run “python collectstatic“ command in our terminal, and add this file in “base.html“

NOTICE: in _header.html file we need to change one element.

To this span near message link

need to add id="messages-count" and style="display:none"

Full list of file for this app

We stand with Ukraine