Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to call celery task in Django from Fastapi app
I have two apps (Django and FastApi) that use Celery to do some background task. Now, I need to communicate the two applications and I have thought about reusing the queues that celery uses (I don't really know if it is the best way to do it).The two apps are using the same broker and all are in Docker containers. I wolud like to execute a task that is in the django app when calling a route in the FastApi app. Django app celery.py app = Celery("app_1") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) settings.py ... CELERY_TASK_DEFAULT_QUEUE = "app_1" CELERY_TASK_CREATE_MISSING_QUEUES = False CELERY_TASK_QUEUES = ( Queue("default"), Queue("app_1"), ) def route_task(name, args, kwargs, options, task=None, **kw): if ":" in name: queue, _ = name.split(":") return {"queue": queue} return {"queue": "default"} CELERY_TASK_ROUTES = (route_task,) ... tasks.py @shared_task( name="app_1:test", bind=True, base=BaseTaskRetry ) def test() -> None: print('Result') FastApi app create_celery.py def create_celery(): celery_app = Celery("app_2") celery_app.config_from_object(settings, namespace="CELERY") celery_app.autodiscover_tasks(["Infraestructure.Celery.tasks"]) return celery_app celery_app = create_celery() config_celery.py (In this case I have tried without defining the django exchange and defining it, but I've got the same result) ... django_exchange = Exchange('app_1', type='direct') settings = { ... 'CELERY_TASK_DEFAULT_QUEUE' : "app_2", 'CELERY_TASK_CREATE_MISSING_QUEUES' : False, 'CELERY_TASK_QUEUES' : ( Queue("app_2"), Queue('app_1', exchange=django_exchange), ), … -
Django: Configuration for serving static files on IIS server
I have a django application deployed on an AWS IIS server. Static fils are served just fine via 'runserver', but not via the IIS server. I have done everything right but it doesn't work. i even tried adding a static folder virtual directory but it didnt work. this is my webconfig: <?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <!-- Required settings --> <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> <!-- Your django path --> <add key="PYTHONPATH" value="C:\myvenv2\NutMIS" /> <!-- Your djangoname.settings --> <add key="DJANGO_SETTINGS_MODULE" value="NutMIS.settings" /> </appSettings> <system.webServer> <handlers> <!-- Remove duplicate entries --> <remove name="NutMIS" /> <remove name="StaticFiles" /> <remove name="StaticFile" /> <!-- Add handler for StaticFiles --> <add name="StaticFile" path="*" verb="*" modules="StaticFileModule" resourceType="Unspecified" requireAccess="Read" /> <!-- Add your custom NutMIS handler --> <add name="NutMIS" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Users\Administrator\AppData\Local\Programs\Python\Python311\python.exe|C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> <staticContent> <mimeMap fileExtension=".*" mimeType="application/octet-stream" /> </staticContent> </system.webServer> </configuration> this is my settings: STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / "static" The static files feature is installed in my IIS. My 'static' folder is placed in the app folder and it works just fine via runserver but not via the public IP over IIS. Please i need help with this. i also tried adding this web.config to to my static file folder … -
Python Django Framework - How to make up ownername and password in Models as login authentication?
This is my class models. I wish to use the ownername and vehicle_password in class Vehicle for owner login. #this is my models.py. class AbstractOwnerInfo(models.Model): ownername = models.CharField(max_length=100) vehicle_password = models.CharField(max_length=100) class Meta: abstract = True #this is my class Vehicle. class Vehicle(models.Model): id = models.AutoField(primary_key=True) parkingnumber = models.CharField(max_length=20) ownercontact = models.CharField(max_length=100) ownername = models.CharField(max_length=100) vehicle_password = models.CharField(max_length=100) IC = models.CharField(max_length=14) regno = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) vehiclecompany = models.CharField(max_length=50) pdate = models.DateField() intime = models.CharField(max_length=50, default='default_value') outtime = models.CharField(max_length=50) parkingcharge = models.CharField(max_length=50) remark = models.CharField(max_length=500) status = models.CharField(max_length=20) def __str__(self): return self.parkingnumber And then I defined the classess, I wish to use the ownername and vehicle_password in class Vehicles as login credentials. This is my defined member_login request and member_home request. def member_login(request): if request.method == 'POST': ownername = request.POST.get('ownername') password = request.POST.get('vehicle_password') if ownername and password: user = authenticate(username=ownername, password=password) if user is not None: login(request, user) messages.success(request, "Logged in successfully.") return redirect('member_home') else: messages.error(request, "Invalid login credentials. Please try again.") return render(request, 'member_login.html') def member_home(request): return render(request, 'member_home.html') And this is my member_login.html page. {% csrf_token %} <label for="ownername"><b>Ownername</b></label> <input type="text" name="ownername" class="form-control" required> <label for="vehicle_password"><b>Password</b></label> <input type="password" name="vehicle_password" class="form-control" required> <br> <input type="submit" value="Login" class="btn … -
AttributeError: 'NoneType' object has no attribute 'cursor'
I have a code that populates data to DB every time I run a script and this data gets displayed on a webpage. But I'm getting the error as : File "/xyz/dept/triangulation/work_dir/db.py", line 124, in populateSpecificRecord cur = conn.cursor() AttributeError: 'NoneType' object has no attribute 'cursor' def populateSpecificRecord(self, jobid, runid, run_label, table_name, input_dict): """Populate database where jobid and runid both exists""" if bool(input_dict) == True: inputStrList = [] logging.debug(f'Updating to db jobid {jobid}, runlabel {run_label}') for key in input_dict: elem = f"{key}='{input_dict[key]}'" inputStrList.append(elem) inputStr = ','.join(inputStrList) sql = f"UPDATE {table_name} SET {inputStr} WHERE jobid='{jobid}' AND runid={runid} AND pca_run_label='{run_label}'" conn = self.createConnection() cur = conn.cursor() cur.execute(sql) cur.close() conn.commit() conn.close() else: print("Inputed dictionary with no data, DB not updated") How to resolve this issue? I just need that it should populate each Record in the database. -
IntegrityError at /add_emp FOREIGN KEY constraint failed Django problem
while adding a user data in db through a form i create i got this error intergrityerror at \add_emp and it says foreign key constraint failed i tried delete dbsqlite3 files pycache files but that didnt work plzz tell where i am wrong its my first time getting this error. **This is Models.py code ** from django.db import models # Create your models here. class Department(models.Model): name = models.CharField(max_length=100,null=True) location = models.CharField(max_length=100) def __str__(self): return self.name class Role(models.Model): name = models.CharField(max_length=100, null=True) def __str__(self): return self.name class Employee(models.Model): first_name = models.CharField(max_length=100, null=False) last_name = models.CharField(max_length=100,null=True) dept = models.ForeignKey(Department, on_delete=models.CASCADE) salary = models.IntegerField(default=0,null=True) bonus = models.IntegerField(default=0,null=True) role = models.ForeignKey(Role, on_delete=models.CASCADE) phone = models.IntegerField(default=0,null=True) hire_date = models.DateField(null=True) def __str__(self): return "%s %s %s" %(self.first_name, self.last_name, self.phone) **Thats views.py code ** from django.shortcuts import render,HttpResponse from .models import* from datetime import datetime # Create your views here. def index (request): return render(request,"index.html") def all_emp (request): context={"emps":Employee.objects.all(),"roles":Role.objects.all(),"departments":Department.objects.all()} return render(request,"all_emp.html",context) def add_emp(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] salary = int(request.POST['salary']) bonus = int(request.POST['bonus']) phone = int(request.POST['phone']) dept = int(request.POST['dept']) role = int(request.POST['role']) new_emp = Employee(first_name= first_name, last_name=last_name, salary=salary, bonus=bonus, phone=phone, dept_id=dept,role_id=role,hire_date = datetime.now()) new_emp.save() return HttpResponse ("Employee added sucessfully") elif … -
Django register form validation for javascript
In django i followed form method is model form i not validate in backend only validate frontend using javascript but if click the submit button the data is not store to database how to fix I tried to submit the data in database but if I click data is validate but not store to database -
Forget Password using Email Django Send Email
I am working on the function of forgetting password then sending email to user to retrieve password using Django programming language. I have the following problem: When I run the server, it shows the link (1) and then I click send email, it shows the link (3) and I check the mail, it doesn't send an email forgot the password to the user even though the system says it has been sent successful email. Please help me. It took me 2 days to fix this function. I hope to be able to send forgotten password emails to users in Django. It took me a total of 2 days to work over and over again, but the result was that I couldn't do it. Very butt get help from everyone. I would like to thank all of you for helping me -
How to make Django Rest Framework Serializers to work different with GET and POST request
Actually, I have am creating the API for Bookmark manager, where I will be having CRUD operations on Bookmark, Collection and Tags Here I am using the BookmarkSerializer for serialization, class BookmarkSerializer(serializers.ModelSerializer): class Meta: model = Bookmark fields = "__all__" def create(self, validated_data): tags_data = validated_data.pop('tags', []) bookmark = Bookmark.objects.create(**validated_data) for tag_data in tags_data: bookmark.tags.add(tag_data) return bookmark and Bookmark model is like class Bookmark(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) url = models.URLField() thumbnail_url = models.URLField(blank=True, default="https://site.image.jpg") title = models.CharField(max_length=512, blank=True) description = models.TextField(blank=True) note = models.TextField(blank=True) tags = models.ManyToManyField("Tag", blank=True) is_favorite = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) collection = models.ForeignKey("Collection", on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.title My requirement is that, when GET request comes in I will return all information, and when POST request comes in I will create the new instance of Bookmark model. Here everything works well, but in the response the primary keys (id) of user, tags and collections are sent, which I don't want. I want it to be string representation. Like { "id": 1, "url": "https://www.flipkart.com/", "title": "Exiting website", "description": "", "note": "Shopping website", "is_favorite": false, "created_at": "2023-08-14T20:41:32.033584Z", "user": "john2000", "collection": "Shopping", "tags": [ "buy", "great_ui"] } but result's are, { "id": 1, "url": "https://www.flipkart.com/", "title": … -
ModelViewSet routes and methods
Following is my model view set for user model: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() def get_serializer_class(self): if self.action == 'list': serializer_class = UserSerializer elif self.action == 'update': serializer_class = UserEditSerializer else: serializer_class = UserRegisterSerializer return serializer_class def get_permissions(self): if self.action == 'list': permission_classes = [IsAuthenticated] elif self.action == 'update': permission_classes = [IsAuthenticated, isOwner] else: permission_classes = [] return [permission() for permission in permission_classes] Basically what i want is .create, .update, and .list methods from the model viewset for user Registration, Edit profile and get user list functionalities respectively. This is my urls.py router = SimpleRouter() router.register(r'users', views.UserViewSet, basename='user') urlpatterns = [ # path('register/', views.RegisterUser.as_view(), name='api-register'), path('login/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), # path('', views.UsersList.as_view(), name='api-home'), # path('users/<pk>/edit/', views.EditProfile.as_view(), name='api-edit'), path('', include(router.urls)), ] Im not sure what is going on because when i send GET request with user edit url api/users/ i can view any users information. Is there a way to avoid this? i want to view all users using api/users only. Not specific ones. -
I want to link tawk.to live chat feature to email
I am building a freelance django website for my client where he want to get orders from the visitors who visit the site, he want to chat with the visitors and communicate with them and throw them the offer, so he want to keep the chat history with the linked email, how can i do that with tawk.to live chat. i only tried the tawk.to live chat widget, i enclosed that in a condition that if the user is logged in then to show up and now i want that when the user will again visit the site he should be able to see his chat history. -
Attach listener to Azure Active Directory Microsoft login for Django
I'm writing an app using Django that uses exclusively MS login to authenticate users. I've followed the same structure as the sample code set up at their Django tutorial. https://github.com/Azure-Samples/ms-identity-python-django-tutorial/tree/main/1-Authentication/sign-in, where it uses some middleware and Django adapters provided by a seemingly undocumented and unused library they've created at https://github.com/Azure-Samples/ms-identity-python-samples-common/. I'm able to grab ID token claims from a request, but what I want to do is attach a listener to login to manipulate or add an entry in a database (regarding user information). I can't figure out a way to hook something to login. For reference, I created and am using a basic AAD tenant, and MS automatically redirects users after authentication to localhost/auth/redirect with some GET parameters like "code", "state", and "session state". -
django admin broken in development mode
I am a newbie in django (not in programming though) and following the w3school tutorials. When running the django admin at 127.0.0.1:8000/admin/ and in development mode, I end up with a layout problem which seems to be related to how the django css files are accessed. I have a clean and new django install. I have googled the problem and all that I have found are posts solving the same problem in production mode (not in development mode) or posts dated more than 10 years. Does anyone understand what is going on and how to fix the problem? -
Can I create a symbolic link inside Azure file share for a file in Azure file share?
I need some understanding and possibility on, how to create a symbolic link for a file present in Azure File share, inside another directory in the same file share. Is it possible? If yes, then please provide an insight on how to do the same using the Azure Python SDK or Azure Portal. PS: I looked into the NTFSAttributes class of Azure Python File share SDK. Is it possible to do it that way? Any guidance on the above would be appreciated. Thank you! -
CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. while debug is true
in the settings.py i use environs for my debug and in docker-compose.yml i set it to True my django is 4.2.4 and python 3.11.3 settings.py from pathlib import Path # from django.db.models import Q from environs import Env # # from accounts.models import CustomUser # Build paths inside the project like this: BASE_DIR / 'subdir'. env = Env() env.read_env() BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env('DJANGO_SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env.bool('DJANGO_DEBUG') ALLOWED_HOSTS = ['*'] docker-compose.yml version: '3.9' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db environment: - 'DJANGO_SECRET_KEY=...' - 'DJANGO_DEBUG=True' db: image: postgres:14 environment: - "POSTGRES_HOST_AUTH_METHOD=trust" but it says CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False i try asking chat gpt and its help and internet and in manage .py i import a file and in that i add django.setup and settings.configure after this i have this error -
Django model aggregate function returns different result in shell and in request endpoint
Django version: 4.2.4 Python version: 3.10.8 from django.shortcuts import render from django.db.models.aggregates import Max from .models.product import Product def product_page(request): agg = Product.objects.aaggregate(max__price=Max('price')) return render(request, 'product.html', {'max_price': agg['max__price']} I get following error when reading the result from agg : 'coroutine' object is not subscriptable But, when I run the same code in django shell I get the expected result in dict What am I missing here? -
How can I create a Django form out of a Model with an intermediary model? (I.E, a box with many products, as in, 10 products A, 5 products B)
First of all, the specifics of the project I'm working on are essentially the same as the example shown in this question, so I think it's easier to explain what I want to achieve using them. Background from the mentioned question: Think of a Box model that contains products, using an intermediary model, we can store not only multiple products but also different quantities of each product. Here is the code from the answer to the question mentioned above: class Box(models.Model): boxName = models.CharField(max_length=255, blank = False) product_set = models.ManyToManyField(ProductSet) def __str__(self): return self.boxName class ProductSet(models.Model): quantity = models.PositiveIntegerField() product = models.ForeignKey(Product, on_delete = models.PROTECT) class Product(models.Model): productName = models.CharField(max_length=200) productDescription = models.TextField(blank=True) productPrice = models.DecimalField(max_digits=9, decimal_places=0, default=0) class Meta: db_table = 'products' ordering = ['-productName'] def __str__(self): return self.productName This solution solves the model set up for what I want to achieve. In my specific case, the box model is a project model, and the products model is a materials model, essentially I want to store projects, which reference various materials required for said project, so each material will have different quantities. As a quick example: if there's a cake project, the materials can be 5 eggs and 1 … -
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