Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does Django admin page and the rest of my pages' CSS files and images are not found?
the GET method returns 404 in the console even though its searching in the correct file path. EDIT: i found another post that said i should turn on the DEBUG in the settings.py file. AND IT WORKED!! now after trying to turn it back to False, it still worked as expected. so the second question is why did it not work on the first try? i made sure the static paths in the settings.py file are correct but it seems the issue is with django itself since the django admin page doesn't show CSS either. i tried python manage.py collectstatic and it didn't work i tried restarting the server multiple times and still -
Error: Redirect URI Mismatch when Integrating Microsoft Authentication with Django
I am trying to integrate Microsoft authentication with my Django app deployed on Azure Web App using the django_auth_adfs package. However, I encountered an error regarding a mismatch in the redirect URI. I have followed the documentation provided by django_auth_adfs for configuring Azure Active Directory integration. In my Azure portal, I registered the application and added http://localhost:8000/oauth2/callback to the Web Redirect URLs as instructed. Web Redirect URLs When attempting to authenticate, I receive the following error message: The redirect URI 'http://127.0.0.1:8000/oauth2/callback' specified in the request does not match the redirect URIs configured for the application. Make sure the redirect URI sent in the request matches one added to your application in the Azure portal. Here is my settings.py configuration related to django_auth_adfs: INSTALLED_APPS = [ ... 'django_auth_adfs', ] MIDDLEWARE = [ ... 'django_auth_adfs.middleware.LoginRequiredMiddleware', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'django_auth_adfs.backend.AdfsAccessTokenBackend', ] LOGIN_REDIRECT_URL = '/' LOGIN_URL = 'django_auth_adfs:login' LOGOUT_REDIRECT_URL = '/' # django-auth-adfs settings AUTH_ADFS = { 'AUDIENCE': config('MICROSOFT_AUTH_CLIENT_ID'), 'CLIENT_ID': config('MICROSOFT_AUTH_CLIENT_ID'), 'CLIENT_SECRET': config('MICROSOFT_AUTH_CLIENT_SECRET'), 'CLAIM_MAPPING': {'first_name': 'given_name', 'last_name': 'family_name', 'email': 'upn'}, 'GROUPS_CLAIM': 'roles', # or None 'MIRROR_GROUPS': True, 'USERNAME_CLAIM': 'upn', 'TENANT_ID': config('MICROSOFT_AUTH_TENANT_ID'), 'RELYING_PARTY_ID': config('MICROSOFT_AUTH_CLIENT_ID'), } ADFS_REDIRECT_URI = 'http://localhost:8000/oauth2/callback' What could be causing this redirect URI mismatch error despite configuring the correct redirect URI … -
Django: how to make a standard input form to conditionally insert OR update many-to-many records?
I am trying to figure out a way to update or insert new many-to-many records of a Product into an Order through an intermediary model ProductOrder. I want to have a standard form with all Products and their respective quantities poQty. A standard form (assuming to have 4 Products in total) is used to update existing Order records. If an order has 2 Products associated to it, the form should: include additional products if poQty>0 change existing products if poQty has changed do nothing if non-existing Products remain with standard poQty=0 I am currently getting the following error message when I try to submit the form: {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}] I would appreciate some help on that... THANKS ! Further details: models.py class ProductClass(models.Model): classDescription = models.CharField(max_length=255, verbose_name='Type', unique=True, null=True) classPrint = models.BooleanField(default=True, verbose_name='Print?') class Meta: verbose_name_plural = 'Product Classes' def __str__(self): return self.classDescription class Product(models.Model): prodclassQuery = models.ForeignKey(ProductClass, on_delete=models.PROTECT, verbose_name='Product Class', default=1) prodDescription = models.CharField(max_length=255, verbose_name='Product') prodPrice = models.DecimalField(max_digits=6, decimal_places=2, verbose_name='Price') … -
Why is permission error returned when sending creating FileResponse in Django?
In temp folder there is a temporary file called video.mp4 which is meant to be created, then sent to user as attachment and then deleted. The following code returns PermissionError: [WinError 32] for this line: os.remove(file_path). Why ? Am i deleting file too early ? def download_video(request): if request.method == 'POST': link_input_data = request.POST.get('link_input_field') # todo change to use django forms later download_cda.start_download(link_input_data) file_path = "temp\\" + "video.mp4" response = None try: file = open(file_path, "rb") response = FileResponse(file, as_attachment=True, filename="video.mp4") except Exception as e: print(e) # todo add exception code finally: os.remove(file_path) return response else: form = UrlForm() return render(request, 'index.html', {"url_form": form}) I couldn't find anything for this in docs: [FileResponse] (https://docs.djangoproject.com/en/5.0/ref/request-response/#django.http.FileResponse) -
not all arguments converted during string formatting when trying to execute mssql stored procedure from django
My procedure consists of inserting the data into a table in the database from REST API. p1,p2,p3 are the parameters coming from the user interface P1,P2,P3 are my stored procedure's parameters. Here is my code def test(request): if request.method == "POST": with connection.cursor() as cursor: P1 = request.data["p1"] P2 = request.data["p2"] P3 = request.data["p3"] params = (P1,P2,P3) print(params) try: cursor.execute("{CALL [dbo].[myStoredProcedure]}",params) if cursor.return_value == 1: result_set = cursor.fetchall() print(result_set) finally: cursor.close() return Response({"msg":"post"}) else: return Response({"msg": "get"}) when I add parameters like this: cursor.execute("{CALL [dbo].[myStoredProcedure] (P1,P2,P3)}")"P1","P2","P3" are inserted in the database but not the value of these parameters. How to solve this problem ? -
Accessing Images in media/ folder In Django, as public url
I can access the image on the local machine as http://127.0.0.1:8000/media/taj.jpg in the browser. How can I access the same image publicly in the browser? Like url: http://49.128.160.80:8000/media/taj.jpg -
How can I optimize raw queries to a MySQL in django
I'm new to Django, this is my code, what happens is that when that view is executed, it takes too long to load, approximately 15 seconds and that's a lot, how could I optimize this so that it doesn't take too long? from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.db import connections import datetime @login_required def show_data_tbl_form_gen(request): with connections['mysql_db'].cursor() as cursor: cursor.execute("SELECT * FROM tbl_form_gen ORDER BY time DESC") datos = cursor.fetchall() datos = [list(dato) for dato in datos] for dato in datos: id_granja = dato[4] with connections['mysql_db'].cursor() as cursor: cursor.execute("SELECT NombreFinca FROM tbl_granjas WHERE CodigoFinca = %s", [id_granja]) nameFarm = cursor.fetchone() if nameFarm: dato.append(nameFarm[0]) else: dato.append("Granja Desconocida") id_colab=dato[2] with connections['mysql_avicon_bluehost'].cursor() as cursor: cursor.execute("SELECT Nombres, Apellidos FROM tblEmpleados WHERE Rol = %s", [id_colab]) nameColab = cursor.fetchone() if nameColab: # union names and lastnames full_name = f"{nameColab[0]} {nameColab[1]}" dato.append(full_name) else: dato.append("Colaborador Desconocido/a") #print list print("Array de datos con nombres de granja:", datos) return render(request, 'app_web_pofapp/select.html', {'datos': datos}) def detalles(request, id): with connections['mysql_db'].cursor() as cursor: cursor.execute("SELECT * FROM tbl_form_gen WHERE id_forms_generators = %s", [id]) formulario = cursor.fetchall() # convert formulario = [list(dato) for dato in formulario] # get names for dato in formulario: id_granja = dato[4] with connections['mysql_db'].cursor() as cursor: … -
Django sync_to_async blocking event_loop on ORM queries?
So I am using asyncio and Django and to use Django's ORM you need to either use asnyc methods or wrap the ORM calls in sync_to_async. I am having some questions however understanding if while I am waiting for the response from the database the event loop is freed to do other operations ex: def sync_function(user_id, name): user = User.objects.get(id=user_id) last_name_user = User.objects.filter(name=name).last() return user, last_name_user If I do async def async_function(user_id, name): user, last_name_user = await sync_to_async(sync_function)(user_id, name) will my event loop be free to do other CPU bound operations while those querys are done? I am also aware there are aget and alast methods but it seems all they do is wrap the actual method with sync_to_async so I'd also like to know if there would be a difference between the example I provided earlier and async def async_function(user_id, name): user = await User.objects.aget(id=user_id) last_name_user = await User.objects.filter(name=name).alast() I read a bit about thread_sensitive parameter in sync_to_async is my understanding that by default being True it means that function wrapped will be ran in the same thread and thus the event loop wont be able to run other tasks, and if it is False it could be parallelized? -
Download image to client's PC django
''' class Archivo(models.Model): Archivo = models.ImageField(upload_to="Seccion1") def descarga1(archivo_nombre): if archivo_nombre.endswith(".jpg"): return True return response ''' ''' class Jpgtopng(View): def get(self,request): return render(request,"Pngtojpg.html",{"form":Formext}) def post(self,request): Formulario = Formext(request.POST,request.FILES)#?Recibimos datos del formulario if Formulario.is_valid(): imagen = Formulario.cleaned_data["Archivo"] imagen_nombre = imagen.name if Formulario.Extension(imagen_nombre): Formulario.save() self.Descargar(imagen) else: return HttpResponse("Extension incorrecta") else: #? En caso de no ser valido reenviamos el formulario return render(request,"Pngtojpg.html",{"Formu":Formulario}) return HttpResponse("Hubo un error") def Descargar(archivo): Nombre = archivo.name return Fileresponse(open(Nombre,"rb"),as_attachment=True, filename=Nombre) ''' ''' from django.urls import path from .views import Jpgtopng,Pngtojpg urlpatterns =[ path("Cambiopngajpg/",Jpgtopng.as_view(),name="JpgtoPng"), path("Cambiojpgtopng/",Pngtojpg.as_view(),name="Pngtojpg"), ] ''' For some reason the download never starts but the verification of the form and the extension do work -
Pre-Signed URL with boto3 and django-storages incorrect filepath
For a file upload feature, I'm trying to set a FileField in Django using a presigned url but when the field is saved it seems that the aws bucket name is being added into the url so when I try to access the file from the django admin I get a Key does not exist error. For the upload I first generate a presigned url on the backend: try: s3_client = boto3.client( "s3", region_name=settings.AWS_S3_REGION_NAME, config=Config(signature_version="s3v4"), aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, ) s3_response = s3_client.generate_presigned_url( "put_object", HttpMethod="PUT", ExpiresIn=settings.AWS_SIGNED_URL_DURATION, Params={ "Bucket": settings.AWS_STORAGE_BUCKET_NAME, "Key": f"{user.uuid}/{instance.uuid}/{payload.dict().get('filename')}", "ContentType": "application/octet-stream", }, ) except ClientError as e: logger.exception(e) return 500, {"message": "Something went wrong."} This is then used by the frontend client to upload the file - this all works ok and uploads a file to the following url: https://<BUCKET_NAME>.s3.<BUCKET_REGION>.amazonaws.com/<USER_UUID>/<INSTANCE_UUID>/<FILE_NAME> (I have checked in s3 and the file is there.) The frontend then sends a patch request to update the DB with the url once the upload has been successful. The data looks like this: {"file_field": "<USER_UUID>/<INSTANCE_UUID>/<FILE_NAME>"} However, when I try to access the file from the django admin (or when I retrieve the instance data from my REST API), the file field shows a different url: https://<BUCKET_NAME>.s3.<BUCKET_REGION>.amazonaws.com/<BUCKET_NAME>/<USER_UUID>/<INSTANCE_UUID>/<FILE_NAME> (Notice the … -
How to start and complete an atomic transaction in MySQL by using Django 5.0.3?
I want to save a CSV (with 50k rows) as a MySQL table in Django. I wrote the model and I started the atomic transaction from the post request (runned by ajax async submit from the template). The problem is that the transaction is interrupted by the StateReloader and it does not continues. Is it possible to run the transaction in background and let it to complete? Here a small version of my code: # file: models.py from django.db import models, transaction class MyManager(models.Manager): @transaction.atomic def create_models(self, file, callback=None): if callback is not None: transaction.on_commit(callback) with open(file, "r") as fp: lines = map(str.strip, fp.readlines()) lines = map(lambda x: x.split(";"), lines) lines = list(lines) headers = lines[0] print("Writing table with {} lines...".format(len(lines) - 1)) # 50k lines for i, line in enumerate(lines[1:]): for j in range(len(headers)): print("Saving line #{}".format(i), end="\r"). # ends at line 800 before the StateReloader self.create(row=i + 1, header=headers[j], value=line[j]) print() return True class MyModel(models.Model): row = models.IntegerField(null=False, blank=False) header = models.CharField(max_length=255, null=False, blank=False) value = models.CharField(max_length=255, null=False, blank=False) objects = MyManager() def __str__(self) -> str: return f"{self.header} = {self.value} on row {self.row}" # file: views.py from django.http import JsonResponse from django.views import generic from django.contrib.auth.mixins import LoginRequiredMixin … -
How to return a json containing a model object, as well as all the models related to it in Django
I have been working on a project in django, and I am stuck trying to extract some concepts, and parse their rules or complex rules depending on the concept's instance_type, and the rule clauses for each rule, and then put them in a json like format. This is the model structure to give you a quick view of the database and this is how its implementation in short: class RuleClause(models.Model): name = models.CharField(max_length=100, null=False, default="") type = models.CharField(max_length=200,choices=clauses_types_choices, default="StatsRuleClause") class Rule(models.Model): name = models.TextField(default=DEFAULT_NAME) # , unique=True) description = models.TextField(null=True, blank=True) clauses = models.ManyToManyField(RuleClause, through="RuleClauseRule") class ComplexRule(models.Model): name = models.TextField(default=DEFAULT_NAME, unique=True) description = models.TextField(null=True, blank=True) rules = models.ManyToManyField(Rule, through="RuleComplexRule") class Concept(models.Model): name = models.CharField(max_length=200, default=DEFAULT_NAME, unique=True) instance_id = models.IntegerField(default=0) instance_type = models.CharField(max_length=200, choices=concept_type_choices) And this is the desired output: {"concepts": [ { "name": "Concept_1", "instance_type": "rule" "instance_id": { "name": "rule_1", "description": "", "clauses": [ { "name": "Clause_1", "type": "" }, { "name": "Clause_2", "type": "" }] } }, { "name": "Concept_2", "instance_type": "complex_rule" "instance_id": { "name": "complex_rule_1", "description": "", "rules": [ { "name": "Rule_2", "description": "", "clauses": [ { "name": "clause_1", "type": "" }, { "name": "clause_4", "type": "" }] }] } } ]} Important: Keep in mind I am … -
My user has permissions but does not have access to pages in django app
My user has for example the following permissions: add_client, view_client, delete_client, change_client of the Client model print(user.request.user_permissions.all()) gives <Permission: elec_meter | client | Can add client>, <Permission: elec_meter | client | Can customer change>... When I add the @permissions_required decorator as follows: @permission_required("client.add_client",login_url="/login") def add_client(request): ... @permission_required("client.view_client",login_url="/login") def view_client(request): ... The user cannot open the pages and is redirected to the login page (/login) How to solve this problem ? -
Got AttributeError when attempting to get a value for field `user_name` on serializer `UserRegistrationSerializer`
I'm trying to create a custom user model with user role but when registering users i keep getting the same error this is what i did MY USER MODEL class User(AbstractBaseUser, PermissionsMixin): class RoleType(models.TextChoices): SCHOOL = 'SCHOOL' PARENT = 'PARENT' role = models.CharField(max_length=50, choices=RoleType.choices, default=RoleType.SCHOOL) user_name = models.CharField(max_length=255, unique=True, db_index=True) email = models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'user_name' REQUIRED_FIELDS = ['email'] objects = UserManager() def __str__(self): return self.email def tokens(self): refresh = RefreshToken.for_user(self) return { 'refresh': str(refresh), 'access': str(refresh.access_token) } THE PARENT MODEL class Parent(models.Model): # other fields related to student ... Parental_code = models.CharField(max_length=10, unique=True) user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user", null=True) THE SERIALIZER class UserRegistrationSerializer(serializers.ModelSerializer): RoleType = { 'SCHOOL': 'SCHOOL', 'PARENT' : 'PARENT' } role = serializers.ChoiceField( choices=RoleType, default=RoleType['PARENT']) class Meta: model = User fields = ['user_name', 'password', 'email', 'role'] extra_kwargs = { 'password': {'write_only': True}, 'email': {'required': True}, 'user_name': {'required': True} } def create(self, validated_data): user = User.objects.create_user(**validated_data) return user class ParentSerializer(serializers.ModelSerializer): user = UserRegistrationSerializer(write_only=True) class Meta: model = Parent fields = ['Parental_code', 'user'] def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create_user(**user_data) user = Parent.objects.create(user=user, **validated_data) return user THE ERROR IM GETTING i tried cheking the spellings but … -
Best practice for intercepting error responses in Django and DRF
I have a Django app that uses the Django Rest Framework. Errors may occur on the Django side, like integrity errors in the database. The default error response will be something like: { "details": { "email": "user with this email already exists." } } Validation errors may also occur DRF side: { "detail": ... } As you can see, there is an inconsistency in the response message, as Django uses "details" and DRF uses "detail". However, I like neither format. I want to respond with a message in the following format: { "message": ... "code": ... } My question is: What is the best practice to handle both Django and DRF exceptions and respond with a custom response body? I have tried: custom exception handler in DRF, but this only handles DRF exceptions custom error messages when defining models email = models.EmailField(error_messages={"required": {"message": "", "code": 123}}) but Django can't handle a dictionary as a message Adding a DRF validator to my serializer: email = serializers.EmailField( validators=[ UniqueValidator( queryset=models.User.objects.all(), message={ "message": "a user with this email already exists", "code": status.EMAIL_EXISTS, }, ) ], ) but this does not override the response body, but instead it embeds the message as an error … -
Using Serializer waste of time while creating new record into database?
In my django Application i have a model and serializer for it as:- 1.) model:- class Requests(models.Model): a = models.AutoField(primary_key=True) b = models.CharField(max_length=20) c = models.CharField(max_length=20) 2.)serializer:- class RequestsSerializer(serializers.ModelSerializer): class Meta: model = Requests fields = '__all__' Now i am using serializers when creating a new record into DB table as:- serialized_item=RequestsSerializer(data=request.data) serialized_item.is_valid(raise_exception=True) serialized_item.save() now i had a doubt that is_valid is hitting DB and .save again hit DB, So because of Serializer we are hitting DB 2 times and if we remove that and directly create a record into database then it will hit the database only once. So here serialier is just adding overhead on database right?, So what is the use of Serializer here? -
How can I get annotate field using child model in Django?
I have problem with getting Annotate field in Django(DRF). For example, there are two models called AA, BB. class AA(models.Model): name = models.CharField() class BB(models.Model): parent = models.ForeignKey(AA, related_name="BB") name2 = models.CharField() Then, I want to get the list AA, with annotate field called status. The status condition is word(provided by client)=name2 For example, [ { name: "aaa1", status: True, // if "aaa1" in AA has the word }, { name: "aaa2", status: False, // if "aaa2" in AA doesn't have the word } ] So I coded like following code in views.py, queryset = (AA.objects.prefetch_related("BB").annotate( status=Case( When(BB__name2=word, then=Value(True)), default=Value(False), output_field=BooleanField() ) )) but the following results came out. (If the word is "bbb1") [ { name: "aaa1", status: True, // "bbb1" whose parent is "aaa1" }, { name: "aaa1", status: False, // "bbb2" whose parent is "aaa1" }, { name: "aaa1", status: False, // "bbb3" whose parent is "aaa1" }, { name: "aaa2", status: True, // "bbb1" whose parent is "aaa2" } ] I want to know if even one child model(BB) has name2 from a parent(AA)'s point of view, and it returned a list of all children. What should I do? -
Deploying Django App onto Elastic Beanstalk (mysqlclient issue)
Having a bit of a mare trying to deploy my Django app to Elasticbeanstalk AWS I'm getting issues related to the installation of mysql. See log files: ---------------------------------------- /var/log/eb-engine.log ---------------------------------------- × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [24 lines of output] Trying pkg-config --exists mysqlclient Command 'pkg-config --exists mysqlclient' returned non-zero exit status 1. Trying pkg-config --exists mariadb Command 'pkg-config --exists mariadb' returned non-zero exit status 1. Trying pkg-config --exists libmariadb Command 'pkg-config --exists libmariadb' returned non-zero exit status 1. Traceback (most recent call last): File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 363, in <module> main() File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 345, in main json_out['return_val'] = hook(**hook_input['kwargs']) File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 130, in get_requires_for_build_wheel return hook(config_settings) File "/tmp/pip-build-env-0u1shkl5/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 325, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=['wheel']) File "/tmp/pip-build-env-0u1shkl5/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 295, in _get_build_requires self.run_setup() File "/tmp/pip-build-env-0u1shkl5/overlay/lib/python3.8/site-packages/setuptools/build_meta.py", line 311, in run_setup exec(code, locals()) File "<string>", line 155, in <module> File "<string>", line 49, in get_config_posix File "<string>", line 28, in find_package_name Exception: Can not find valid pkg-config name. Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually [end of output] My Python pip requirements file is: beautifulsoup4==4.12.3 bs4==0.0.2 Django==2.2 gunicorn==20.1.0 mysqlclient==2.2.4 numpy==1.24.4 pandas==2.0.3 python-dateutil==2.9.0.post0 pytz==2024.1 six==1.16.0 soupsieve==2.5 sqlparse==0.4.4 tzdata==2024.1 whitenoise==6.4.0 and I've also specified … -
Difficulty in getting the number of data
Difficulty in getting the number of data, which does not receive all the data model is : class ArchiveChat(models.Model): id = models.BigIntegerField() user_jid = models.CharField(max_length=255,primary_key=False) class Meta: db_table = 'li_archive_chat' message_count = ArchiveChat.objects.count() message_count is 77000 The number of real data is 78 thousand, but this query returns 77 -
added gml layer to openlayers does not appear on map
I recently moved from using leaflet to using openlayers. For a new project I want to display the content of a gml file on a openlayers map. But whatever I have tried nothing gets visible on the map. When I print the content of the fetch response I see the string of the gml content being printed perfectly to the console however when I print the features variable after parsing the gml I end up with an empty array. I have read the official documentation and written some javascript code according to the API discription. I use a python request in django to obtain the text content of the gml and make it accessable for the front end javascript. When I log the fetch response to the console in dev tools I see that the string of the fetch response get's printed succesfully, however when I log the features variable to the console I end up with an empty array and nothing visible on the map. The gml file that I try to add to the map can be found here: https://ruimtelijkeplannen.nl/documents/NL.IMRO.0252.GHbpkernMalden-VA01/NL.IMRO.0252.GHbpkernMalden-VA01.gml My used javascript code: import Map from '../../../node_modules/ol/Map.js'; import OSM from '../../../node_modules/ol/source/OSM.js'; import TileLayer from '../../../node_modules/ol/layer/Tile.js'; import View … -
Implementing Email Confirmation & Reminder System and WhatsApp Messaging Integration in Django
I'm developing a Django-based project that requires implementing an email confirmation and reminder system, as well as WhatsApp messaging integration. The project has specific user engagement features, such as sending confirmation emails upon survey completion and scheduling reminder emails, with an expected volume of about 50,000 emails per month. Additionally, it involves sending automated WhatsApp messages to users based on their interactions with the platform. Here are the technical challenges I'm facing: Email System Implementation: How can I efficiently manage and send a large volume of emails (approx. 50,000/month) in Django? What are the best practices for scheduling and sending reminder emails at predetermined dates? I'm particularly interested in understanding how to optimize Django's email backend for this scale and whether Django's built-in features or third-party libraries are more suited for this task. WhatsApp Messaging Integration: What is the recommended approach for integrating WhatsApp messaging into a Django application? Are there specific Django packages or tools that facilitate this integration while ensuring scalability and reliability? My main objective is to implement these features in a cost-effective and efficient manner, focusing on scalability and reliability. I'm looking for insights into the technical implementation within Django's framework that adhere to best practices. … -
Can't add value to table Django DataBase
Sorry i am beginer in django try to make app for appoiment for doctors and could not solved this problem I can't add value in to Appoiment Db in to django app this is my models.py from django.db import models models.py_ doctor_name = models.CharField(max_length=80) specialization_doctor = models.CharField(max_length=80) def __str__(self): return self.doctor_name class Appoiment(models.Model): doctor_name = models.ManyToManyField(Doctors) date_appoiment = models.DateField() time_appoiment = models.TimeField() patient_name = models.CharField(max_length=80) patient_phone = models.CharField(max_length=15) reason_for_visit = models.TextField(max_length=400) def __str__(self): return self.patient_name And this is my views.py i'm trying many ways but steal can't approch to solve it VIEWS.PY from django.shortcuts import render from .models import Doctors,Appoiment from .forms import AppoimentForm from django.http import HttpResponseRedirect def main(request): list_of_doctors = Doctors.objects.all().values('doctor_name') list_of_doctors = [item['doctor_name']for item in list_of_doctors] doctor_name='' date_appoiment='' time_appoiment='' name='' phone='' reason='' form = '' patient='' if request.method == 'POST': doctor_name = request.POST.get('doctor_name') date_appoiment = request.POST.get('date') time_appoiment = request.POST.get('time') name = request.POST.get('name') phone = request.POST.get('phone') reason = request.POST.get('reason') # doctor = Doctors() # The problem is here how to write right statement #------->> patient = Appoiment.objects.create(doctor_name=doctor_name,date_appoiment=date_appoiment,time_appoiment=time_appoiment,patient_name=name,patient_phone=phone,reason_for_visit=reason) return render(request,'main.html',{'list_of_doctors':list_of_doctors,'patient':patient})``` -
UNIQUE constraint failed: customuser.username
im trying to understand the drf. I´ve set up all the endpoints and they work, the only thing that doesnt work is when i want to post something to my database, the first Post goes well and then the second one shows an integrity error, ive been stuck now for a few days haha Could somebody help me understand what i am missing here models.py : class CustomUser(AbstractUser): name = models.CharField(max_length=30) email = models.EmailField(default ="no email") first_name = models.CharField(max_length = 25 ,default = 'No name') last_name = models.CharField(max_length = 25, default = 'No surname') password = models.CharField(max_length = 25,default = "no password") def __str__(self): return self.name views.py class CustomModelViewSet(ModelViewSet): serializer_class = UserSerializer queryset = CustomUser.objects.all() @api_view(['GET', 'POST']) def user_list(request,format =None): #get all users #serialize them #return json if request.method == 'GET': allUser = CustomUser.objects.all() serializer = UserSerializer(allUser, many=True) return Response(serializer.data) elif request.method =='POST': serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) @api_view(['GET','PUT','DELETE']) def user_detail(request,id,format =None): try: user = CustomUser.objects.get(pk=id) except CustomUser.DoesNotExist: return Response(status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = UserSerializer(user) return Response(serializer.data) elif request.method == 'PUT': serializer = UserSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': user.delete() return Response(status=status.HTTP_204_NO_CONTENT) serializers.py class … -
Django-cte gives: 'QuerySet' object has no attribute 'with_cte'
I have records in below format: | id | name | created | ----------------------------------------------- |1 | A |2024-04-10T02:49:47.327583-07:00| |2 | A |2024-04-01T02:49:47.327583-07:00| |3 | A |2024-03-01T02:49:47.327583-07:00| |4 | A |2024-02-01T02:49:47.327583-07:00| |5 | B |2024-02-01T02:49:47.327583-07:00| Model: class Model1(model.Models): name = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) I want to perform a group by in django with month from field created and get latest record from that month. Expected output: | id | name | created | ----------------------------------------------- |1 | A |2024-04-10T02:49:47.327583-07:00| |3 | A |2024-03-01T02:49:47.327583-07:00| |4 | A |2024-02-01T02:49:47.327583-07:00| I am using django-cte to perform the above action from django.db.models.functions import ExtractMonth m = Model1.objects.get(id=1) cte = With( Model1.objects.filter(name=m.name) rank=Window( expression=DenseRank(), partition_by=[ExtractMonth("created")], order_by=F("created").desc(), ) ) qs = cte.queryset().with_cte(cte).filter(rank=1) But the above give error: qs = cte.queryset().with_cte(cte).filter(rank=1) ^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'QuerySet' object has no attribute 'with_cte' Please help! -
Django test_get_chat_list
I have a really strange problem because my ...chat_list test returns every time different result, test is waiting for the order [2 3 1] but is's every time different. Here my test: def test_get_chat_list(self): # Create 3 users with whom we will have chats. user_1 = UserFactory() user_2 = UserFactory() user_3 = UserFactory() # Create chats with them chat_1 = ChatFactory(user_1=self.user, user_2=user_1) chat_2 = ChatFactory(user_1=self.user, user_2=user_2) # Let our user be in the role of user_2 in the third chat. chat_3 = ChatFactory(user_1=user_3, user_2=self.user) # Create one message in each chat. # To test the correctness of sorting chats # we intentionally create a message first in the third chat, # and then in the second. mes_1 = MessageFactory(author=self.user, chat=chat_1) mes_3 = MessageFactory(author=self.user, chat=chat_3) # Also create one message from the interlocutor. mes_2 = MessageFactory(author=user_2, chat=chat_2) # Create a batch of foreign messages in foreign chats. # They are needed to make sure # that we only receive our chats and messages. MessageFactory.create_batch(10) with self.assertNumQueries(2): response = self.client.get(self.url, and here my view function: def get_queryset(self): user = self.request.user last_message_subquery = Message.objects.filter( chat=OuterRef('pk') ).order_by('-created_at').values('created_at')[:1] last_message_content_subquery = Message.objects.filter( chat=OuterRef('pk') ).order_by('-created_at').values('content')[:1] qs = Chat.objects.filter( Q(user_1=user) | Q(user_2=user), messages__isnull=False, ).annotate( last_message_datetime=Subquery(last_message_subquery), last_message_content=Subquery(last_message_content_subquery), ).select_related( "user_1", …