Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: update model via task
The code examples mentioned below are (over) simplified I have a users model with a field where all data related to each user from that model is recorded as xml. File -> users.py class Users(models.Model): firstname = models.CharField(max_length=200) dob = models.DateTimeField("date published") unconfirmed = models.BooleanField(blank=True, default=False) xml = models.TextField(blank=True, default="") I created a task in charge of updating that field for all users. At the end of the process, I trigger user.save() and it works fine. This task will be used on a regular basis to run a full update File -> update-users-xml.py Class Command(ParallelCommand): def handle(self, *args, **options): users = Users.objects.filter(unconfirmed__isnull=True) for user in users: # Get all fields user.xml = .... user.save() Now, what I'm trying to achieve is -> if an user is edited/created from the admin, the task is called and the xml column is updated. I edited the save function in the users model to trigger the task: def save(self, *args, **kwargs): async_task(call_command, "update-users-xml", self.id) And, as I anticipated, it wouldn't work because: Can't update because of lock key Maximum recursion depth exceeded Checking what options are available, using signal seems the way to go but I cannot make it work In the users model, … -
Why is 'Go Back' button not working in Django?
I am currently building an image description writing website. Tools/langs I use are html, css, django, and javascript. The problem is, when I click on the 'Go back' button on the html provided below, it doesn't redirect me to the previous mission-acting-writing page (account:write_page_url) but stays at the mission-acting-finish.html. 'Posting' and 'Image' are the models stored in models.py. 'Posting' stores every info user enters when writing one's post, and 'Image' stores individual image files extracted from the image zip file user has provided when writing the post. I've been struggling with this problem for the past 20 hours nonsleep. Please identify the problem in the code. Thank you so much in advance! Here is the code of my function 'end' in views.py: def end(request, posting_id, image_index): posting = get_object_or_404(Posting, id=posting_id) user_detail, created = UserDetail.objects.get_or_create(user=request.user) if request.method == 'POST': action = request.POST.get('action') if action == 'complete': total_reward = request.session.get('total_reward', 0) user_detail.point += total_reward user_detail.save() request.session['total_images'] = 0 request.session['total_reward'] = 0 request.session['image_index'] = 0 request.session['listlength'] = posting.remaining_count return redirect('account:explore') context = { 'total_images': request.session.get('total_images', 0), 'total_reward': request.session.get('total_reward', 0), 'posting_id': posting_id, 'image_index': image_index, } request.session.pop('image_ids', None) return render(request,'mission-acting-finish.html',context)` Here is a section of my mission-acting-finish.html: <main class="main-wrapper"> <header class="section_product-header"> <div class="w-layout-blockcontainer w-container"> <h1 … -
Showing 'str' object has no attribute 'text'
I am trying to build a quiz app, where a user can select an option and the option is saved against its question in a particular quiz. So i tried using the below approach. I created my models.py as below. class Quiz(models.Model): name=models.CharField(max_length=200) topic=models.CharField(max_length=100) number_of_questions=models.IntegerField() difficulty=models.CharField(max_length=100,choices=difficulty_choices) TimeLimit=models.IntegerField(blank=True) def get_questions(self): return self.questions_set.all()[:self.number_of_questions] class Questions(models.Model): text=models.CharField(max_length=200) quiz=models.ForeignKey(Quiz,on_delete=models.CASCADE) correct=models.CharField(max_length=25) def __str__(self): return str(self.text) def get_answers(self): return self.answers_set.all() class Answers(models.Model): text = models.CharField(max_length=200) question = models.ForeignKey(Questions, on_delete=models.CASCADE) def __str__(self): return f"Question: {self.question.text}, Answer: {self.text}" class UserAnswer(models.Model): quiz=models.ForeignKey(Quiz,on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Questions, on_delete=models.CASCADE) answer = models.ForeignKey(Answers, on_delete=models.CASCADE,null=True,blank=True) now the question and eahc of its respective answers is displayed in a form. the options are in the forms of radio select button. I have created that form below. class QuizForm(forms.ModelForm): class Meta: model = Quiz fields = ['text'] exclude = ["text"] # Add other fields as needed selected_answer = forms.ChoiceField( label="Select the correct answer", choices=[], # We'll update choices dynamically widget=forms.RadioSelect ) def __init__(self, *args, **kwargs): super(QuizForm, self).__init__(*args, **kwargs) quiz_instance = kwargs.get('instance') questions = quiz_instance.get_questions() for question in questions: answers = question.get_answers() answer_choices = [(answer.id, answer.text) for answer in answers] # Update the choices of the selected_answer field self.fields['selected_answer'].choices = answer_choices Now in … -
AWS ALB DNS is not reachable
New to AWS. I setup ECS and create a task with ALB. Running python Django application in ECS task on port 8000, and ALB shows healthy on status based on health endpoint. When I try to run curl http://<DNS_ALB>/<healthcheck endpoint> its not able to return any data. ALB shows healthy means that health check endpoint is reachable from ALB to ECS container. There is not specific security, I am using all default VPC and Security group. Default security group has ALL inbound and ALL outbound open. I know I have to change the security and all, but just trying to learn with default if all things works, then will add more security. -
How to edit a models (users) field ''globally'' using fetch or ajax?
So I have this JavaScript file and I want to globally change a field for the current authenticated user? I have a profile model with a level field: class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) level = models.IntegerField(default=1) And for my url I have added the context and got it to log into the targeted JS file urls.py def game(request): profile = Profile.objects.get(user=request.user) #profile object level = profile.level #level context from the profile return render(request, 'games/game.html', {'level': level}) game.js: const data = document.currentScript.dataset; const level = parseInt(data.level); console.log(level); // BOILER PLATE FETCH // fetch(url, { method: "POST", credentials: "same-origin", headers: { "X-Requested-With": "XMLHttpRequest", "X-CSRFToken": getCookie("csrftoken"), }, body: JSON.stringify({payload: "data to send"}) }) .then(response => response.json()) .then(data => { console.log(data); }); and It console logs the level from that, However I want to know Is it possible to ''globally'' edit the level value using that boilerplate fetch down there? or maybe Ajax? My main issue is that I think I could specifically edit the level for the showProfilePage view (maybe) but I would prefer the level to be permanently updated to the desired number. That way it would retain its updated number anywhere I used its context. I just don't even … -
Django ORM .distinct() seems to return duplicate results
I have an Event model that represents an Event happening. I have another EventShow model which represents a date and time that the event is taking place. Each event can have multiple shows, so I have a ForeignKey from EventShow to Event as follows - class Event(models.Model): name = models.CharField(max_length=32) # ... and more class EventShow(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='shows') start_date = models.DateTimeField() I want to get a list of events which have at least one show happening in the future, so in my view I'm calling the ORM like this - events = Event.objects.filter(shows__start_date__gt=now()).prefetch_related('shows').distinct().order_by('shows__start_date') However, I still get the same event showing up multiple times if it has multiple shows. How can I fix this? I looked at the SQL that was being generated by this call - SELECT DISTINCT "core_event"."id", "core_event"."name", "core_eventshow"."start_date" FROM "core_event" INNER JOIN "core_eventshow" ON ("core_event"."id" = "core_eventshow"."event_id") WHERE ("core_eventshow"."start_date" > 2023-08-16 02:48:46.063093) ORDER BY "core_eventshow"."start_date" ASC I'm using SQLite for development. -
Gunicorn & Django: Handle timeout
We run a Django REST API behind Gunicorn (on a Kubernetes Cluster in EKS exposed via AWS ALB). The Gunicorn command: gunicorn config.wsgi --timeout 20 (...) When a request takes over 20 seconds to be processed by Django (due to various reasons), gunicorn will timeout by emitting a SigAbt signal and restart the gunicorn worker. However, this causes an issue in tracking the error in various tools such as Datadog or Sentry which are not able to track the error correctly. Instead, we would like to emit an explicit error (customer error) called TimeoutError. After a thorough investigation, we want to find the best way to raise this TimeoutError at Django Level when the request takes 20 seconds to complete. What would be a recommended solution? -
Django slice then filter queryset
I'm trying to use pgvector to find similar products by name, I've built the embedding on the name, now, when I try to use the method that is stated on the docs for pgvector in order to get the products with a certain distance using ALIAS the query never executed, I tried the other method using group_by which worked the get top 10 for example, but in some cases, top 10 might be too far from being similar to the product, That's why I want to order_by then filter based on the distance only for the 100 in order to ensure that I'm getting similar items, The problem with Django is I can't filter after slicing the queryset, I have a workaround which is: Getting the top 100 ordered by distance and then using their id to filter for the next query which will cause more executing time. (More than 100K records) Is there a better way of doing it, thanks. Slice then filter: result = self.get_queryset().order_by(L2Distance('name_embedding', entry_vector))[:100].alias(distance=L2Distance('name_embedding', entry_vector)).filter(distance__lt=threshold) -
Django Custom User model and Authentication
i want to create a user model for three types of user role Student, Teacher and Principal By inheriting AbstractUser in Django how can i do this.? i have seen many projects but the create a single table for authentication of all students, teachers and principal and link it to another model such as StudentProfile, TeacherProfile and PrincipalProfile using onetoone field i want that all student information such as their username, email, password,... to be saved in a single table similarly i want all info for teacher to be save in single table (Not in student table) same for principal Is it possible? If yes how can i perform their authentication -
I am getting AnonymousUser for request.user after loggin out in Django. How can I fix this?
I have a view called LogoutView that is decorated with the @permission_classes([IsAuthenticated]) decorator. When I call the get() method on this view, I am getting AnonymousUser for request.user after logging out. I have tried the following things to fix this, but none of them have worked: I have checked the request.user.is_authenticated attribute to make sure that the user is authenticated before logging them out. I have returned a 401 Unauthorized response if the user is not authenticated. I have called the logout() method to log the user out. from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from myapp.models import User from django.contrib.auth import authenticate, login, logout import requests from django.shortcuts import get_object_or_404 from django.http import JsonResponse from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated, AllowAny from .models import ChatRoom, UserChatRoom from myapp.serializers import ChatRoomSerializer, UserSerializer from django.contrib.sessions.models import Session from django.contrib.auth import login, authenticate from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status import requests from .models import User # Make sure you import your User model correctly from rest_framework.permissions import AllowAny class GoogleLoginView(APIView): permission_classes = [AllowAny] def post(self, request): credential = request.data.get('credential') google_response = requests.get(f'https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={credential}') if google_response.status_code == 200: google_data = … -
How can I access templates from an imported Django application?
I want to pip install a Django application and be able to access its templates when adding it to the "INSTALLED_APPS" section in Django project's "settings.py" file. I followed the tutorial here to build a Django app and export it as an installable package, then installed this package into the virtual environment of another Django project. Everything works fine when I add the app's name in INSTALLED_APPS and when I include the urls of the imported app in the project's urls.py file. However, when I run the lightweight server of the Django project and try to access one of the imported app's page, I get a "django.template.exceptions.TemplateDoesNotExist" error. Why would Django allow to access the urls and views of an imported app, but not its templates or templatetags? When running the server and sending a request to it for a specific web page, I was expecting to get this web page (located in the templates of the imported app) to load on my browser. -
django view function is not executing in asgi mode
I am using django development environment to develope an app while trying to execute view function i am getting raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. i have configured the django app using asgi mode and running the daphne via command daphne myproject.asgi:application. there is a signup form in my app where user put his name,company_id,email as username and password. i want to store the username,password in user model and the company_id against that user in userprofile model. signup view is failing to execute the django orm queries and i am unable to store the data as expected. ``` async def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.email = user.username user.first_name = request.POST.get('first_name') user.last_name = request.POST.get('last_name') user.save() customer_id = request.POST.get('customer_Id') # Get the customer_id from the form print(customer_id) try: customer = await sync_to_async(Customer.objects.get)(customer_id=customer_id) except Customer.DoesNotExist: return render(request, 'core/signup.html', {'form': form, 'error_message': 'NA'}) userprofile = await sync_to_async(Userprofile.objects.create)(user=user, customer=customer) await sync_to_async(userprofile.save)() await sync_to_async(login)(request, user) # Using sync_to_async for login return redirect('landingpage') else: form = UserCreationForm() return render(request, 'core/signup.html', {'form': form}) ``` -
How can I move data from one model to another with Django/python?
basically i have trhee models where the information of user is already there, but i created a third model called License user, so that i can move the information to that model, how can i do that in an efficient way? Model 1 class License1(models.Model): full_name = models.TextField(blank=False, null=False) email = models.TextField(blank=True, null=True) expire_date = models.DateTimeField(blank=False, null=False) unitcode = models.TextField(blank=True, null=True) wg_version = models.CharField(max_length=10, blank=False, null=False) user_name = models.CharField(max_length=40, blank=False, null=False) description = models.TextField(blank=True, null=True) Model 2 class License2(models.Model): full_name = models.TextField(blank=False, null=False) email = models.TextField(blank=True, null=True) expire_date = models.DateTimeField(blank=False, null=False) unitcode = models.TextField(blank=True, null=True) wg_version = models.CharField(max_length=10, blank=False, null=False) user_name = models.CharField(max_length=40, blank=False, null=False) description = models.TextField(blank=True, null=True) User Model class UserLicense(models.Model): """User information model.""" user_name = models.CharField(max_length=40, blank=False, null=False, unique=True) full_name = models.CharField(max_length=80, blank=False, null=False, unique=True) email = models.TextField(blank=False, null=False) I'm usign db.sqlite3, if anyone can explain the process i would be really grateful -
Running R code in Python using rpy2 - Kernel dying
I want to run a R code in my pythons jupyter notebook, My plan is to run the model with both R code and python combined in Django server to publish the ML model(I myself din't make the model so I dont know anything about it). People who made the ML model have used both python varaibles in R code and R varibles in python code. So it would be better if I have all of the programs in a single django server. Due to which I want to run the R code in my python jupyter notebook as the first step. I came accros rpy2 and tried using rpy2 for this. But whenever I try to import something from rpy2 my kernel just dies I just did "pip install rpy2" as suggested to install rpy2. Do I need to set a path like this to for the import to work, But I dont know where to set the path of R to set to since I dont have R folder in my libs even after I installed rpy2 using pip Optional Quetion: Also on the side note is it possible to do what I am thinking on running the … -
Nautobot celery ERROR/MainProcess] Received unregistered task of type
I'm using nautobot with celery and redis for background tasks but it doesn't seem to work. This is my error: [2023-08-15 18:37:13,227: ERROR/MainProcess] Received unregistered task of type 'nautobot_device_onboarding.worker.onboard_device_worker'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: b'[["bcc4229d-f59b-427d-b702-042ff378bfed", {"__nautobot_type__": "nautobot_device_onboarding.utils.credentials.Credentials", "username": "UserAdmin", "password": "Acuat1v3", "secret": "Acuat1v3"}], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (269b) Thw full contents of the message headers: {'lang': 'py', 'task': 'nautobot_device_onboarding.worker.onboard_device_worker', 'id': '3adba9a4-6aee-49ce-bdca-78eafb6c43e1', 'shadow': None, 'eta': None, 'expires': None, 'group': None, 'group_index': None, 'retries': 0, 'timelimit': [None, None], 'root_id': '3adba9a4-6aee-49ce-bdca-78eafb6c43e1', 'parent_id': None, 'argsrepr': "(UUID('bcc4229d-f59b-427d-b702-042ff378bfed'), *Credentials argument hidden*)", 'kwargsrepr': '{}', 'origin': 'gen56@f8decca231bf', 'ignore_result': False} The delivery info for this task is: {'exchange': '', 'routing_key': 'default'} Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/celery/worker/consumer/consumer.py", line 591, in on_task_received strategy = strategies[type_] KeyError: 'nautobot_device_onboarding.worker.onboard_device_worker' This file is the worker.py where the task should be defined with the @nautobot_task, the import works but it doesn't define the function. try: from nautobot.core.celery import nautobot_task CELERY_WORKER = True @nautobot_task def onboard_device_worker(task_id, credentials): """Onboard device with Celery worker.""" return onboard_device(task_id=task_id, credentials=credentials) except ImportError: … -
Microsoft Teams integration for Django self-hosted in AWS
I already spent several hours on Microsoft docs making very little progress for what I believe should be a trivial integration, but apparently it's not. I've a Slack integration (via Slack app, built in Django and hosted on AWS) that works this way: our client installs the app and we receive a single token with the token we can pull all slack workspace accounts once that's done, our app sends 2 types of messages using that same token: a message to a public slack channel a 1-to-1 message to an individual I need to replicate this behaviour for Microsoft Teams. I don't want to use Azure, nor node.js, ideally if I could spin up few endpoints to exchange tokens on Django and some logic to send the messages that would be gold. At this point I will take any wisdom from Teams experts ... Thanks -
AttributeError: module 'projeto_cad_chip' has no attribute 'wsgi'
I have a problem when i'll deploy my Django application. The error return is: error return This is my file path: file path I have too my web.config in wwwroot: web.config I'm using windows server 2008 and python 3.7 wsgi.py: wsgi.py I already check my Handler Mappings and FastCGI Settings, but doesn't found anything wrong, by i know. I trying to deploy a Django application in a local Windows Server, but when open in the port 80 returns me this error: Error occurred while reading WSGI handler: Traceback (most recent call last): File "c:\users\nmcscript\appdata\local\programs\python\python37\lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "c:\users\nmcscript\appdata\local\programs\python\python37\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "c:\users\nmcscript\appdata\local\programs\python\python37\lib\site-packages\wfastcgi.py", line 603, in get_wsgi_handler handler = getattr(handler, name) AttributeError: module 'projeto_cad_chip' has no attribute 'wsgi' StdOut: StdErr: -
Why I ain't able to open a file after downloading "virtualenv env" as I saw it in a Yt tutorial video
I decided to learn the Django tutorial from the Yt video but as I saw that guy gave a command "pip install "virtulenv env" and a new file was opened in his file explorer. Then he again downloaded several other stuffs but I stucked on this step only and he moved ahead of me completing Django download successfully and started coding. A complete set up guidance for Django environment for Windows11, including commands and if raised any issue their solutions. -
How can I add taggit tags to a newly created Django model instance?
I'm unable to add Taggit tags to a newly created Django model instance from within a DRF serializer. When attempting to do use the new instance, the operation fails with list object has no attribute add. class ThingSerializer(serializers.ModelSerializer): def create(self, validated_data): # fails with `list object has no attribute add` thing = Thing.objects.create(**validated_data) custom_tags = validated_data.pop("custom_tags", []) for custom_tag in custom_tags: thing.custom_tags.add( custom_tag.pop("name"), tag_kwargs=custom_tag ) thing.save() def create_with_hack(self, validated_data): # works after fetching the record from DB thing = Thing.objects.create(**validated_data) thing_ = Thing.objects.get(pk=thing.id) custom_tags = validated_data.pop("custom_tags", []) for custom_tag in custom_tags: thing_.custom_tags.add( custom_tag.pop("name"), tag_kwargs=custom_tag ) thing_.save() As noted above, I'm able to work around this by first explicitly fetching record from the database but that is undesirable. Also, the refresh_from_db model method does not solve the problem. Python 3.8 Django 4.2.2 Taggit 4.0.0 -
How to use Django views variables in Google Maps API Javascript on HTML template?
For obvious reasons, I'll be referring to my API KEY by [GOOGLE_API_KEY]. I have the following view : def search_places(request): GOOGLE_API_KEY = os.getenv('google_api_key') search_keywords = request.POST.get('keywords') search_type = request.POST.get('type') top = request.POST.get('top') is_open = request.POST.get('open') w_duration = 1 - (int(request.POST.get('w-duration')) / 100) rating_filter = float(request.POST.get('btnradio-rtg')) price_filter = int(request.POST.get('btnradio-price')) # Converting is_open from string to bool if is_open: is_open = True else: is_open = False df_users = get_all_users_df() dict_users = format_df_users_for_map(df_users) barycenter = compute_barycenter(df_users) return render(request, "index.html", {'google_api_key': GOOGLE_API_KEY, 'dict_users': dict_users, 'barycenter': barycenter } ) Which return in dict_users and in barycenter the following : dict_users = [{'lat': 48.8501531, 'lng': 2.3897723, 'name': 'John'}, {'lat': 48.8490926, 'lng': 2.458714, 'name': 'Jack'}, {'lat': 48.8472106, 'lng': 2.3792469, 'name': 'James'}, {'lat': 48.8490926, 'lng': 2.458714, 'name': 'Jose'}] barycenter = (48.848887225, 2.4216118) In my 'index.html' template, I have : <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="shortcut icon" href="{% static 'css/favicon.ico' %}" type="image/x-icon"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin="anonymous"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://maps.googleapis.com/maps/api/js?key=[GOOGLE_API_KEY]&libraries=places" defer></script> </head> With a script block : <html lang="en"> <body style="background-color: #f4f6f9;"> <script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))}) ({key: "[GOOGLE_API_KEY]", v: "beta"}); // … -
prevent closing of python app using windows CMD X button (by mistake)
I have a running Django app (localy) in "start.bat" file. CALL venv\Scripts\activate.bat manage.py runserver 0.0.0.0:8000 --insecure --noreload Someone on the PC sometimes close the window How can I prevent this? like: warning popup with prompet / hide X button / run in different app than CMD ? I did run it on TK gui but it was messing with my process manager inside the Django. -
Update the text entry widget in a django_jsonform JSONField
I'm using a JSONField from django_transform for a json column in my DB. On the admin page Django renders a nice form that allows users to add entries to the json according to the schema. I want to switch out the text entry input field (a Textinput, I think) for string inputs in the JSONField form with a rich text entry widget. I've tried overwriting the JSONField widget with a rich text widget (I'm using TinyMCE) but that replaces the whole thing and just prints the dumped json string in it. Is it possible to override internal widgets of the JSONField form? -
TypeError at /empinfo/add EmployeeInfoViewset.get_empinfo() got an unexpected keyword argument 'pk'
Here i was used Django Rest Framework to create simple API, But I was facing the Error on try to create new data model.py class EmpPersonalInfo(models.Model): emp_id = models.OneToOneField( 'Employees', models.PROTECT, primary_key=True, db_column='emp_id', verbose_name='Employee ID') dob = models.DateField(verbose_name='Date of Birth') mobile = models.CharField( max_length=10, unique=True, verbose_name='Mobile No.') email = models.CharField(max_length=45, unique=True, verbose_name='Email Address') aadhar = models.CharField(max_length=12, unique=True, verbose_name='Aadhar No.', help_text='Enter Aadhar no. without space') pan = models.CharField(max_length=20, unique=True, verbose_name='PAN No.') add1 = models.CharField(max_length=100, blank=True, null=True, verbose_name='Address line') city = models.CharField(max_length=25, blank=True, null=True, verbose_name='City') state = models.CharField(max_length=25, blank=True, null=True, verbose_name='State') pincode = models.IntegerField( blank=True, null=True, verbose_name='Pincode') class Meta: managed = False db_table = 'emp_personal_info' verbose_name_plural = "Personal Information" def __str__(self): return str(self.emp_id) in my Django app i was used without id field, but in my Mysql Db table i have extra id field Auto increment but not PK, emp_id only used FK and PK here. views.py class EmployeeInfoViewset(viewsets.ViewSet): queryset = EmpPersonalInfo.objects.all() serializer_class = EmpInfoSerializer lookup_field = 'emp_id' @api_view(['GET']) def get_empinfo(request, emp_id=None): with connection.cursor() as cursor: if emp_id is not None: cursor.execute("CALL sp_get_empInfo(%s)", [emp_id]) else: cursor.execute("CALL sp_get_empInfo('')") results = cursor.fetchall() employee_info = [] for result in results: employee_info.append({'emp_id': result[0], 'dob': result[1], 'mobile': result[2], 'email': result[3], 'aadhar': result[4], 'pan': result[5], 'address1': result[6], 'city': … -
Multiple processes spawned when running Django runserver
Sometimes, When I run Django (ver 4.1.6) runserver and monitor the usage memory usage using htop I see that there multiple processes or threads spawned (see the below image). The same thing doesn't happen when running another application's Django even though most of the code is almost identical. Any idea why this is happening? Is there any setting to determine the number of threads? and how do I figure out where the issue is? -
Sending Catalogue WhatsApp Business API
I am trying to ingrate integrate WhatsaApp Business API. I have setup the webhook and can now receive messages through the webhook but when when I send a catalogue, the webhook says Message type is currently not supported.Below is the full response { 'object': 'whatsapp_business_account', 'entry': [ { 'id': '**********************', 'changes': [ { 'value': { 'messaging_product': 'whatsapp', 'metadata': { 'display_phone_number': '***************', 'phone_number_id': ''***************' }, 'contacts': [ { 'profile': { 'name': 'Majesty' }, 'wa_id': 'Majesty' } ], 'messages': [ { 'from': ''***************', 'id': 'wamid.'***************==', 'timestamp': ''***************', 'errors': [ { 'code': ******, 'title': 'Message type unknown', 'message': 'Message type unknown', 'error_data': { 'details': 'Message type is currently not supported.' } } ], 'type': 'unsupported' } ] }, 'field': 'messages' } ] } ] } Is there a way to send catalogue receive it through the webhook