Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use both MySQL and MongoDB in Django backend [closed]
I'm going to build a simple user post backend using Django with MySQL and MongoDB. But Django provides SQLite by default and I don't know how to hybrid MySQL and MongoDB and use them in development. Is there anyone who can help me with end-to-end guide? -
cannot accept the name from user input and the file does not enter the image directory located in the scanner directory App
So this program runs smoothly status code 200 and Developer Status does not show error code, I have checked in the models, views, and forms files but the logic of running the system I think is correct. I really appreciate all the help. I alrd try debug from this project Links scanner.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Scanner</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous" /> <style> body { display: flex; flex-direction: column; min-height: 100vh; margin: 0; } main { flex: 1; padding: 20px; } </style> </head> <body> <!-- Navbar --> <nav class="navbar bg-primary-subtle navbar-expand-lg border border-black"> <div class="container-fluid d-flex justify-content-evenly"> <div class="container-fluid d-flex justify-content-start align-items-center"> <i class="fa-brands fa-python fa-2xl pt-0"></i> <p class="fw-bold fs-4 pt-2">Tubes Citra Digital</p> </div> <div class="navbar-collapse collapse d-flex align-items-start"> <ul class="navbar-nav"> <li class="nav-item "> <a class="icon-link icon-link-hover link-offset-2 link-offset-3-hover link-underline link-underline-opacity-0 link-underline-opacity-75-hover" style="--bs-icon-link-transform: translate3d(0, -.125rem, 0);" href="{% url 'home:home_page' %}"> <i class="fa-solid fa-right-to-bracket bi" aria-hidden="true"><use xlink:href="#clipboard"></use></i> Home </a> </li> </ul> </div> </div> </nav> <main> <!-- From file--> <!-- {% url 'cartoon:cartoon_result' %}, Ubah action disini menjadi app dan urls pada setiap APP--> <form id="cartoon-form" action="{% url 'scanner:scanner_page' %}" method="post" class="validate container-fluid d-flex justify-content-center flex-column gap-3" enctype="multipart/form-data" > {% csrf_token %} … -
Transaction atomic with Django signals
Inside the transaction atomic block am updating table1 and creating table2. Where table2 use foreign key of table1. Table1 is updated successfully and table 2 is created. But when django signals of table2 is called, am getting the old instance of table1. I need the latest instance of table1 inside Django signals. -
AWX + Hashicorp Vault django.request Bad Request
In order to improve my AWX management for my team, i'm currently trying to configure Hashicorp Vault Credentials but i'm having some errors and doubt. Usually in my Ansible project I run from a Debian server, I'm used to set up Vault secrets using lookup like this (works in var file or within vars:) ### Vault Configuration ansible_hashi_vault_token="{{ lookup('env','VAULT_ANSIBLE') }}" my_secret="{{ lookup('community.hashi_vault.vault_kv2_get', 'my_secret', engine_mount_point='kv/', token=ansible_hashi_vault_token) }}" #### Credentials (compte de service ansible) #### ansible_user="{{ my_secret.secret.ansible_user_from_vault}}" Ansible will seek for an environment variable which is called 'VAULT_ANSIBLE' that is the result token of an AppRole call to my vault server. It allows to run playbook without writing any token in the code. Now after adding project in AWX, i'm trying to make the Vault part working => I created Credentials with HashiCorp Vault Secret Lookup as you can see here. Simply add Server URL + Token for testing. When I click on Test, no matter what secrets I want to retrieve I always have this error Here's my questions : which log file can give me more information about the credentials/api call to Vault? Is there any thing I miss for this peculiar configuration ? I tried to add my root.CA … -
Psycopg2 - Django 3.0.5
I am trying to makemigrations in my project with Django using postgresql. But I have been having the following error: (agenda_api) C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agendadj\agenda>python manage.py makemigrations Traceback (most recent call last): File "C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agenda_api\lib\site-packages\django\db\backends\postgresql\base.py", line 25, in <module> import psycopg2 as Database File "C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agenda_api\lib\site-packages\psycopg2\__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ImportError: DLL load failed while importing _psycopg: No se puede encontrar el módulo especificado. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agendadj\agenda\manage.py", line 21, in <module> main() File "C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agendadj\agenda\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agenda_api\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agenda_api\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agenda_api\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agenda_api\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agenda_api\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\felip\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agenda_api\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\felip\OneDrive\Escritorio\Managment\Cursos\Django\agenda_api\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class … -
Django Production Deployment Issue: Blog Articles Stacking and Unexpected <strong> Tags
I'm facing a rather perplexing issue with deploying a Django site on which I'm working. I'm using Django version 4.2.5, and my development environment is on Windows. The production deployment is on O2Switch using CPanel. To deploy the code, I'm using CPanel's Python Application Manager and fetching the code via push/pull from GitHub. The problem I'm encountering is as follows: after the production deployment, the blog articles are not displaying correctly. Instead of appearing side by side, they are stacking on top of each other. This issue doesn't occur locally, and upon investigation, I noticed that <strong> tags are being generated with each iteration, disrupting the styling I've implemented. Screen of code with inspector Screen of code with inspector Screen render in prod Screen render in prod I tested the site in a pre-production environment on a test URL (on the same server but in a different directory), and everything works correctly. However, once in production, the issue arises. Do you have any ideas about the possible cause of this unexpected behavior during production deployment? Thanks in advance for your assistance and suggestions! Additional context: Development environment: Windows Production environment: O2Switch with CPanel Django version: 4.2.5 I've included screenshots of … -
Django change fuzzy threshold while running makemessages
When Im running python manage.py makemessages I have fuzzy lines in my django.po file, for example : #, fuzzy #| msgid "Last Month" msgid "Last Year" msgstr "Dernier mois" This is due to the gettext.merge command used by django as explained here : https://hexdocs.pm/gettext/Mix.Tasks.Gettext.Merge.html#module-options To solve this issue, I should use the --no-fuzzy tag or reduce the --fuzzy-threshold. But my issue is that there is no way to do that using django makemessages command (at least I can't find it) Is there a workaround I can use to fix my problem please? -
How to overwirte Django Backend?
I would like to give access to the backend of a Django project for all my users who is registered in a specified Azure AD group. I use django_microsoft_auth package to handle SSO Usage — django-microsoft-auth When I log for the 1st time with an account from Azure AD, the account is created in Django. But I would like to : change the loggin (by default is using the email address as loggin), force is_staff = True and add the user to a django group. I think I must overwrite the authenticate method from BaseBackend. I did follow the doc DjangoProject but I having trouble to make it work urls.py urlpatterns = [ path('admin/', admin.site.urls), path('microsoft/', include('microsoft_auth.urls', namespace='microsoft')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py INSTALLED_APPS = […, 'django.contrib.admin', 'django.contrib.auth', 'microsoft_auth, 'django.contrib.sites' …] AUTHENTICATION_BACKENDS = ["microsoft_auth.backends.MicrosoftAuthenticationBackend","django.contrib.auth.backends.ModelBackend","myproject.signals.SettingsBackend"] ADMIN_LOGIN = env(“my_login”) ADMIN_PASSWORD = env(“my_password_h”) In signals.py (located in the same directory of settings.py) I used the code from the django doc and I try to add a groupe to the user. from django.conf import settings from django.contrib.auth.backends import BaseBackend from django.contrib.auth.hashers import check_password from django.contrib.auth.models import User, Group, Permission class SettingsBackend(BaseBackend): def authenticate(self, request, username=None, password=None): login_valid = settings.ADMIN_LOGIN == username pwd_valid = check_password(password, … -
Why the CSS Styles not working for h1 in home.html file? is there any special method to do styling of for loop elements in django?
[[enter image description here](https://i.stack.imgur.com/jnAJN.png)](https://i.stack.imgur.com/PTYbY.png) I am trying to apply some styling to the list of elements but nothing is working for loop elements. Base.html is working fine i checked there is no error in that. Thanks for your help -
Django models.py I want a function go to a variable
I want the def remain and the result of it to go to the field d_remain but whatever I use the function it doesn't show anything, it shows only negative numbers, this is my code, this is the base code give me a way to make it happen thank you. class sub(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key = True, editable = False) provider = models.CharField(max_length=70) tier = models.CharField(max_length=40) date_started = models.DateField(auto_now=False, auto_now_add=False) date_end = models.DateField(auto_now=False, auto_now_add=False, ) author = models.ForeignKey(User, on_delete=models.CASCADE) price = models.DecimalField(max_digits=7, decimal_places=2, default=0) d_remain = models.IntegerField()#I want the value of def remain go to this filed def remain(self): today = date.today() remaining_days = (self.date_end - today).days return(remaining_days) def get_absolute_url(self): return reverse('sub-detail', kwargs={'pk':self.id}) -
Frontend + backend on aws lightsail
So I have a webapp with reactjs as frontend and django as backend and mysql as database. Now I have my django deployed on heroku which i want to put on my lightsail server as well. My frontend is also deployed on lightsail same as my mysql instance (I did not use containers). It for now only has 1 page as the webapp was not yet ready. Now that everything is ready I want to deploy everything on the Lightsail server. It has 2gb of RAM and 1vCPU. I was wondering what the best way is to go about the deployment of this. My main concern is about concurrent users, with the biggest concern being the backend (not sure how many concurrent users it can hold). So my questions is can this server hold many concurrent users (i know you need more information to calculate this so approximation is fine) I look forward to hearing everyones ideas thanks! -
How can localhost and 127.0.0.1 share the same request in Django/Vue?
In my Django application, I'm authenticating a user on the backend, with port 8000. Upon success, the user is redirected to the frontend on port 5173. After configuring CORS and CSRF correctly, I was able to successfully reproduce this when I accessed localhost:8000/login. It redirected to localhost:5173/ and the authenticated content was provided. The issue is however, when the user attempts to access the URL provided by Django (127.0.0.1:8000), it gets redirected to the localhost:5173 origin, meaning they don't share the same resources as they are different URLs. Are there any practices or workaround in this scenario? Or is it assumed that the user should always be accessing localhost? I tried to execute the same_site= None option, however, I believe that is for HTTPS which I have not configured yet -
Can I generate token using DRF after I validate the user using LDAP?
In the beginning I will ask everyone to excuse me if my question is wrong/not properly framed because I am new starting something new which I am totally not aware of, I need to learn this as it is very much needed for my work. Question goes as below, I am planning to develop a framework using Django, to authenticate users to use my framework I need to validate user using my org LDAP. In my framework I have multiple API endpoints (as I am developing API end points using Django), for each end point I need user to have permission/authentication. Here is the catch, when I am trying to authenticate user using LDAP I am not able to generate tokens (access or refresh). If I generate token I am not able to authenticate user using LDAP. I tried integrating both part but I am getting error ( may be I dont know how to integrate as I am new to Django). I need help from you guys like....I need to validate user using LDAP and after validation I need to generate token (access and refresh). Please help me with this... Below is my code snippet. Code of LDAP validation: … -
how to automatically kill sessions on postgres db in python django, before django tests recreate the db
django recreates our postgres test database on start, however in some cases there are sessions open. I can kill the sessions with SELECT 'SELECT pg_terminate_backend(' || pg_terminate_backend(pg_stat_activity.pid) || ');' FROM pg_stat_activity WHERE pg_stat_activity.datname = 'MY_DBNAME' AND pg_stat_activity.pid <> pg_backend_pid(); but currently, I do that manually as needed from SquirrelSQL. How can this be done automatically before django recreates the DB (very early in the test setup process). THis is needed because otherwise the delete DB fails due to connected sessions. -
Can't figure out how to make a simple "add to favourite" view with Django and HTMX
In my streaming app (for portfolio), I've been trying desperately to make a very simple function to add a film to a user's list. The simple thing : a heart, when you click it adds or removes the film to your list and change the heart colour. I'm trying to make it with a class based view and with HTMX. All of the similar application I found online were made with function based views and older version of Django. I don't want and copy/paste weird code, I want to understand. But whatever I do (just spent 2 hours with ChatGPT, trying a million thing), I keep on getting one of two errors : a Method Not Allowed or a NoReverseMatch. Whatever I do, I get one of these. I've tried many different things, but right now, this is my code : My view : class AddToFavoriteView(CustomLoginRequiredMixin, UpdateView): model = Film fields = ["favorite"] template_name = "includes/heart.html" http_method_names = ["get", "post"] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.object.favorite.filter(id=self.request.user.id).exists(): context["is_favorite"] = True else: context["is_favorite"] = False print(f"is_favorite: {context['is_favorite']}") return context def post(self, request, *args, **kwargs): self.object = self.get_object() print("Trying to add to favs.") film = Film.objects.get(pk=self.object.pk) print(f"{film.title}") if film.favorite.filter(id=request.user.id).exists(): film.favorite.remove(request.user) is_favorite … -
Can still access login page after logging in using ReactJS and dj-rest-auth
I'm using dj-rest-auth for the authentication endpoints in my django project and reactjs in the frontend of my project. What happens if after I login, the user can still go to the /login page which should not. Here's my LoginForm code: import React, { useState } from 'react'; import { Form, Button, Alert, Container } from 'react-bootstrap'; import axios from 'axios'; import { useNavigate } from 'react-router-dom'; const LoginForm = () => { const navigate = useNavigate(); const [credentials, setCredentials] = useState({ username: '', password: '' }); const [error, setError] = useState(null); const handleChange = (e) => { const { name, value } = e.target; setCredentials((prevCredentials) => ({ ...prevCredentials, [name]: value })); }; const validateCredentials = () => { if (credentials.username.length < 4) { setError('Username must be longer than 4 characters.'); return false; } if (credentials.password.length < 8) { setError('Password must be at least 8 characters.'); return false; } return true; }; const handleSubmit = async (e) => { e.preventDefault(); if (!validateCredentials()) { return; } try { const response = await axios.post('http://localhost:8000/api-auth/login/', credentials); const token = response.data.token; localStorage.setItem('token', token); navigate('/rants'); } catch (error) { handleLoginError(error); } }; const handleLoginError = (error) => { console.log(error.response); if (error.response && error.response.status === 400) … -
Creating Django Models Without Rounding off Decimal Fields
For now, when I save an amount like 5400.5789, it is being saved as 5400.58. However, I want it to be saved as 5400.57 only. I don't want to round off the decimal places. How can I achieve that? class PerTransaction(models.Model): amount = models.DecimalField(default=0, max_digits=10,decimal_places=2, verbose_name = "Transaction Amount") Database: PostgreSQL -
Optimising Gunicorn Configuration for High-Concurrency I/O-Intensive Tasks with Low CPU and Memory Usage
I'm currently managing a Django application hosted on a 16-core server. Despite having 25% maximum CPU and memory usage, performance starts to degrade at around 400 active connections according to Nginx statistics. Currently, we have 12 Gunicorn workers, which is lower than the recommended (2 * CPU) + 1. However, as per Gunicorn's documentation, 4-12 workers should handle hundreds to thousands of requests per second. Question about Worker Configuration: Has anyone successfully used a number of workers exceeding the 12 as mentioned, especially in scenarios with low CPU and memory usage? Any insights into optimal configurations for high-concurrency scenarios in such situations? Performance Optimization: Our application primarily involves I/O tasks. Despite optimizing database queries and having low CPU and memory usage, performance remains an issue. Would increasing the number of workers or introducing threads (summing up to (2 * CPU) + 1) be a viable solution for improving performance in I/O-bound scenarios with seemingly underutilized resources? This means setting workers to 33 if I use (2 * CPU) + 1, or maybe 10 workers with 3 threads? Additional Considerations: We are considering tweaking Gunicorn configurations, but want to ensure we're on the right track given the low CPU and memory … -
HTTP APIs vs Restful APIs
What is the major difference in HTTP and Restful API. How is each implemented? Which is better in which situation? And any other thing to be noted to understand the difference in a better way. I am learning DJANGO with DRF. And it is my first time working on Rest architecture. -
Django middleware is executed at every API call
I created a middleware to record the activity log for user login but it executes at every API call. The ActivityLog is to record the entries. Middleware.py class UserActivityMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Set a flag in the session to indicate that the user has been logged in during this session request.session['user_logged_in'] = request.session.get('user_logged_in', False) response = self.get_response(request) # Check if the user is authenticated, has just logged in, and hasn't been logged during this session if ( request.user.is_authenticated and request.user.last_login is not None and request.session.get('user_logged_in', False) is False and not request.path.startswith('/static/') and not request.path.startswith('/media/') ): print("reached middleware") print(f"User: {request.user.username}") print(f"Last Login: {request.user.last_login}") print(f"Session Flag: {request.session.get('user_logged_in')}") print(f"Request Path: {request.path}") # Log the user login activity ActivityLog.objects.create( user=request.user, action="Login", target_model="User", target_object_id=request.user.id, details=f"User {request.user.username} logged in at {timezone.now()}." ) # Set a flag in the session to indicate that the user has been logged in during this session request.session['user_logged_in'] = True return response What should I do to reduce it to a single execution i.e. when the user logs in? -
Django Autocomplete Light: multiple selection from List (not Model)
I know how to use DAL (Django Autocomplete Light) to allow a single selection, like in the tutorial: CHOICE_LIST = [ ['FR', 'France'], ['FJ', 'Fiji'], ['FI', 'Finland'], ['CH', 'Switzerland'] ] class CountryAutocompleteFromList(autocomplete.Select2ListView): def get_list(self): return CHOICE_LIST class CountryForm(forms.ModelForm): country = autocomplete.Select2ListChoiceField( choice_list=CHOICE_LIST, widget=autocomplete.ListSelect2(url='country-list-autocomplete') ) However, I can't find any lead in the documentation or DAL source code to implement multiple selection, e.g. to allow users to pick 2 countries or more. Has anyone a working example I could learn from? -
How do I modify the Django training project (poll voting system) so that it has a home page at the root of the domain?
mysite/urls.py (main app with a settings.py) from django.contrib import admin from django.urls import include, path from . import views urlpatterns = [ path('admin/', admin.site.urls), path("polls/", include("polls.urls")), path('', ?), ] polls/urls.py - Currently contains the following information. notice even though path("", ..) looks like "domainname.com/" root location, it is "domainname.com/polls/" is that became of the app_name = "polls" namespace?) How do I add a mapping for the root of the domain (domainname.com/) so I can add my own homepage? from django.urls import path from . import views app_name = "polls" # Namespace to url template tag can find correct url urlpatterns = [ # ex: /polls/ path("", views.index, name="index"), # ex: /polls/5/ path("<int:question_id>/", views.detail, name="detail"), # ex: /polls/5/results/ path("<int:question_id>/results/", views.results, name="results"), # ex: /polls/5/vote/ path("<int:question_id>/vote/", views.vote, name="vote"), ] I have noticed some github projects are mapping the home page like so videoapp/urls.py urlpatterns = [ path("admin/", admin.site.urls), path("", include("videos.urls")), ] And mapping them to the view like so videos/urls.py from django.urls import path from . import views # http://127.0.0.1:8000/ # http://127.0.0.1:8000/home # http://127.0.0.1:8000/videos # http://127.0.0.1:8000/videos/1 # http://127.0.0.1:8000/videos/video-1 urlpatterns =[ path("",views.home,name="home"), path("home",views.home), path("videos",views.videos,name="videos"), path("videos/<int:id>",views.videodetails,name="details"), ] However I cannot do this as it automatically is starting the url from 'polls/'. What is a … -
Complex Django Query Spanning Multiple Tables
Table set up for reference only: class CustomerInformation(Model): first_name = charfield() last_name = charfield() class CustomerCreditInformation(Model): customer = OneToOneField(CustomerInformation, on_delete=CASCADE) max_credit_amount = DecimalField( max_digits=10, decimal_places=2, verbose_name='Credit Amount') due_in = CharField(choices=PAYMENT_DUE_DATES, max_length=4, verbose_name='Payable before') Class Invoice(Model): financial_party = models.ForeignKey( CustomerInformation, on_delete=models.CASCADE, null=True, verbose_name="Submit Invoice To:") date_billed_original = models.DateField( verbose_name='Billed Date', editable=False, null=True) class InvoicePayment(models.Model, ListViewModelFunctions): invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE) amount = models.DecimalField( max_digits=12, decimal_places=2, verbose_name='Payment Amount') class Charges(models.Model, ListViewModelFunctions): invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=12, decimal_places=2) Invoices could be created, but not billed, meaning charges may be created on invoices that have not been billed. Given the following table set up, is there a way to create a "single" query from the Customer table that accomplishes the following (listed in order of difficulty): Concat First/Last Name (simple concat here works no issues/already completed) Annotate the Customers Credit Max Amount (Simple annotate here works/already completed) Annotate outstanding charges for all billed invoices (the filter is what throws me off) Annotate The total outstanding based on the date billed being less than timezone.localdate() - timedelta(customercredit__due_in). The resulting query would return a data dict with: Name, Customer Credit Amount, Total Outstanding Invoices (billed to date), Total Outstanding Invoices from past due invoices only. … -
Django not picking up static files like css and js
my Django app failed to load static files and gave me a 404 file not found error while I'm sure that the files do exist there. And I'm pretty sure that it is looking for it in the right directory. I'm attaching the error screenshot along with my Django static settings and the code part of HTML where I call the static file. error screenshot app directory static file settings: STATICFILES_DIR = [os.path.join(BASE_DIR, 'static')] STATIC_URL = '/static/' some CSS that I called in the HTML file (yes I did include load static): <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <linkhref="https://fonts.googleapis.com/css2family=Noto+Sans+JP:wght@100;300;400;700;900&display=swap" rel="stylesheet"> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet" type="text/css"> <link href="{% static 'css/bootstrap-icons.css' %}" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="{% static 'css/magnific-popup.css' %}" type="text/css"> <link href="{% static 'css/aos.css' %}" type="text/css" rel="stylesheet"> -
How to render in real-time the django model's field using django channels?
I already set up the connection between the server side which are the asgi.py, consumers, and routing, that is already listening to client side using javascript. But I don't know how to render out, in real time, the field in that one model to my javascript that'll will be shown in HTML. This is the JavaScript: var socket = new WebSocket(`ws://${window.location.host}/orders/`); socket.onmessage = function (e) { var data = JSON.parse(e.data); document.getElementById("testingMessage").innerText = data.message; }; This is the consumers.py so far: class OrderConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() await self.send(json.dumps({'message':"testing"})) async def disconnect(self, close_code): await self.disconnect() And this is the routing.py: from . import consumers from django.urls import path websocket_urlpatterns = [ path('time/', consumers.OrderConsumer.as_asgi()) ] This is the models.py model: class BillingAddress(models.Model): isComplete = ( ('NO', 'NO'), ('YES', 'YES'), ) user = models.ForeignKey(User, on_delete=models.CASCADE) full_name = models.CharField(default='', null=True, max_length=1000) contact_number = models.CharField(default='', null=True, max_length=1000) full_address = models.CharField(default='', null=True, max_length=1000) message = models.CharField(default='', null=True, max_length=1000) total_price = models.CharField(default='', null=True, max_length=1000) is_complete = models.CharField(choices=isComplete, null=True, default='') def __str__(self): return self.full_name def save(self, *args, **kwargs): if self.full_name: self.slug = slugify(self.full_name) super(BillingAddress, self).save(*args, **kwargs) All I want to achieve is to render that one field from the model (full_name) through the HTML in real time. …