Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF self.paginate_queryset(queryset) doesn't respect order from self.get_queryset()
i have a ListAPIView with custom get_queryset() where it ordered by a custom annotate() field called 'mentions' i have customized my list function in ListAPIView, but when calling self.paginate_queryset() with the queryset i'm getting different result(not getting the first data from queryset class KeywordList(ListAPIView): """return list of keywords """ pagination_class = CursorPagination serializer_class = ListKeywordSerializer total_reviews_count = Review.objects.all().count() ordering = ["-mentions"] def get_queryset(self): queryset = Keyword.objects.all() queryset = queryset.annotate(...).order_by('-mentions') def list(self, request, *args, **kwargs): queryset = self.get_queryset() print('queryset first', queryset[0]) page = self.paginate_queryset(queryset) print('page first', page[0]) here is the print log: queryset first good page first design program as you can see, i'm getting different result(first index) after running the queryset through self.paginate_queryset(queryset) how can i fix this? -
Django + RabbitMQ multiple Tabs
In my project, I'm using pika/RabbitMQ to send a SQL script from my web page to a remote database. This database processes and returns the conclusion. My problem is that I want to give my users the possibility to use multiple tabs to connect to different databases simultaneously to expedite remote maintenance. However, I'm facing a significant challenge when attempting to use Django's local storage and session storage. Since each tab shares the same session, changing the session affects everyone. I'm using a control inside my consumer to manage Rabbit consumers individually and to stop only the one that received a response, or to force a consumer to stop if the user refreshes the page. I'm open to any suggestions for a solution. Should I use websockets? Try generating an ID on the client side for control? Any other good solutions? This is my consumer code: import pika from comandos.connectionAMQP.connectionSettings import getConnectionRabbitMQ class MessageReturn: def __init__(self, consumer_key) -> None: self.consumer_key = consumer_key self.message_body = None self.is_consuming = True def set_message_body(self, body): self.message_body = body def get_message_body(self): return self.message_body def stop_consuming(self): self.is_consuming = False # Lista para armazenar instâncias de MessageReturn consumers = [] def create_consumer(consumer_key): global consumers consumer = MessageReturn(consumer_key) … -
Error message "failed building wheel for mysqlclient" when I try to use a pip installation in VS code
I am trying to connect mysql(which I have installed) to a Django project. I try to run 'pip install mysqlclient', but I keep receiving an error message. I am using python 3.12 on Windows 64-bit. Can someone please help? The full output is below: pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.2.0.tar.gz (89 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pyproject.toml) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for mysqlclient (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [46 lines of output] # Options for building extention module: library_dirs: ['C:/mariadb-connector\lib\mariadb', 'C:/mariadb-connector\lib'] libraries: ['kernel32', 'advapi32', 'wsock32', 'shlwapi', 'Ws2_32', 'crypt32', 'secur32', 'bcrypt', 'mariadbclient'] extra_link_args: ['/MANIFEST'] include_dirs: ['C:/mariadb-connector\include\mariadb', 'C:/mariadb-connector\include'] extra_objects: [] define_macros: [('version_info', (2, 2, 0, 'final', 0)), ('version', '2.2.0')] running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-cpython-312 creating build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\connections.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\converters.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\cursors.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\release.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb\times.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb_exceptions.py -> build\lib.win-amd64-cpython-312\MySQLdb copying src\MySQLdb_init_.py -> build\lib.win-amd64-cpython-312\MySQLdb creating build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\CR.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying src\MySQLdb\constants\ER.py -> build\lib.win-amd64-cpython-312\MySQLdb\constants copying … -
How to sync the current user logged in to the Django web server with the activities in the React client?
In my current application I am using Django as the backend with React as the frontend with JWT tokens for authentication. Currently I am able to sign in an out of React correctly but when I manually visit Django server through http://localhost:8000/ on my browser I notice that the current user isn't changed regardless of whether I sign in or out in React. I also want the vice versa to be accomplished where manual logins and logouts from Django would affect my current authentication in React. I have managed to implement this by using web sockets to send a message based on my current authentication status and performing the required authorisation in React based on the message. However, I am struggling with implementing the reverse where my activities in React will change my current user in Django. I tried using responses from React through sockets when the user signs in or out and based on these responses I tried to change the current user in Django but no changes were noticed with the current implementation. If anyone has any suggestions as to what I may do then please suggest them. I attached the relevant code for my consumers.py, views.py, SignIn.js … -
Overridden function calling base function
I've been working on learning Django from MDN Web Docs. In part 6, this comes up: "We might also override get_context_data() in order to pass additional context variables to the template (e.g. the list of books is passed by default). The fragment below shows how to add a variable named "some_data" to the context (it would then be available as a template variable)." class BookListView(generic.ListView): model = Book def get_context_data(self, **kwargs): # Call the base implementation first to get the context context = super(BookListView, self).get_context_data(**kwargs) # Create any data and add it to the context context['some_data'] = 'This is just some data' return context I am confused how the overridden "get_context_data" is calling itself in essence, but without recursion. Does super only call the overridden function after it is fully declared, or is this behavior not exclusive to super. Link: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Generic_views -
Adding space between two divs on the same without assigning a px value?
The main problem is that there is no separation between my two divs when I use the typical css trick of using the float: left;, float: left; and clear:both; . However, it sets the divs right next to each other and I have seen that I can use margin left or right 20px, but I was wondering is that was a way which would automatically factor in scaling without being too complicated. Ideally the left hand div will stick to the right-side and the right hand div will stick to the right-side. I have attached my current code. I am using Python Django. CSS and HTML <div> <div style = "float: left;">Due</div> <div style = "float: right;"">Completed</div> <div style="clear:both;"></div> </div> Output The plan is to then repeat this for the 0 and 1 in the picture, I have not included this in the code. PS I do plan on moving my css to a dedicated css file and not have it like this but I found it way easier to try different combinations in this format -
What's the analog of requests.get in Django REST Framework?
I am currently using requst.get() then convert it to an HttpResponse of djnago.http but I expect DFR to have something for that purpose. full code is def site(request, site_url): response = requests.get(site_url) http_response = HttpResponse( content=response.content, status=response.status_code, content_type=response.headers['Content-Type'] ) return http_response -
Combine django-filter with rangefilter
I have an app that successfully combines single input filters such as: Company name Payment Status ... All of these filters are nicely created by using the django_filters app (pypi link). Also, I can apply more than 1 filter at once, so I can search for Payments for a Specific company. I would like to add a range filter that filters by values between 2 numbers: Payment Amount To do this, I am trying to use django-rangefilter (pypi link) which is an extension of django_filters, and has specific out-of-the-box templates and functionality for Numeric Range Filters and Date Range Filters. Problem: After adding the rangefilter, and submitting a filter request, the range filter clears up all of the other filters, and only applies the range filter. Has anyone ever faced this need and problem ? What would be the least-custom-code approach recommended ? Any other modules thats could help here, noting that it must work with django_filters out the box. -
How to make the @apply tailwind directive to work in Django?
do u know how to make the @apply tailwind directive to work in django static css files? Screenshot My css static files are working perfectly, but the @apply directive not. I followed the official docs to set tailwind and django: Django + Tailwind -
Django modelform not rendering when included in another template
I'm still fairly new to Django and trying to get through the docs and basics. My sticking point is that I cannot get a working modelform on page X to be included inside of another template Y. It's a very simple example derived from django docs. I've looked at the many other SO posts and have tried the obvious fixes to no avail. (they did fix bigger issues but I'm left with this) I ultimately plan to embed modelforms into modals, but at this stage cannot even render them into other html and some help would be appreciated. Python 3.12, Django 4.2.7 on SqLite Model: class Title(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) def __str__(self): return self.title Form: class TitleForm(ModelForm): class Meta: model = Title fields = '__all__' View for the Title modelform (works): def add_title(request): if request.method == 'POST': form = TitleForm() context = {'form': form} print(request.POST) # to see if the form works return render(request, 'add_title.html', context) else: form = TitleForm() return render(request, 'add_title.html', {'form': form}) Here is the add_title.html file: {% block content %} <h1>Test Form</h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% endblock %} The modelform is working at the page … -
Convert rawsql to Django
I am using PostgreSQL DB. this is my SQL query. I want to convert this to Django. I tried but I could get how the logic is applied in Django. lead over is not getting in Django SELECT a1."userId", s3.id as projectid, count(s1."checkIn" :: date) as check_in_count, max(a2."payrollFileNumber") as number, max(a1."firstName") as name, max(s3."projectName") as projectName from public."x" a1 JOIN public."xx" a2 ON a1."userId" = a2."userId" join ( SELECT l1."stayId", l1."checkIn" :: date, l1."checkOut" :: date, l1."userId", LEAD(l1."checkIn" :: date) OVER ( ORDER BY l1."checkIn" :: date ) AS next_check_in FROM public."xxx" l1 WHERE l1."userId" = '9cc6bf03-976c-46ce-8465-e7e1dc4f110d' ) as s1 on a1."userId" = s1."userId" JOIN public."xxxxxx" s2 ON s2.id = s1."stayId" JOIN public."xxxxx" s3 ON s3.id = s2."projectId" WHERE a1."userId" in( '-e7e1dc4f110d' ) AND s3.id in( '9c95f774b' ) AND ( next_check_in IS NULL OR next_check_in <> s1."checkOut" :: date ) group by a1."userId", s3.id -
Django Model Structure for products with Multiple Categories
I want to know if it is possible (and if so, what is the most pythonic way) to have a product that belongs to multiple product categories. e.g. an avocado belonging to [Food->Fresh Food->Fruit & Vegetables->Salad & Herbs] as well [Food->Pantry->Global Cuisine->Mexican]? I am currently using Django-MPTT to create the category tree for single-category products. How do I set up the Product and Category models, what would the data import look like, and what would an efficient query look like? I am open to any suggestion, even if it requires me to rewrite my project. I would appreciate ANY advice on anything to do with this problem. I am currently using Django-MPTT to create the category tree for single-category products. It makes sense conceptually, but I'm struggling with the multiple-category tree. I've found some examples of TreeManyToManyField class Category(MPTTModel, CreationModificationDateMixin): parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=200) def __str__(self): return self.title class Meta: ordering = ['tree_id', 'lft'] verbose_name_plural = 'categories' class Product(CreationModificationDateMixin): title = models.CharField(max_length=255) categories = TreeManyToManyField(Category) def __str__(self): return self.title class Meta: verbose_name_plural = 'movies' but there are no explanations or examples of import/creating data for such a model. I have also seen the following example … -
How do I get the label from the value models.IntegerChoices
please help out. I have the class that inherits from models.IntegerChoices, however, I know getting the value can be retried for instance if i want to retrieve the value for Daily, I can run RecurringType.DAILY, and I can get the value using RecurringType.DAILY.value and label by RecurringType.DAILY.label. But now, what if I have the value and want to get the label, how can I do that, I have tried so many things on here but nothing seems to work. Below is the code from django.db import models class RecurringType(models.IntegerChoices): DAILY = 1, ("Daily") WEEKLY = 2, ("Weekly") MONTHLY = 3, ("Monthly") -
PostgreSQL data not showing in Docker Container
I need some help, I'm stuck in Docker and can't find it out. I'm using Windows for a Django APP and Docker I'm using PgAdmin4 with PostgreSQL 16 and created a new server for docker The log for the Postgres Image: PostgreSQL Database directory appears to contain a database; Skipping initialization 2023-11-23 20:17:38.008 UTC [1] LOG: starting PostgreSQL 16.1 (Debian 16.1-1.pgdg120+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit 2023-11-23 20:17:38.008 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 2023-11-23 20:17:38.008 UTC [1] LOG: listening on IPv6 address "::", port 5432 2023-11-23 20:17:38.027 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" 2023-11-23 20:17:38.086 UTC [30] LOG: database system was shut down at 2023-11-23 20:17:11 UTC 2023-11-23 20:17:39.317 UTC [1] LOG: database system is ready to accept connections Logs from my web: No changes detected Operations to perform: Apply all migrations: admin, auth, base, contenttypes, sessions Running migrations: No migrations to apply. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). November 23, 2023 - 20:17:44 Django version 4.2.2, using settings 'cutler.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. My docker-compose file: version: '3.9' services: db: image: postgres … -
My django form is not sending the values correctly to my responses page
Im invested on solving the code, theres still some things missing, i took a print the visual part of the pages seem fine, but theres something wrong with how im sending the values and I cant find what, im very distracted though and just started to learn Django, id be glad if someone could help me. views.py imports def form_view(request): if request.method == 'POST': form = ParticipantResponseForm(request.POST) if form.is_valid(): response = form.save(commit=False) # Check if absences_count is not empty before saving absences_count_value = form.cleaned_data['absences_count'] response.absences_count = int(absences_count_value) if absences_count_value else 0 response.save() # Add a success message messages.success(request, 'Form submitted successfully!') # Print form data for debugging print(form.cleaned_data) # Redirect to responses page return redirect('show_responses') else: form = ParticipantResponseForm() return render(request, ' form.html', {'form': form}) def show_responses(request): responses = ParticipantResponse.objects.all() print(responses) return render(request, 'responses.html', {'responses': responses}) models.py from django.db import models from .choices import PARTICIPANT_DISABILITY_CHOICES class Disability(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class ParticipantResponse(models.Model): participant_name = models.CharField(max_length=255) birth_date = models.DateField() gender_choices = [ ('male', 'Masculino'), ('female', 'Feminino'), ] PARTICIPANT_DISABILITY_CHOICES = [ #choices ] gender = models.CharField(max_length=6, choices=gender_choices) participant_disability = models.CharField(max_length=255, choices=PARTICIPANT_DISABILITY_CHOICES, default='') clinical_diagnosis = models.TextField() functional_profile = models.TextField() participation_modalities = models.TextField() participation_observations = models.TextField() attendance_frequency = models.IntegerField() attended_dates … -
Django Heroku pipfile lock out of date
So I recently moved from pipenv to venv, now that I try to push my changes to Heroku, I'm getting: -----> Installing pip 23.3.1, setuptools 68.0.0 and wheel 0.41.3 -----> Installing dependencies with Pipenv 2023.7.23 Your Pipfile.lock (old_hash[-6:]) is out of date. Expected: ({new_hash[-6:]}). Usage: pipenv install [OPTIONS] [PACKAGES]... How can I migrate to venv and not use pipenv anymore in Heroku? should I delete my pipfilelock? -
I have problem with receieving POST type http requests
So... My issue is very simple. I send request from my roblox game using http request (POST method). Now... I've tested with php already, the request is sent successfully and is receieved. However, we talk about Django here. I really want to do that on Django, because I am more familliar with python + I want to do a lot of complicated things, and I highly believe Django is simply what I need With my problem, I suspect simple problem, such as not adding few lines, or simply wrong instalation of django or something else (even tho am very sure I did that correctly) Anyways, if that isn't clear, I send a POST request into the .py file which is placed on my website. The website does not run on my PC, but on my paid VPS which runs on linux ubuntu. After the request is sent, the script is supposed to get the request, and at least tell me it's receieved in my logs, which works perfectly fine. Script: `import logging from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import json import time logging.basicConfig(level=logging.DEBUG, filename="testfile", filemode="w", format="%(asctime)s - %(levelname)s - %(message)s") @csrf_exempt def home(request): if request.method == 'POST': post_data … -
Django downloads the result after successful validation and processing of the form
I have such a form for pdf files: class PDFFileUploadForm(forms.Form): file = forms.FileField(widget=forms.FileInput(attrs={'accept': 'application/pdf'})) And this is the view: class PdfTextExtractView(FormView): form_class = PDFFileUploadForm template_name = 'pdf_processing/pdf_processing.html' def form_valid(self, form): text = services.extract_text_from_pdf(form.cleaned_data['file']) In form_valid, I need to redirect the user to a page where he can download a txt file. I know that it is possible to save the file in the database and then redirect the user to the appropriate page with the file id passed for download. But I don't know if this is the best way to do it. Maybe there are some better options? Thank you! -
I'm having problems when sending User's Id's on a django model
I'm tryng to do a post method on projetos on my Vue Front-end but i keep getting the error message of "null value in column "professor_id" of relation "fabrica_projeto" violates not-null constraint" even though the request body is the same when i try to post on django-admin and it works there I'm kinda new to this whole coding world so sorry if my vocabulary is lacking On Vue/ my front-end enter image description here On Django-Admin(works) enter image description here enter image description here This is the model for Projeto enter image description here from django.db import models from usuario.models import Usuario from uploader.models import Image class Projeto(models.Model): nome = models.CharField(max_length=200) descricao = models.CharField(max_length=2500) data = models.DateTimeField(auto_now_add=True) professor = models.ForeignKey(Usuario, related_name='professor', on_delete=models.PROTECT) alunos = models.ManyToManyField(Usuario, related_name='alunos') capa = models.ForeignKey( Image, related_name="+", on_delete=models.CASCADE, null=True, blank=True, ) def __str__(self): return self.nome My Vue page is looking like this: (the professor part of the request is getting directly from the current user id): import api from '../plugins/api' import {useAuthStore} from '../stores/auth' class WorkspaceService { async getAllWorkspaces() { const response = await api.get('/projetos/') return response.data } async saveWorkspace(workspace) { const authStore = useAuthStore() workspace.professor = authStore.user_id let response if (workspace.id) { response = await … -
Set variable session out of a view in Django
I’m trying to set a variable session out of a view in Django. I’m aware of django’s documentation on Using sessions out of views. But in my case, I try to set a session variable in a custom management command. Here’s what I tried : from django.contrib.sessions.models import Session class Command(BaseCommand): help = "My custom command." def handle(self, *args, **options): for s in Session.objects.all(): s['my_variable'] = None What I get is this error: TypeError: 'Session' object does not support item assignment How can I set my_variable to None ? -
pyODBC Conversion failed when converting date and/or time from character string
Hello I want to convert date stored on a server from string to datetime here the view: class SubscribersListAPIView(ListAPIView): serializer_class = AbonesSerializer def get_queryset(self): start_date_param = self.request.query_params.get("start_date", None) end_date_param = self.request.query_params.get("end_date", None) start_date = None end_date = None if start_date_param: try: start_date = datetime.strptime(start_date_param, "%d/%m/%Y").date() except ValueError: pass if end_date_param: try: end_date = datetime.strptime(end_date_param, "%d/%m/%Y").date() except ValueError: pass queryset = Abones.objects.all() queryset = Abones.objects.annotate( date_as_datetime=ExpressionWrapper(F('date'), output_field=DateTimeField() ) ) if start_date_param and end_date_param: queryset = queryset.filter(date_as_datetime__range=(start_date, end_date)) elif start_date_param: queryset = queryset.filter(date_as_datetime=start_date) elif end_date_param: queryset = queryset.filter(date_as_datetime=end_date) return queryset i tried many solutions using ExpressionWrapper, Cast to force the conversion, Func but it didn't work. I want to filter date using the date_as_datetime but there is this error that come "Conversion failed when converting date and/or time from character string" Here are the traceback : Traceback (most recent call last): File "/home/darcy/var/www/envs/onasoft/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/darcy/var/www/envs/onasoft/lib/python3.10/site-packages/mssql/base.py", line 621, in execute return self.cursor.execute(sql, params) pyodbc.DataError: ('22007', '[22007] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Conversion failed when converting date and/or time from character string. (241) (SQLExecDirectW)') -
Split Django ModelForm selection base on previous field
So Im making a booking form, I have my Booking Model : class Bookings(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, null=True, verbose_name="کاربر",) booker_name = models.CharField(max_length=100, null=True, verbose_name="نام",) booked_time = models.ForeignKey(AvailableHours, on_delete=models.CASCADE,related_name='booked_time', verbose_name="سانس",) booking_code = models.IntegerField(unique=True,default=random_string, verbose_name="کدپیگیری",) confirmed = models.CharField(max_length=100,choices=BOOKING_STATUS,default='در انتظار',null=True, verbose_name="وضعیت",) class Meta: verbose_name_plural = "رزرو ها" verbose_name = "رزرو" def __str__(self): return f'{str(self.booker_name)} - {self.booked_time} ** {self.confirmed}' and my booked_time is based on : class AvailableHours(models.Model): free_date = models.ForeignKey(AvailableDates,verbose_name="تاریخ فعال", null=True, blank=True,on_delete=models.CASCADE,related_name='freedate') free_hours_from = models.IntegerField(null=True, blank=True, verbose_name="از ساعت",) free_hours_to = models.IntegerField(null=True, blank=True, verbose_name="الی ساعت",) status = models.BooleanField(null=True,default=True, verbose_name="آزاد است؟",) class Meta: verbose_name_plural = "سانس ها" verbose_name = "سانس" def __str__(self): return f'{str(self.free_date)} - {self.free_hours_from} الی {self.free_hours_to}' class AvailableDates(models.Model): free_date = jmodels.jDateField(null=True, verbose_name="تاریخ فعال",) status = models.BooleanField(choices=AVAILABLE_DATE_CHOICES,null=True,default=True, verbose_name="وضعیت",) class Meta: verbose_name_plural = "روزهای فعال" verbose_name = "روز فعال" def __str__(self): return f'{str(self.free_date)}' I cannot workout how to split my Dates and Hours fields in ModelForm. class BookingForm2(forms.ModelForm): class Meta: model = Bookings exclude = ('user','booking_code','confirmed',) def __init__(self,*args, **kwargs): super(BookingForm, self).__init__(*args, **kwargs) self.fields['booked_time'].queryset = AvailableHours.objects.filter(status=True) so in frontend user picks from a dropdown menu the AvailableDates then picks AvailableHours made in that model. Anyone can suggest a workaround ? -
djnago application cant see data from html
I have django application named emnosy (emergency notification system) when i try to use add_contact function from html i can see only that error IntegrityError at /addcontact/ ERROR: A null value in the "message" column violates the NOT NULL constraint DETAIL: The error line contains (2, booby, null, booby@gmail.com). Request Method: POST Request URL: http://127.0.0.1:8000/addcontact/ Django Version: 3.2.23 Exception Type: IntegrityError Exception Value: ERROR: A null value in the "message" column violates the NOT NULL constraint DETAIL: The error line contains (2, booby, null, booby@gmail.com). Exception Location: D:\projects\EmNoSy\venv\lib\site-packages\django\db\backends\utils.py, line 84, in _execute Python Executable: D:\projects\EmNoSy\venv\Scripts\python.exe Python Version: 3.7.9 Python Path: ['D:\\projects\\EmNoSy\\venv\\emnosys_wqrfl', 'C:\\Program' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0\\python37.zip', 'C:\\Program' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0\\lib', 'C:\\Program' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_3.7.2544.0_x64__qbz5n2kfra8p0', 'D:\\projects\\EmNoSy\\venv', 'D:\\projects\\EmNoSy\\venv\\lib\\site-packages'] Server time: Thu, 23 Nov 2023 15:50:47 +0000 i dont know how to fix that issue this is my addcontacts.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="../../static/emnosys/css/addcontacts.css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div class="about"> <div class="label"> Add contact </div> <form action="" method="post"> {% csrf_token %} <div class="username"> <input name="about--username" id="about--username" placeholder=" " maxlength="40"></input> <label for="#about--username" id="username--label">Username for recipient (locally)</label> </div> <div class="textarea"> <textarea name="about--textarea" id="about--textarea" cols="30" rows="10" placeholder=" " maxlength="999"></textarea> <label for="#about--textarea" id="textarea--label">Message</label> </div> <div class="telegram" id="telegram--label"> <input name="about--email" id="about--email" placeholder=" … -
How Can I implement Dynamic Real Time Counter in Django
I have the following Django Models where I want to display real timer count down of the subscription (count down to the expiring Date) of every business account. I also have ajax code stored in my static/js folder where i referenced it on the base.html template. while in the index.html template I added a p tag with the countdown id but nothing is working. Someone should demonstrate the best way of achieving this in Django real time. Models: class BusinessAccount(models.Model): STATE_CHOICES = [ ('Benue', 'Benue'), ] LGA_CHOICES = [ ('Gboko', 'Gboko'), ] ACCOUNT_CHOICES = [ ('RICE MILL', 'RICE MILL'), ] name = models.CharField(max_length=100) account_type = models.CharField(max_length=100, choices=ACCOUNT_CHOICES, null=True) address = models.CharField(max_length=200, null=True) state = models.CharField(max_length=50, choices=STATE_CHOICES, null=True) lga = models.CharField(max_length=50, choices=LGA_CHOICES, null=True) subscription_plan = models.ForeignKey(Subscription, on_delete=models.CASCADE, null=True) is_active = models.BooleanField(default=False) created_date = models.DateField(auto_now_add=True) def subscription_countdown(self): if self.subscription_plan: expiration_date = self.subscription_plan.expiration_date remaining_time = expiration_date - timezone.now() return max(remaining_time, timedelta(0)) else: return timedelta(0) def __str__(self): return self.name class SubscriptionHistory(models.Model): business_account = models.ForeignKey(BusinessAccount, on_delete=models.CASCADE) plan = models.ForeignKey(SubscriptionPlan, on_delete=models.CASCADE) pin = models.UUIDField(default=uuid.uuid4, unique=True) start_date = models.DateField() expiration_date = models.DateField() def __str__(self): return f'Subscription for {self.business_account.name} \ ({self.plan.name})' My Ajax code in static/js folder: <script> // Fetch the updated countdown value from the server function … -
is there a relation cloud database and if there is can i use it as a backend database for my django projects?
is there a free relation cloud database and if there is can i use it as a backend database for my django projects and can you recommended one for free usage ..................................................................................................................................................................................................................................................................................................................................................................................................................... ?