Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any benefit to using `URLValidator` on a django `URLField`
Is there any benefit to using URLValidator on a django URLField in models.py or does the URLField already do all the necessary validation? Also is it recommended to use it to enforce https? For example: from django.core.validators import URLValidator class Processor(models.Model): website = models.URLField( max_length=250, blank=True, null=True, validators=[URLValidator(schemes=['https'])] # Enforce HTTPS ) -
Dropdown works with Tailwind CDN but doesn't work with PostCSS
I am trying to integrate TailwindCSS with my Django project using PostCSS. Here are the configurations I’m using: PostCSS Configuration (postcss.config.js) module.exports = { plugins: { tailwindcss: {}, autoprefixer: {}, }, }; Tailwind Configuration (tailwind.config.js) /** @type {import('tailwindcss').Config} */ module.exports = { content: [ // Include all Django HTML and template files "./templates/**/*.html", // Templates at the project level "./**/templates/**/*.html", // Templates inside apps "./static/**/*.js", // JavaScript files in the static folder "./**/static/**/*.js", // JavaScript files in app-level static folders ], theme: { extend: { // Customizations for your design colors: { primary: "#1d4ed8", // Example custom color secondary: "#9333ea", }, fontFamily: { sans: ["Inter", "sans-serif"], // Example custom font }, }, }, plugins: [], }; Tailwind CSS File (static/css/tailwind.css) @tailwind base; @tailwind components; @tailwind utilities; 4. HTML Template Example (index.html) {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Add Task - TaskMaster</title> {% comment %} <link rel="stylesheet" href="{% static 'css/output.css' %}"> {% endcomment %} <script src="https://cdn.tailwindcss.com"></script> </head> <body class="font-sans bg-gray-100"> <!-- Content of the page --> <header class="bg-white shadow-md"> <nav class="container mx-auto px-6 py-3"> <div class="flex justify-between items-center"> <a href="index.html" class="text-xl font-bold text-gray-800">Taskify</a> <!-- Other navigation elements --> </div> </nav> </header> <main … -
Can I create a many to many relation using a junction table with a junction table
I want to create a m2m relation between two tables and one of the table is a junction table for m2m relation. So basically, I have 3 tables and 2 can be joined using a m2m. But in order to join three tables, I have two options, one is to create a m2m with the third table and the already created junction table and the other approach is to create a table which has foreign key of all the three tables. Which of the above approach is suitable. The two approaches to implement table with relation to three tables are: CREATE TABLE PromoPrizeScreen ( id SERIAL PRIMARY KEY, prize_cap INTEGER DEFAULT NULL, prize_used INTEGER DEFAULT NULL, promo_prize_id INTEGER NOT NULL, screen_id INTEGER NOT NULL, FOREIGN KEY (promo_prize_id) REFERENCES PromoPrize (id) ON DELETE CASCADE, FOREIGN KEY (screen_id) REFERENCES Screen (id) ON DELETE CASCADE ); CREATE TABLE PromoPrizeScreen2 ( id SERIAL PRIMARY KEY, prize_cap INTEGER DEFAULT NULL, prize_used INTEGER DEFAULT NULL, promo_id INTEGER NOT NULL, prize_id INTEGER NOT NULL, screen_id INTEGER NOT NULL, FOREIGN KEY (promo_id) REFERENCES Promo (id) ON DELETE CASCADE, FOREIGN KEY (prize_id) REFERENCES Prize (id) ON DELETE CASCADE, FOREIGN KEY (screen_id) REFERENCES Screen (id) ON DELETE CASCADE ); I … -
ERROR: Failed building wheel for psycopg2-binary
Using cached psycopg2-binary-2.9.10.tar.gz (385 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: psycopg2-binary Building wheel for psycopg2-binary (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [32 lines of output] running bdist_wheel running build running build_py creating build\lib.win-amd64-cpython-313\psycopg2 copying lib\errorcodes.py -> build\lib.win-amd64-cpython-313\psycopg2 copying lib\errors.py -> build\lib.win-amd64-cpython-313\psycopg2 copying lib\extensions.py -> build\lib.win-amd64-cpython-313\psycopg2 copying lib\extras.py -> build\lib.win-amd64-cpython-313\psycopg2 copying lib\pool.py -> build\lib.win-amd64-cpython-313\psycopg2 copying lib\sql.py -> build\lib.win-amd64-cpython-313\psycopg2 copying lib\tz.py -> build\lib.win-amd64-cpython-313\psycopg2 copying lib\_ipaddress.py -> build\lib.win-amd64-cpython-313\psycopg2 copying lib\_json.py -> build\lib.win-amd64-cpython-313\psycopg2 copying lib\_range.py -> build\lib.win-amd64-cpython-313\psycopg2 copying lib\__init__.py -> build\lib.win-amd64-cpython-313\psycopg2 running build_ext building 'psycopg2._psycopg' extension creating build\temp.win-amd64-cpython-313\Release\psycopg "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.42.34433\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD "-DPSYCOPG_VERSION=2.9.10 (dt dec pq3 ext lo64)" -DPSYCOPG_DEBUG=1 -DPG_VERSION_NUM=170002 -DHAVE_LO64=1 -DPSYCOPG_DEBUG=1 -IC:\Users\hello\memesite\myenv\include "-IC:\Program Files\Python313\include" "-IC:\Program Files\Python313\Include" -I. -IC:/PROGRA~1/POSTGR~1/17/include -IC:/PROGRA~1/POSTGR~1/17/include/server "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.42.34433\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\VS\include" /Tcpsycopg\adapter_asis.c /Fobuild\temp.win-amd64-cpython-313\Release\psycopg\adapter_asis.obj adapter_asis.c C:\Program Files\Python313\include\pyconfig.h(59): fatal error C1083: Cannot open include file: 'io.h': No such file or directory It appears you are missing some prerequisite to build the package from source. You may install a binary package by installing 'psycopg2-binary' from PyPI. If you want to install psycopg2 from source, please install the packages required for the build and … -
Django serializer depth doesn't serialize nested models
I use django and react and I want to make some workspaces where they have inside channel instances. Models.py class Workspace(models.Model): channels = models.ManyToManyField('Channel', related_name='channels', blank=True) Serializers.py class WorkspaceSerializer(serializers.ModelSerializer): class Meta: model = Workspace fields = '__all__' depth = 2 Views.py @api_view(['POST']) def getworkspace(request): if request.method == 'POST': workspace = Workspace.objects.filter(id=request.POST['id']).first() serializer = WorkspaceSerializer(workspace, many=False) return Response(serializer.data) Then I use axios to fetch the data axios.post('http://127.0.0.1:8000/getworkspace/', formData, {headers: {'Content-type': 'multipart/form-data'}}).then(res=>{ setWorkspace(res?.data) }) console.log(workspace) What I was expecting was for workspace channel to be serialized and me be able to access it but instead I get this {id, 1, channels: [1]} What can I do, I have changed the depth to even 10 but it still doesn't work. If I use shell and serialize it from there like this: from main.models import * from main.serializers import * workspace = Workspace.objects.filter(id=1).first() serializer = WorkspaceSerializer(workspace, many=False) print(serializer.data) It works perfectly. I believe the problem starts from the view because when I print print(serializer.data) from there channels isn't being serialized. -
Can't serve static files Django + Gunicorn + Nginx + Docker
I have the following structure on my project: -> api_solar_django --> manage.py --> api_app (where are the view.py model.py, etc) --> api_solar (where are settings.py, etc) In my docker-compose file I have the following: services: django: build: context: ./api_solar_django container_name: django-app restart: unless-stopped ports: - "8090:8090" volumes: - ./api_solar_django:/app - static_volume:/app/static environment: - DJANGO_SETTINGS_MODULE=api_solar.settings - ENC_KEY=key depends_on: - db networks: - app-network nginx: image: nginx:alpine container_name: nginx restart: unless-stopped ports: - "80:80" volumes: - ./nginx.conf:/etc/nginx/nginx.conf:ro - static_volume:/static depends_on: - django - frontend networks: - app-network networks: app-network: driver: bridge volumes: postgres_data: static_volume: The static files, inside each container is located as: Django container: /app folder, same as manage.py Nginx container: root folder My nginx.conf file is configured as: user nginx; worker_processes auto; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; # Incluindo o servidor configurado server { listen 80; # Serve arquivos estáticos do Django location /static/ { alias /static/; } # Proxy para o backend (Django) location /api/ { proxy_pass http://django-app:8090/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } # Proxy para o frontend (Vue.js) location / { proxy_pass http://vue-app:5173; proxy_set_header Host … -
How to pass UNICODE characters in a url?
I am attempting my first steps in web dev with Django. Can anybody help me modify somehow the paths so that <slug:slug> works for Unicode characters, not only ASCII? from django.urls import path from . import views urlpatterns = [ path('book/<slug:slug>/', views.view_book, name='book'), path('genres/', views.view_all_genres, name='genres'), path('genres/<slug:slug>/', views.preview_genre, name='preview_genre'), ] I tried to play around with some regex but still I couldn't solve my problem -
Django Field 'id' expected a number but got <django.db
Github of the "project": https://github.com/Doomsizer/why Django test project keeps crushing when I'm trying to add email functionalityerror I tried changing many things(in forms, models, html and views) in past couple days, nothing seems to work. I genuinely have no idea how to fix it. -
Django Rest Framework: validate_username and update methods not called during PUT request
I am working on a Django Rest Framework (DRF) project, where I need to validate a username field and handle custom update logic in a serializer. My model has a username field with unique=True. Here's the relevant setup: Model: from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): pass Serializer: class CustomUserSerializer(serializers.ModelSerializer): class Meta: model = models.CustomUser fields = ["id", "username", "first_name", "last_name"] read_only_field = ["id"] extra_kwargs = { "password": {"write_only": True}, } def validate_username(self, value): print('here.......') user_model = get_user_model() request = self.context.get('request') if request and request.method in ['PUT', 'PATCH']: if user_model.objects.filter(username=value).exclude(id=self.instance.id).exists(): raise serializers.ValidationError('User with this username already exists.') else: if user_model.objects.filter(username=value).exists(): raise serializers.ValidationError('User with this username already exists.') return value class CustomUserProfileSerializer(serializers.ModelSerializer): user = CustomUserSerializer() roles = ProfileRolesSerializer(many=True) department = DepartmentSerializer() gender = GenderSerializer() Views: class CustomUpdateView(APIView): def put(self, request, *args, **kwargs): serializer = CustomUserProfileSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) When I send a PUT request to update a user profile, the validate_username and update methods in the serializer are not executed. Instead, I get a response error: { "user": { "username": [ "User with this username already exists." ] } } I suspect that the default unique=True constraint on the username field is bypassing the serializer-level … -
How to pull up Django model data based on ALREADY filled out form fields for other ForeignKeys
I have a form in which there are several fields with foreign keys. For example, the table "Entrance" (3 entries -> 1st entrance, 2nd entrance, 3rd entrance), "Apartment" (30 entries, 10 for each entrance (No.1-10, No. 11-20 and No. 21-30), "Owner" (also 30 entries of surnames). In turn, the "Owner" has an external key to the apartment, and the "Apartment" has an external key to the entrance. here's the question, if I selected entrance No. 2 in the form, then in the other two fields (Apartment and Owner) I need to display ONLY related records (that is, apartments from 11 to 20 rooms, and the owners who live in these apartments) how to implement it??? here is the code in forms.py(naturally, it gives out an error, I just pointed out where, logically, I wanted to get involved.) ` id_entr = ModelChoiceField(queryset=Bs_entrance.objects.all(), widget=Select( attrs={'class': 'form-select', 'placeholder': 'выберите подъезд'})) id_apart = ModelChoiceField(queryset=Bs_entrance.objects.filter(id_entrance=**id_entr**), widget=Select( attrs={'class': 'form-select', 'placeholder': 'выберите квартиру'})) id_owner = ModelChoiceField(queryset=Bs_apartment.objects.filter(id_apartment=**id_apart**), widget=Select( attrs={'class': 'form-select', 'placeholder': 'выберите собственника'})) ` enter image description here Here is an example of the form (the example is not on apartments)There are all kinds of fault groups, although there should have been only two, since the ballast was … -
Can't get Cursor to work with Django linting
I have Python code in a Django project that says: x = models.DecimalField(max_digits=18, decimal_places=2, default='0.00') In Cursor, I get a Linter error from pylance: "No overloads for "__new__" match the provided argumentsPylancereportCallIssue" I have "python.analysis.django": true, in my settings.json, but it is greyed out. The code runs fine interactively, and when I run pylance from the terminal it doesn't flag this error. I have the django-stubs package installed in my venv. It seems like pylance in Cursor doesn't know about Django, and I can't figure out why. Any suggestions most appreciated! -
How to Efficiently Manage JWT Authentication (Refresh & Access Tokens) in React Without Repeated Server Calls and Implement a Centralized Alert System
I'm working on a React application that requires JWT authentication with both access and refresh tokens. I want to manage the authentication process in a way that prevents multiple requests for the refresh token and handles token expiration smoothly. Additionally, I want to centralize the alert system for handling success, error, and informational messages across the entire application. ** What I want to achieve:** JWT Authentication: Proper handling of access and refresh tokens in the React app. When the access token expires, I want to refresh it using the refresh token, but without making repeated server requests or causing race conditions. Automatically retry the original request after refreshing the access token. Centralized Alert System: I need an alert system that can handle and display error messages from API responses (both nested and non-nested). The alert system should be available globally across all components. Alerts should be dynamically triggered based on different responses (error, success, etc.). Problem: I use the Djoser for backend handling and react for frontend handling I’m confused about how to manage the refresh token mechanism without making repeated calls to the server or causing race conditions. I’m also trying to implement a centralized alert system that works … -
Update a field of a Django Model class from another class linked through a OneToOne Relationship
I'm on Django 5.0.4. I'm building an API using DRF. I'm new to DRF. I have 2 django models which looks like this : class PostVideo(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='videos', null=True) width = models.PositiveIntegerField(editable=False, null=True) height = models.PositiveIntegerField(editable=False, null=True) duration = models.FloatField(editable=False, null=True) file = VideoField(width_field='width', height_field='height', duration_field='duration', storage=post_image_storage, upload_to=upload_to_post_video_directory, blank=False, null=True) video_type = (('regularvideo', 'regularvideo'),('gridvideo', 'gridvideo'),('livevideostream', 'livevideostream')) mediaviewtype = models.CharField(max_length=24, choices=video_type, default='') class LiveVideoStream(models.Model): parent = models.OneToOneField(Post, related_name='live_video_stream', blank=False, null=True,on_delete=models.CASCADE) stream_uuid = models.CharField(_('uuid'), null=False, editable=False, unique=False, max_length=settings.LIVE_VIDEO_STREAM_UUID_MAX_LENGTH) streamer = models.ForeignKey(User, related_name='live_video_streams', on_delete=models.CASCADE) started_at = models.DateTimeField( default=timezone.now, blank=False, editable=False,null=False) video = models.OneToOneField(PostVideo, related_name='live_video_stream', blank=False, null=True,on_delete=models.CASCADE) def create_live_video_stream_post(cls, parent, stream_uuid, streamer,started_at): return cls.objects.create(parent=parent,stream_uuid=stream_uuid,streamer=streamer, started_at=started_at) My objective is to update the mediaviewtype in the PostVideo class with the value ‘livevideostream’ when i create a PUT request to create a Live Video Stream Post using the create_live_stream_post method above. I’m not sure how to do it.I get the value of mediaviewtype which is 'livevideostream' from my frontend flutter app and I process it via a Serializer, but I get stuck when I think how to update the value of mediaviewtype in model PostVideo.* The view to create a live stream post : def put(self, request): query_params = request.data.dict() serializer = LiveVideoStreamRequestSerializer(data=query_params) serializer.is_valid(raise_exception=True) … -
Real time vechile tracking using django channels and react
I want to implement real time tracking for vehicles but I don't know most of my things are not working. I use the geolocation API to get current device location and send those locations(latitude, longitude) to backend every five seconds. Then using django channels and Daphne I implement routing APIs I will use in react with the websockets but things take a delay to respond. I was requesting for yhe way I can design the database efficiently and the way I can handle the websocket connections I tried to create the real time tracking using leaflet maps so that I can see the image move smoothly on the map but it just jumps or let me say it doesn't work as expected -
Facing configuration problem with the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?
connection to server at "127.0.0.1", port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? Request Method: Django Version: 3.2.4 Exception Type: OperationalError Exception Value: connection to server at "127.0.0.1", port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? Exception Location: /home/ebong/djangoproject/djangoprojectenv/lib/python3.10/site-packages/psycopg2/init.py, line 122, in connect Python Executable: /home/ebong/djangoproject/djangoprojectenv/bin/python Python Version: 3.10.12 Python Path: ['/home/ebong/djangoproject/smsdigo', '/home/ebong/djangoproject/djangoprojectenv/bin', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/ebong/djangoproject/djangoprojectenv/lib/python3.10/site-packages'] Server time: Wed, 25 Dec 2024 04:11:09 +0000 This happens when a user tries to login into the website. The website is hosted by digital ocean droplet on django, gunicorn, nginx and postgres. For some reasons, I had reported server, then this problem occured. I have tried the following below. Restarted my postgresql using sudo systemctl restart postgresql I have done changes in postgresql.conf and pg_hba.conf postgresql.conf file below listen_addresses = '*' data_directory = '/var/lib/postgresql/14/main' # use data in another directory # (change requires restart) hba_file = '/etc/postgresql/14/main/pg_hba.conf' # host-based authentication file # (change requires restart) ident_file = '/etc/postgresql/14/main/pg_ident.conf' # ident configuration file # (change requires restart) # If external_pid_file is not explicitly set, no extra PID file is written. external_pid_file = '/var/run/postgresql/14-main.pid' # write an extra … -
Microservice with django
i tried turning an old project to see if i make it work as microservices it is a chat application i separated them into two auth service(which handles registration, login, contacts and emails) chat service (which handles chatting with contacts) the auth service works perfectly but i am having issues in the chat service first let me send the models class Message(models.Model): sender_id = models.IntegerField() # Store user IDs instead of foreign keys receiver_id = models.IntegerField() message = models.TextField() timestamp = models.DateTimeField(default=timezone.now) is_read = models.BooleanField(default=False) def __str__(self): return f"Message from {self.sender_id} to {self.receiver_id} at {self.timestamp}" since i cannot reference foreign key i am using integerfield i also made a custom middleware that verifies the token entered when th chat endpoint is called class SimpleUser: def __init__(self, user_id, email, full_name, is_active): self.id = user_id self.email = email self.full_name = full_name self.is_active = is_active @property def is_authenticated(self): return True @property def is_anonymous(self): return False def __str__(self): return f"{self.full_name} ({self.email})" class AuthenticateJWTMiddleware: AUTH_SERVICE_URL = "http://127.0.0.1:8800/api/auth/verify_token/" def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.path.startswith('/admin/'): return self.get_response(request) self.process_request(request) response = self.get_response(request) return response def process_request(self, request): print(f"Middleware Processing: Path={request.path}") token = self.get_token_from_headers(request) if not token: print("No Authorization token found.") request.user = AnonymousUser() … -
How Connect Tkinter With django using zerorpc?
i have tkinter app want connect and send data to django project using zerorpc on local host its work nice but after deploy django on ubuntu server with gunicorn & nginx and open port 4242 on ufw still dosen't work. when i check gunicorn status i get error on: Exception in thread Thread-l (verificate): Traceback (most recent call last): File'/usr/lib/python3.12/threading.py',line 1075, in _bootstrap_inner self.run() File'/usr/lib/python3.12/threading.py',line 1012, in run self._target(*self._agrs, **self._kwargs) File '_zmq',line 732, in zmq.backend.cython._zmq.Socket.set TypeError: set() takes exactly 2 positional arguments (3 given) i bind django gunicorn and nginx pass proxy on address: 0.0.0.0:8000 i try also bind django gunicorn and nginx pass proxy on address: 127.0.0.1:8000 i use zerorpc python module on python tkinter and django app tkinter client connect django using zerorpc on address: connect('tcp://serverip:4242') django has function to listen on port 4242 but i use thread module to run this function with django views in sametime. i open port 8000 and 4242 and 80 and 443 and tcp and nginx full -
ClientException: XMLHttpRequest error. Flutter WEB
I get this error in my app. and once i get this error, even though im catching it. it stops all my api requests to my back end django server from working steps to reproduce: i call an api to my django rest framework back end. works fine. i shut off my back end server ( to simulate an outage) api call from my flutter web app is then again made to a server that is not online a ClientException: XMLHttpRequest error. is thrown. which is caught. i turn my server back on. and then no further api calls are made to the back end. Is there any way around this in flutter web? (without disabling web security) -
DuckDB, Django and apache2 Permission Denied in production
I have a problem with my duckdb database, that I really don't seem to understand. After I created a .db database and put it in the apache2/Django webapp root and gave www-data access to it and its directory, I still get permission denied. Here's the weird part(s): I don't get the permission error when I establish the connection, I only get it in the fetchdf() part. con = duckdb(database='path/to/db.db',read_only=True) P = con.execute('SELECT * FROM products LIMIT 1;') p = p.fetchdf() # Here's where the error gets thrown ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ duckdb.duckdb.IOException: IO Error: Permission denied When I run the same python code with the www-data, everything works nice. Also in the runserver situation it works without a problem. It seems that the issue is related the production environment. I suspect that duckdb wants access to a certain directory or file that I have to make available in the apache2 config, but me and AI didn't know what or where. Any help? I tried changing the temp_directory, home_directory, extension_directory, and secret_directory to a directory within the webapp root directory. I tried moving the db file to a different dir and gave apache permission to it also in the .conf. -
Can't create second celery queue
I want to create two celery queues (for different types of tasks) My celery configuration. I expect that this config creates two queues 'celery' and 'celery:1' # celery.py import os from celery import Celery from core_app.settings import INSTALLED_APPS # this code copied from manage.py # set the default Django settings module for the 'celery' app. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core_app.settings') app = Celery("my_app") # To start scheduling tasks based on priorities # you need to configure queue_order_strategy transport option. app.conf.broker_transport_options = { 'queue_order_strategy': 'priority', } # ['celery', 'celery:1',] - two queues, the highest priority queue will be named celery app.conf.broker_transport_options = { 'priority_steps': list(range(2)), 'sep': ':', 'queue_order_strategy': 'priority', } # read config from Django settings, the CELERY namespace would make celery # config keys has `CELERY` prefix app.config_from_object('django.conf:settings', namespace='CELERY') # load tasks.py in django apps app.autodiscover_tasks(lambda: INSTALLED_APPS) I am defining and running celery task like this: @shared_task(queue="celery", soft_time_limit=600, time_limit=650) def check_priority_urls(parsing_result_ids: List[int]): check_urls(parsing_result_ids) @shared_task(queue="celery:1", soft_time_limit=600, time_limit=650) def check_common_urls(parsing_result_ids: List[int]): check_urls(parsing_result_ids) # running task check_priority_urls.delay(parsing_results_ids) But I see only one queue celery -A core_app inspect active_queues -> celery@d1a287d1d3b1: OK * {'name': 'celery', 'exchange': {'name': 'celery', 'type': 'direct', 'arguments': None, 'durable': True, 'passive': False, 'auto_delete': False, 'delivery_mode': None, 'no_declare': False}, 'routing_key': 'celery', 'queue_arguments': None, 'binding_arguments': … -
Django model migration from standard model to multi-table inherited model with FK relations
I have a task to migrate some existing models to multi-table inherited models (make them subclass of existing parent). I'm testing my code on local machine and I've managed to enforce multi-table inheritance without faults. However some models are ForeignKeys linked to another models and I'm wondering how to manage such relations swap to avoid data lose. Example: class Member(models.Model): pass class Person_A(models.Model): member_ptr = OneToOneField(parent_link=True) class Person_B(models.Model): member_ptr = OneToOneField(parent_link=True) class Group(models.Model): person_a = models.ForeingKey(Person_A) person_b = models.ForeignKey(Person_B) So, Person_A and Person_B are on their way to be inherited from Member. All Member instances created and data prepopulated. Remains last step to remove _ptr field replacing models.Model with Member at the same time which causes drop of id field so ForeignKey link will be broken. Is there an easy way to manage this ForeignKey transfer without data lose? I have some weird ideas of field duplications etc. but hoping there is some more convinient way. -
how to know which field(category) most used
have query like this Product.objects.filter( title__icontains=self.query, # something to get most used category id ).values('id', 'is_featured').order_by('-is_featured', 'rank', '-created') what I want is. With one query can I get most used category id and above result. Note: order by should not be changed. is that possible?. this is my model looks like class Product(BaseModel): category = models.ForeignKey( 'tag_map.Category', on_delete=models.PROTECT, blank=False, null=False, verbose_name=_("Category of product"), ) class Category(BaseClassification): name_uz = models.CharField(max_length=200) name_ru = models.CharField(max_length=200) slug = models.SlugField(max_length=220, unique=True) rate = models.PositiveIntegerField() position = models.PositiveIntegerField() parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) -
how to create a form using multiple models in django?
So I am trying to make a student result management project.Where I can add students subhect grade and exam result.In the project i need to make a form where i can add marks of a subject to all the students of a grade(Class) at once.I want the look like the photo.Example Example . I tried to create individual form for every sector and try to combaine them.But it didn't work.Now I need to know how can I make a form using many models in django [Sorry for my Bad English ] -
Django Rest Framework - Nested Serializer Attribute error in response
wondering if someone could help me with the following problem. I have a serialises such as this: class LineupPlayerSerializer(serializers.ModelSerializer): id = serializers.UUIDField(write_only=True) name = serializers.CharField(read_only=True) positionType = serializers.CharField(read_only=True) alternativePositions = serializers.CharField(read_only=True, required=False, allow_blank=True) shirtNumber = serializers.IntegerField(read_only=True, required=False, allow_null=True) positionOnPitch = serializers.IntegerField(required=True) class Meta: model = LineupPlayer fields = ['id', 'positionType', 'alternativePositions', 'name', 'shirtNumber', 'positionOnPitch'] def create(self, validated_data): player_id = validated_data.pop('id') player = Player.objects.get(id=player_id) position_on_pitch = validated_data.pop('positionOnPitch') lineup = validated_data.pop('lineup') lineup_player = LineupPlayer.objects.create(lineup=lineup, player=player, positionOnPitch=position_on_pitch) return lineup_player class LineupSerializer(serializers.ModelSerializer): players = LineupPlayerSerializer(many=True) class Meta: model = Lineup fields = ['id', 'formation', 'players'] def create(self, validated_data): try: players_data = validated_data.pop('players') lineup = Lineup.objects.create(**validated_data) for player_data in players_data: player_data['lineup'] = lineup LineupPlayerSerializer().create(player_data) return lineup except Exception as e: print(f"Error: {e}") raise e However, when I send the request I get an Attribute error: Got AttributeError when attempting to get a value for field `positionOnPitch` on serializer `LineupPlayerReadSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Player` instance. Original exception text was: 'Player' object has no attribute 'positionOnPitch'. For some reason Django thinks that the positionOnPitch is in the Player model and I can't figure out how. When I use write_only=True for positionOnPitch it sends the … -
Efficient way to get relationship data
I have a Modal ABC and a field named GROUP which is a foreign key, and this model Abc is also used as a foreign key in another model XYZ. My requirement is that when I view the list of XYZ with filters such as (whse="01" and abc="02") I want to get the name of the group(from model abc) along with the list data of the XYZ model. class ABC(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) class XYZ(models.Model): abc = models.ForeignKey(ABC, on_delete=models.CASCADE) whse = models.ForeignKey(WHSE, on_delete=models.CASCADE) qty = models.CharField() What I do right now is - in serializer I define a SerializerMethodField() fields. here is the code - class XYZSerializer(serializers.ModelSerializer): groupName = serializers.SerializerMethodField() def get_groupName(self, instance): return instance.abc.group.name if instance.abc else '' class Meta: model = ZYX fields = '__all__' I get my desired result but you can see that my filter requirement is always (whse="01" and abc="02") on the XYZ model and so the value of get_groupName is always going to remain the same for each of my requests (my abc is always the same in the output list, so will be the group name). How can I format my data, serializer to reduce the database query, (to find groupName) for …