Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django is saving UUID without dashes in MySQL
I'm creating a Django application that uses UUID in some models. While i was using a MySQL database locally django was creating the UUID and saving it without dashes. Everything was working. Now i'm using a DB hosted in Hostinger. The problem is that the authentication is no longer working. The response i get if i try to access the API endpoints: "{"detail":"Usuário não encontrado","code":"user_not_found"}". Furthermore, in the remote DB django is saving the UUID with dashes. enter image description here I tried to create some users using the remote DB, the UUID are saved with dashes, and the django seems not to know how to deal with it: File "C:\Python311\Lib\uuid.py", line 178, in init raise ValueError('badly formed hexadecimal UUID string') ValueError: badly formed hexadecimal UUID string -
issue with post_detail view in django
hi there i am doing a project for my fullstack course but have come across an issue I am trying to make a detailed post view put once I added it to my URLs.py I get this error Reverse for 'post_detail' with arguments '('DEAD-BY-DAYLIGHT’S-MYTHIC-TOME-EXPLORES-YUI-KIMURA-AND-THE-SPIRIT',)' not found. 1 pattern(s) tried: ['(?P[-a-zA-Z0-9_]+)/\Z'] and it is saying this line is giving me that error <a href="{% url 'post_detail' post.slug %}" class="post-link black-text"> but when I delete this from my urls.py path('<slug:slug>/', views.post_detail, name='post_detail'), my page loads again how do I fix it i do not even know how to explain what ive tried but i have tried everything i cant think of ive even tried deleting the post that is in the error but it just gives me another post in it -
Banner is not displaying at the top and css is not working
I have html like following, in my Django project <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Index Page</title> <link rel="icon" type="image/png" sizes="16x16" href="{% static 'favicon.png' %}"> <link rel="stylesheet" href="{% static 'style.css' %}"> </head> <body> <div id="error-banner" class="error-banner" style="display: none;"></div> <header> <div class="header-content"> <!--some header contents--> </div> </header> <div> <!--some other divs--> </div> <script> function showErrorBanner(message) { var banner = document.getElementById('error-banner'); banner.textContent = message; banner.style.display = 'block'; setTimeout(function() { banner.style.display = 'none'; }, 10000); // 10 seconds } {% if error_message %} showErrorBanner("{{ error_message }}"); {% endif %} </script> </body> </html> My signin_view is like following: def signin_view(request): if request.method == 'POST': form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('login') # Change 'home' to the name of your homepage URL pattern else: error_message = "Invalid username or password." else: error_message = "Invalid form submission." else: form = AuthenticationForm() error_message = None return render(request, 'login.html', {'login_form': form, 'error_message': error_message}) and entire style.css is like following body { font-family: Arial, sans-serif; margin: 0; padding: 0; background-image: url('resources/background.jpg'); background-size: cover; background-position: center; background-repeat: no-repeat; background-attachment: fixed; display: flex; … -
My project is not recognizing my static files and I am using Django
I have been trying to run my project on the local host But my project is not displaying the template in the normal wayenter image description herethis the error it giving me.pls is there anybody who can help in solving the problem because I have tried every possible things I know -
Filtered reverse of a one to many relation in Django
I have a model called Item and another called ItemSynonym with a one to many relation like so: from django.db import models from django.conf import settings from project.utils.models import UUIDModel class Item(UUIDModel): name = models.CharField(max_length=200) class ItemSynonym(UUIDModel): marker = models.ForeignKey( Marker, on_delete=models.CASCADE, related_name="synonyms", ) name = models.CharField(max_length=200) I would now like to add a new field to the ItemSynonym model called language code so that it becomes: class ItemSynonym(UUIDModel): marker = models.ForeignKey( Marker, on_delete=models.CASCADE, related_name="synonyms", ) language_code = models.CharField( db_index=True, max_length=8, verbose_name="Language", choices=settings.LANGUAGES, default=settings.LANGUAGE_CODE, ) name = models.CharField(max_length=200) However I would like to filter I am wondering if it is possible somehow to filter the synonyms by only modifying the models, so that I don't have to hunt through the entire code base and filter synonyms individually so something like: class Item(UUIDModel): name = models.CharField(max_length=200) synonyms = models.FilteredRelation( "all_synonyms", condition=models.Q(language_code=get_language()), ) class ItemSynonym(UUIDModel): marker = models.ForeignKey( Marker, on_delete=models.CASCADE, related_name="all_synonyms", ) language_code = models.CharField( db_index=True, max_length=8, verbose_name="Language", choices=settings.LANGUAGES, default=settings.LANGUAGE_CODE, ) name = models.CharField(max_length=200) Though obviously the above doesn't work, otherwise I wouldn't be here. I've also tried adding an annotation for the FilteredRelation inside a custom manager for Item`, but for whatever reason the annotation isn't even accessible as a property. … -
How to Create a Token Using Django REST Framework?
I am trying to implement token-based authentication in my Django project using Django REST Framework, but I am unsure of the steps required to create and manage tokens. I Installed Django REST Framework and djangorestframework-authtoken: Used the command pip install djangorestframework djangorestframework-authtoken. Configured settings.py: Added rest_framework and rest_framework.authtoken to INSTALLED_APPS. Added token authentication to DEFAULT_AUTHENTICATION_CLASSES. Created and registered token views: Attempted to use built-in views such as ObtainAuthToken for token creation. Attempted to configure URL routing: Added URL patterns for token endpoints. I expected to be able to generate a token when a user logs in and use that token for subsequent authenticated requests. I am unsure if I have set up the views and URL configurations correctly. Could someone provide a clear explanation or guide on how to properly set up token creation and authentication with Django REST Framework? If possible, please include a link to a YouTube video or tutorial that covers this topic. Thank you! -
Jinja tags: Not Loading
labels: [{% for task in task_distribution %}'{{ task.task }}',{% endfor %}], datasets: [{ label: 'Tasks', data: [{% for task in task_distribution %}{{ task.count }},{% endfor %}], backgroundColor: 'rgba(75, 192, 192, 0.2)', borderColor: 'rgba(75, 192, 192, 1)', borderWidth: 1 }] }, My jinja tags are not working inside the javascript while i was using to to plot the graph, What to do or How to overcome this ? Any other methods to overcome this? -
Entries not showing on page
Cant seem to figure out why my entries from my database are not appearing on my page but my topics name on the entry page is I'm trying to show show entries from my database on a page, the link to the page works and the Topic name from the database appearing but the entries from the database is not. views.py from django.shortcuts import render from .models import Topic # Create your views here. def index(request): """The home page for learning log.""" return render(request, 'learning_logs/index.html') def topics(request): """Show all topics""" topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) def topic(request, topic_id): """Show a single topic and all its entries""" topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) topic.html {% extends 'learning_logs/base.html' %} {% block content %} <p>Topic: {{ topic.text }}</p> <p>Entries:</p> <ul> {% for topic in topics %} <li> <p>{{ entry.date_added|date:'M d, Y H:i' }}</p> <p>{{ entry.text|linebreaks }}</p> </li> {% empty %} <li>There are no entries for this topic yet.</li> {% endfor %} </ul> {% endblock content %} models.py from django.db import models # Create your models here. class Topic(models.Model): """A topic the user is learning about.""" text = … -
Celery Beat sends to workers tasks that do not exist
I saw a lot of similar questions but nothing helped. Every now and then I am receiving the following error: 'app.tasks.do_some_work'. When I check inside the Django container, Celery Beat container, or Celery Worker container's app.tasks module, I don’t see any task with that name. I define the schedule for periodic tasks using celery_app.conf.beat_schedule, and everything appears to be correctly set up. I suspect that there might have been a task with this name in the past, but it was deleted or renamed. Maybe somehow it persists Here is the code inside the containers: from proj.celery import celery_app @celery_app.task def do_some_work(): DoSomeWorkUseCase.execute() return True Tried to use: Define CELERY_IMPORTS in settings -
Issue with Token Authorization in Django that uses djang_auth_adfs (Azure) as authentication backend
I am working on a django project which uses django_auth_adfs (Azure Active Directory) as its authentication backend. I have set up its API service using rest_framework. In the browsable views of the rest_framework, I am able to authorize using the session authentication which requires my settings.py to have such a thing: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'django_auth_adfs.rest_framework.AdfsAccessTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } With this, I am able to send post requests which requires the user to be authorized. But as soon as I change it to (deleting session authentication): REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'django_auth_adfs.rest_framework.AdfsAccessTokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } I get the http 401 unauthorized error which means it is not able to authorize using the token. This, further causes me not being able to send requests with postman. Does anyone know how I can use the API using adfs tokens? Here is an overall look of how my settings.py look: """ Django settings for core project. Generated by 'django-admin startproject' using Django 5.0.4. For more information on this file, see https://docs.djangoproject.com/en/5.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.0/ref/settings/ """ from pathlib import Path import os from dotenv import load_dotenv load_dotenv() # … -
when logging out, it shows white blank page - django 5
so when I want to log the user out it shows a white blank page at 'http://127.0.0.1:8000/accounts/logout/ I'm using the shortcut way to redirect to next page in settings.py and I tested to logout with admin panel and it works fine settings.py ... LOGIN_REDIRECT_URL = 'index' LOGOUT_REDIRECT_URL = 'index' ... this is my urls.py: from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('post.urls')), path('accounts/', include('django.contrib.auth.urls') ), ] this is how I login: login.html: {% extends "base.html" %} {% block content %} <div class="container"> <h1> LOGIN FORM </h1> <form method="post"> {% csrf_token %} {{form.as_p}} <button type="submit" class= "btn btn-success">Log In</button> </form> </div> <br> {% endblock content %} base.html: ... <ul> <li><a class="active " href="{% url 'index' %}">Home</a></li> <li><a class="active " href="{% url 'about' %}">About</a></li> {% if user.is_authenticated %} <li><a class="active " href="{% url 'logout' %}">Log Out</a></li> {% else %} <li><a class="active " href="{% url 'login' %}">Log In</a></li> {% endif %} </ul> ... and for log out all I did was the 'href="{% url 'logout' %}"' in base.html as far as I learned there is no code needed in views.py. .what am I missing? -
Filtering across multiple fields from a subquery where there is no related field
I'm trying to find a portable way to express the following record filtering query using the Django ORM. The intention is to: take a subquery of FilterSpec (eg. with a common FilterGroup) find all instances of Record where Record.text1 = FilterSpec.r_text1 AND Record.text2 = FilterSpec.r_text2 for at least one of the instances of FilterSpec in the subquery. include the matching FilterSpec.filter_name in the returned instances of Record. Record will have high cardinality, >100,000, after filtering typically <1000. The subquery of FilterSpec will have low cardinality, typically <10. Here is a gist of the models: class RecordGroup(Model): name = CharField(unique=True) # further data fields class Record(Model): text1 = CharField() text2 = CharField() group = ForeignKey(RecordGroup) # further data fields class FilterGroup(Model): name = CharField(unique=True) class FilterSpec(Model): r_text1 = CharField() r_text2 = CharField() filter_name = CharField() group = ForeignKey(FilterGroup) The challenge is that there is no formal relation between the record fields and the filter fields. There will be lots of repeated values in Record.text1 and Record.text2. I've found or developed examples where: there is one field being compared there are two fields being compared by concatenating the two fields into one (but I expect this will be slow at scale) there … -
ValueError:The field admin.LogEntry.user was declared with a lazy reference to 'recipes.customuser',but app'recipes'doesn't provide model 'customuser'
This is the Custom user model I also declared in settings AUTH_USER_MODEL="recipes.CustomUser" still I face this error ValueError:The field admin.LogEntry.user was declared with a lazy reference to 'recipes.customuser',but app'recipes'doesn't provide model 'customuser'` from django.db import models from django.http import HttpResponse from django.contrib.auth.models import AbstractUser, Permission from django.conf import settings from django.contrib.auth import get_user_model import secrets class CustomUser(AbstractUser): email=models.EmailField(unique=True) USERNAME_FIELD="email" REQUIRED_FIELDS=["username"] def __str__(self) -> str: return self.email -
What is the configuration for Apache Airflow, Django, PySpark together in Systemd services?
We are using Apache airflow, Django (python), and Spark (pySpark) in our project. Our DAGs are running fine when run 'airflow scheduler' is run from command line. However, these DAGs are not working when 'airflow scheduler' is run from systemd (systemctl). Note: We are using virtual environment to run airflow scheduler (and many python apps). Initially, we faced issues related to Virtual Environment. Later, Django Setup. We resolved the same. However, we are now facing the pyspark related issues. We have tried this for the scheduler. [Unit] Description=Airflow scheduler daemon After=network.target postgresql.service mysql.service redis.service rabbitmq-server.service Wants=postgresql.service mysql.service redis.service rabbitmq-server.service [Service] PIDFile=/home/datauser/Documents/airflow_workspace/airflow_env/bin/scheduler.pid Environment="PATH=/home/datauser/Documents/airflow_workspace/airflow_env/bin:/home/datauser/airflow_workspace/airflow_env/airnet/aqdms:/home/datauser/Downloads/spark-3.5.1-bin-hadoop3/bin:/home/datauser/Downloads/spark-3.5.1-bin-hadoop3/sbin" Environment="PYTHONPATH=/home/datauser/Documents/airflow_workspace/airflow_env" Environment="JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/jre" Environment="SPARK_HOME=/home/datauser/Downloads/spark-3.5.1-bin-hadoop3" Environment="PYSPARK_DRIVER_PYTHON=python3" Environment="PYTHONSTARTUP=/home/datauser/Downloads/spark-3.5.1-bin-hadoop3/python/pyspark/shell.py" Environment="PYSPARK_PYTHON=python3" Environment="SPARK_CONF_DIR=/home/datauser/Downloads/spark-3.5.1-bin-hadoop3/conf" Environment="PYSPARK_SUBMIT_ARGS=--master local[2] pyspark-shell" User=datauser Group=datauser Type=simple ExecStart=/usr/bin/bash -c 'source /home/datauser/Documents/airflow_workspace/airflow_env/bin/activate ; /home/datauser/Documents/airflow_workspace/airflow_env/bin/airflow scheduler --pid /home/datauser/Documents/airflow_workspace/airflow_env/bin/scheduler.pid' Restart=on-failure RestartSec=5s PrivateTmp=true [Install] WantedBy=multi-user.target What should be the configuration to use Apache airflow, Django, PySpark and virtual environment in Systemd? -
What is causing Unexpected Keyword 500 error when trying to pass data from URL as a variable using Django?
I am taking an online course and replicate the instructor's code on my Mac in VS Code to help me learn how it works; and this is not a homework problem. The instructor was showing how to dynamically create responses based on the URL by sending the last part of the url as a variable to a function that then generates the response. However , when I try it I get a 500 error. I have reviewed my code and it looks identical to the instructors, with only added comments. Fixed paths work fine, i.e. path("brian", views.brian, name = "brian"), works fine, but this fails: path("<str:name>", views.greet, name = "greet") the error is: [18/Jul/2024 20:50:39] "GET /hello/jim HTTP/1.1" 500 59430 [18/Jul/2024 20:50:41] "GET /hello/ HTTP/1.1" 200 5 Internal Server Error: /hello/jim Traceback (most recent call last): File "/Users/XXX/Documents/Work/Python Projects/Dashboard/.venv/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/XXX/Documents/Work/Python Projects/Dashboard/.venv/lib/python3.12/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: greet() got an unexpected keyword argument 'Name' I created several bits of code: (comments are mine so when I go back to the code later I can understand it) Created app called hello and added to installed apps in … -
Django prefetch_related not being helpful in diminishing queries
myList = [] qs = MyModel.objects.all().prefetch_related('m2m_model_set') for model in qs: k = model.m2m_model_set.all().values_list('field') myList.extend(k) This code represents what I am doing. Why is the line k = model.m2m_model_set.all().values_list('field') causing many queries? How can I fix this problem and do the same without making so many queries? -
How can I log variables based on database configuration?
Backend: Python 3.11 and Django 5.0.6 Database: PostgreSQL 15.6 We are shifting to deploying a Python executable file for the backend. Consequently, we will be unable to modify the code directly on the server. We do use a logger to save important information or errors from the server. However, sometimes we need to debug the code in production. How can we achieve this considering we can't modify the executable? Can we log/print variables at a specific line number configured in the database, without restarting the backend service? For example, if I want to log a variable report_name1 at line number 40 in the file portal/reports/report.py, how should this be set up? I am considering importing a class or function at the top of the file once, with all configurations being handled from the database. Here's the proposed structure for a LogVariables table: path_name = 'portal/reports/report.py' line_number = 40 variable_name = 'report_name1' is_active = True is_deleted = False -
Optimized way to handle user graded items?
I'm working on website that allows users to grade items, e.g. books. The grade should be displayed on the book page, but also on the collective page containing all books. The grades should be possible to modify: class BookUserGrade: user = foreign_key_to_user book = foreign_key_to_book grade = ... However the operation of requesting the grades each time a user access the booklist (or to lesser degree single book page) seems expensive. I'm pondering about making an additional two fields on the book itself, number_of_grades and cumulative_grade which are going to be updated only on user grading a book. Maybe also calculated_grade (is it worthy to add this field instead of calculating cumulative_grade / number_of_grades on the fly? Or perhaps there's another proper way to do so? -
A local variable seemingly breaking scope in Django
I have introduced this function in a file storage.py that is imported from models.py: def uuid_file_name(kind): def file_name(instance, filename): h = str(uuid.uuid4()) basename, ext = os.path.splitext(filename) return os.path.join(f'{kind}_files', h[0:1], h[1:2], h + ext.lower()) return file_name The intention of the function is to dynamically generate file names in a field declaration, such as: class Thingy(models.Model): widget = FileField(upload_to=uuid_file_name("widget")) Now when I makemigrations, I get an odd error: ValueError: Could not find function file_name in <app>.storage. There is no other mention of file_name in my project, and if I change the identifier, the error message changes accordingly, so the error is definitely from this. However, without some metaprogramming, I can't see how file_name can leak from within this function. I thought I could avoid whatever magic was happening by from .storage import uuid_file_name as _uuid_file_name, hoping Django wouldn't act on a private module member, but the same error occurs. So, a two-fold question: Why is this happening, and how do I prevent it? Is there another way to write the equivalent code to circumvent the error? Full traceback: Traceback (most recent call last): File "<project>/./manage.py", line 22, in <module> main() File "<project>/./manage.py", line 18, in main execute_from_command_line(sys.argv) File "<project>/<venv>/lib/python3.12/site-packages/django/core/management/__init__.py", line 442, in … -
How to restrict available InlinePanel instances that can be choosen in wagtail admin
Let's say we Course and Lesson Wagtail Page models, where Lesson page instances are sub-pages of Course page instance. E.g. "Web Development Course > HTML Lesson". Implemented as: class Course(Page): description = models.TextField(null=True, blank=True) content_panels = Page.content_panels + [ FieldPanel('description'), ] class Lesson(Page): description = models.TextField(null=True, blank=True) content_panels = Page.content_panels + [ FieldPanel('description'), ] parent_page_types = ['app.Course'] Now we add an orderable many2many relationship to Course using InlinePanel(), so we can set each course's lessons and order them in Wagtail Admin. implementation: class Course(Page): description = models.TextField(null=True, blank=True) content_panels = Page.content_panels + [ FieldPanel('description'), InlinePanel('course_lessons', label='Lessons'), ] class CourseLessons(Orderable): page = ParentalKey('Course', on_delete=models.CASCADE, related_name='course_lessons') lesson = models.ForeignKey('Lesson', on_delete=models.CASCADE) panels = [ FieldPanel('lesson'), ] class Lesson(Page): description = models.TextField(null=True, blank=True) content_panels = Page.content_panels + [ FieldPanel('description'), ] parent_page_types = ['course.Course'] Question: How can we limit the inline page choices to specific parent page's sub-pages? E.g. When selecting lessons for a course, only that course's lessons(sub-pages) are available. I thing this can be achieved either by limiting Page -
How to run on_success in Celery ONLY on the last worker process in a group?
I have been scratching my head about this for days now. I have a a background running task, which takes around 1 hour. I am processing 5000 images. I create a group of celery tasks and each task processes 1000 images each. I have an on_success method where I create a 'Finished' database record, and remove the 'inProgress' record. The problem however is, that even while having tons of checks in the on_success method, it still somehow generates 2 'Finished' database records. It sounds confusing, see the code below: def on_success(self, retval, task_id, *args, **kwargs): self.image_job.refresh_from_db() total_nr_of_images = self.image_job.total_nr_of_images stored_results = ImageJobResults.objects.filter(job=self.image_job).count() if stored_results == total_nr_of_images: #It means all the workers have completed processing images # for this job, and we need to create a csv file, and a Finished BC Job with transaction.atomic(using='my_db'): image_job = ImageJob.objects.select_for_update().get(id=self.image_job.id) if not ImageJobFinished.objects.filter(job=image_job).exists(): job_in_progress = ImageJobInProgress.objects.get(job=image_job) started_at = job_in_progress.started_at image_job.generate_results(started_at=started_at,completed_at=now(),csv_rds_handle_job_id=self.image_job.pk) #Now that a ImageJobFinished is created. # We delete the ImageJobInProgress instance job_in_progress.delete() return super().on_success(retval, task_id, *args, **kwargs) Now theoretically, the stored_results should be equal to total_nr_of_images only in the last worker. But both the workers somehow finish on the same time, and they get the same values here. Both of them then … -
How to register voice for TTS in windows 11?
I have some troubles to use 2 additional voices, in my case i try to use Pablo (Spanish - Spain) and George (English - GB). I develop a app in python/Django, from the front i sent a JSON with the language (in this case with what voice i want to read the text), and the text, the back received and process it calling the proper voice reading the text. here is part of the code: import win32com.client, pythoncom from .translator import translate_text def check_voices(): pythoncom.CoInitialize() try: speaker = win32com.client.Dispatch('SAPI.SpVoice') voices = speaker.GetVoices() for voice in voices: print(f"Voice: {voice.GetDescription()}, Id: {voice.Id}") finally: # Finalizar COM pythoncom.CoUninitialize() def sound_rate(speaker): speaker.Rate = -1 # rango -10(lento) - 10(rapido) def sound_volume(speaker): speaker.Volume = 100 # rango 0(bajo) - 100(alto) def text_to_speech(language, text): pythoncom.CoInitialize() try: speaker = win32com.client.Dispatch('SAPI.SpVoice') voices = speaker.GetVoices() check_voices() if language.startswith('en-'): text = translate_text(text, from_code='es', to_code='en') language_map = { 'es-ES-female': 'Microsoft Helena Desktop - Spanish (Spain)', 'es-ES-male': 'Microsoft Pablo Desktop - Spanish (Spain)', 'en-UK-female': 'Microsoft Hazel Desktop - English (Great Britain)', 'en-UK-male': 'Microsoft George Desktop - English (Great Britain)', } voice_name = language_map.get(language) for voice in voices: if voice.GetDescription() == voice_name: speaker.Voice = voice break speaker.Speak(text) except Exception as e: print(f"An error … -
Optimizing Django Application Performance
I'm currently dealing with performance issues in a Django application that's structured as follows: User - Social Network - Post - Tag/Label Each entity is represented by its own table. The number of tags is growing exponentially, even after filtering out less significant ones (tags are assigned by an AI, not humans). Here's what I'm considering to optimize performance: Separate Tables for Insignificant Tags: Move less significant tags to a different table or even a different database. For instance, having 100k rows in MediaTags table and 10M rows in SmallMediaTags. Would this improve the performance of the main tables? Denormalization: Currently, each post is linked to 2-5 primary tags, meaning the number of tags equals 2-5 times the number of posts, with occasional outliers having 6+ tags. This puts a massive load on MediaTags, complicates searches, and incurs additional costs for converting MediaTags into objects. However, if we store top-N tags directly with the posts (e.g., top-10 tags), it could result in nearly a 1:1 ratio. This way, all required tags would be part of the posts themselves, eliminating the need for additional table queries. We have recently started displaying lists of posts with specific tags, which has become a … -
How do I pass request to a form in test
I am trying to pass request to a Django form in unittest. This is my test: def test_AddPairedStudyForm(self): self.client.force_login(self.user) request = RequestFactory().get(reverse("researcher_ui:console")) request.user = self.user study_group = 'StudyGroup' payload = { "study_group": study_group, "paired_studies": [self.study.id, self.study1.id], 'request': request } form = AddPairedStudyForm(data=payload) self.assertTrue(form.is_valid()) This generates a key error in the form: KeyError: 'request' Within the form itself, this error occurs during the __init__ function def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super(AddPairedStudyForm, self).__init__(*args, **kwargs) Within the CBV I add the request using the get_form_kwargs function: def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs["request"] = self.request return kwargs How can I pass the request to the form in unittest? -
How to retrieve the mobile number linked to an any user Aadhaar card in python django
How to retrieve the mobile number linked to an any users Aadhaar card. I want to validate user aadhaar card so I'll send OTP on aadhaar mobile number to validate, that's my approach. So Any builtin API or any Doc suggestion anyone can refer.