Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I cannot authenticate user with the jwt token in my django project
I'm trying to authenticate a user with jwt token generated in the login view, while copying the jwt token and adding it into the headers for authorization it says: { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] } class loginapi(APIView): def post(self, request): try: data = request.data serializer = LoginSerializer(data=data) if serializer.is_valid(): email = request.data['email'] password = request.data['password'] user = CUser.objects.filter(email=email).first() #check for user. if user is None: return Response({ 'status':400, 'message':'User not found', 'data': {} }) if not user.check_password(password): return Response({ 'status':400, 'message':'Wrong password', 'date': {} }) payload = { 'id': user.id, 'exp': timezone.now() + datetime.timedelta(minutes=60), 'iat': timezone.now() } token = jwt.encode(payload, 'secret', algorithm='HS256') #token_string = token.decode('utf-8') response = Response() response.set_cookie(key='jwt', value=token, httponly=True) response.data = { 'jwt':token } return response return Response({ 'status':400, 'message':'Something went wrong', 'date': serializer.errors }) except Exception as e: return Response({'message': str(e)}, status=400) class userapi(APIView): def get(self, request): token = request.COOKIES.get('jwt') if not token: raise AuthenticationFailed('Unauthenticated') try: payload = jwt.decode(token, 'secret', algorithms=\['HS256'\]) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Unauthenticated') user = CUser.objects.filter(id=payload\['id'\]).first() serializer = UserSerializer(user) return Response(serializer.data) these are my login and user views -
Publish messages to MQTT using Celery-Beat scheduled tasks
I am developing a Django+Vue web application along with an MQTT server. I want to implement Celery Beat to execute scheduled tasks, which I define in the "calendarios" models where I input the tasks according to the date, interval, repetition, and others. In "eventosCalendarios," I save each task with the time and date to execute. What I aim for is that upon executing each task, I can publish to a specific topic on the MQTT server. Models.py class calendarios(models.Model): nombre=models.CharField(max_length= 100, verbose_name='Nombre', unique=True) acciones=models.ForeignKey(acciones, null=True,blank=True,on_delete=models.CASCADE,verbose_name='Acciones') fecha_inicio = models.DateField(null=True, blank=True) fecha_fin = models.DateField(null=True, blank=True) repeticion= models.CharField(max_length=1, choices=repeticionChoices, default='D') # Ej: 'diaria', 'semanal', 'mensual' intervalo = models.IntegerField(null=True, blank=True) # Número de días, semanas o meses dependiendo de la repeticion todoCultivo= models.CharField(max_length=1, choices=SioNO, default='S') hora_repeticion_1 = models.TimeField(null=True, blank=True) # Hora de la primera repetición diaria hora_repeticion_2 = models.TimeField(null=True, blank=True) # Hora de la segunda repetición diaria hora_repeticion_3 = models.TimeField(null=True, blank=True) cultivo=models.ManyToManyField(cultivo, verbose_name="Cultivos",blank=True) plantas=models.ManyToManyField(plantas, verbose_name="Plantas",blank=True) def __str__(self): return self.nombre class Meta: verbose_name = 'Calendario' verbose_name_plural = 'Calendarios' db_table = 'calendarios' ordering = ['id'] class eventosCalendarios(models.Model): title = models.CharField(max_length=100) start = models.DateTimeField() calendario = models.ForeignKey(calendarios, on_delete=models.CASCADE) allDay = models.BooleanField(default=False) def __str__(self): return self.title class Meta: verbose_name = 'Evento calendario' verbose_name_plural = 'Eventos calendarios' db_table = … -
getting rank of specific user with windows function in djago
this is my query which gives me the ranking of all user: rank = Wallet.objects.filter(type=0, space_id=space.id).annotate( rank=Window( expression=DenseRank(), order_by=F('point_amount').desc(), ) ).order_by('rank').values("user__id","user__username","rank") but how can i get rank of specific user in this query?(i don't want to handle this whit python) i already try this: rank = Wallet.objects.filter(type=0, space_id=space.id, user_id=user.id).annotate( rank=Window( expression=DenseRank(), order_by=F('point_amount').desc(), ) ).order_by('rank').values("user__id","user__username","rank") but it gives me rank 1 which is not correct note: this raw query gives me the right answer but i don't konw how to convert this in to django orm query query = f''' SELECT FIND_IN_SET( `transaction_wallet`.`point_amount`, ( SELECT GROUP_CONCAT(`transaction_wallet`.`point_amount` ORDER BY `transaction_wallet`.`point_amount` DESC) FROM `transaction_wallet` WHERE `transaction_wallet`.`type` = 0 AND `transaction_wallet`.`space_id` = {space.id} ) ) AS `rank` FROM `transaction_wallet` WHERE `transaction_wallet`.`type` = 0 AND `transaction_wallet`.`space_id` = {space.id} AND `transaction_wallet`.`user_id` = {self.id}; ''' ``` -
KeyError in Django 'id_user'
Here, i have to take a user id from the url and use it to search for the user in the Profile model and return it , but when username = self.kwargs['id_user'] runs, it gives the KeyError VIEWS class SearchUser(generics.ListAPIView): serializer_class = ProfileSerializer queryset = Profile.objects.all() def list(self, request, *args, **kwargs): username = self.kwargs.get['id_user'] logged_in_user = self.request.user users = Profile.objects.filter(Q(user__username__icontains=username)) if not users.exists(): return Response( {"detail": "No users found."}, status=status.HTTP_404_NOT_FOUND ) serializer = self.get_serializer(users, many=True) return Response(serializer.data) SEERIALIZER class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields=['id','user', 'id_user', 'department', 'degree', 'year', 'bio','profileimg'] MODELS class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField() department= models.CharField(max_length=50,blank=True) degree= models.CharField(max_length=20,blank=True) year= models.CharField(max_length=20,blank=True) bio = models.TextField(blank=True) profileimg= models.TextField(blank=True) def __str__(self): return self.user.username URLS path("search/<username>/", views.SearchUser.as_view()) -
How reset Django DB? (ValueError: The field <field> was declared with a lazy reference to <app.model>, but app <app> doesn't provide model <model>.)
The Problem I'm using Django and I was having the error after attempting manual fixes on the migrations folder.: ValueError: The field API_Materials.ModelParams.material_param was declared with a lazy reference to 'API_Materials.materialparams', but app 'API_Materials' doesn't provide model 'materialparams'. The structure in models.py for those two classes cited in the error mensage ("MaterialParams", and "ModelParams") is: class MaterialParams(models.Model): material = models.ForeignKey(Material, models.CASCADE, related_name='params') name = models.CharField(max_length=50) submitted_by = models.ForeignKey(User, models.SET_NULL, null=True, related_name='material_params') class ModelParams(models.Model): model = models.ForeignKey(Model, models.CASCADE, related_name='params') material_param = models.ForeignKey(MaterialParams, models.CASCADE, related_name='model_params') submitted_by = models.ForeignKey(User, models.SET_NULL, null=True, related_name='params') params = models.JSONField() # {"x": 10, "z": 40, "output_do_outro" : 30} // {"input": [12, 1, 3.4], "output":} class Meta: constraints = [ models.UniqueConstraint(fields=['model', 'material_param'], name='unique_model_params') ] Attempts As usual with migrations, I tried to comment those classes, create a makemigrations, and then uncomment, but it didn't work. I also attempted to comment the "material_param" with the constraints in "ModelParams", but with the same result. Looking for similar questions in Stack Overflow, usually they were related to the User or by the lack of "Model.models" heritance. Later I deleted the "ModelParams" table in the DB Server to attempt to remove this error, but without positive results. At some point, I tried to … -
How can i filter by many-to-many field in other table Django ORM?
My models: class Job: id = models.UUIDField() name = models.CharField() category = models.UUIDField() class JobReviewers: user_id = models.UUIDField() name = models.CharField() categories = models.ManyToManyField(Category, related_name='reviewers') class Category: id = models.UUIDField() I want to filter all job's where user is reviewer for job with name and category user_id = uuid.uuid4() all_jobs = Job.objects.all() jobs_where_user_is_reviewer = ... If it'll be filter just by name without category i can write this: job_names_where_user_reviewer = JobReviewers.objects.filter(user_id=user_id).values('name', flat=True) jobs_where_user_is_reviewer = all_jobs.filter(name__in=job_names_where_user_reviewer) How can i do this with categories m2m field? -
Error connecting gitlab ci pipeline to redis service
I have been having issues connecting my redis to my gitlab ci to run some tests I keep getting this error Error -2 connecting to redis:6379. Name does not resolve This is my docker-compose.yml section for redis redis: image: "redis:alpine" and this is my .gitlab.ci file image: docker:19.03.5 services: - docker:19.03.5-dind - redis:latest stages: - Build - Push variables: APK_CACHE: "/etc/cache/apk" REDIS_PORT: 6379 REDIS_HOST: redis REDIS_URL: redis://redis:6379 before_script: - apk add python3 - apk add --update docker-compose - docker-compose run --rm app sh -c "python manage.py migrate && python manage.py test --parallel" Build: stage: Build before_script: [] script: - mkdir data/ - docker build --compress -t ecr_image . - docker save --output data/image.tar ecr_image artifacts: name: image paths: - data/ -
Django test TypeError: Field 'id' expected a number but got ()
I got this error 3 times in my code. I searched on other question and I didn't find anything that worked. Does anyone have any idea? Thank you. models.py class Exam(models.Model): code = models.CharField(max_length=50) name = models.CharField(max_length=100) semester = models.IntegerField(default=1) year = models.CharField(max_length=9) users = models.ManyToManyField(User, blank=True) test_models.py class ExamModelTestCase(TestCase): def setUp(self): self.user = User.objects.create(username='test_user', first_name='Test', last_name='User') self.exam = Exam.objects.create(code="EXAM1", name="Exam 1", semester=1, year="2024") error Found 12 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). .....EEEEEE. ====================================================================== ERROR: test_exam_str_method (examc_app.tests.test_models.ExamModelTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/lucile/examreview/venv/lib/python3.10/site-packages/django/db/models/fields/__init__.py", line 2053, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a real number, not 'tuple' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/lucile/examreview/examc_app/tests/test_models.py", line 9, in setUp self.exam = Exam.objects.create(id="1", code="EXAM1", name="Exam 1", semester=1, year="2024") TypeError: Field 'id' expected a number but got (). -
antd Global color setting
I am new to antd and need to set the global theme to one of the antd colour palettes. I am building an app using Django, React and antd. I have installed the colours package: npm install @ant-design/colors --save Then I added the palette to my Layout.js file, my default layout: import { purple } from '@ant-design/colors'; Which shows up in the console console.log(purple); console.log(purple.primary); I am struggling with how to make this override the default colours and display the purple ones. I have tried to include in the theme: const theme = { primary: purple[5] }; I have also tried to add to the token: const { token: { purple, colorBgContainer, borderRadiusLG }, } = theme.useToken(); -
Unable to migrate in Second Multi database in Django
I have implemented multi-DB concept inside my Django project where for whole project i am using default db and for User I am using separate DB here are the settings.py file configs: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': default_db, 'USER': env('DB_USER'), 'PASSWORD': env('DB_PASSWORD'), 'HOST': env('DB_HOST'), 'PORT': env('DB_PORT'), }, 'auth_db': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'user_auth_db', 'USER': env('DB_USER'), 'PASSWORD': env('DB_PASSWORD'), 'HOST': env('DB_HOST'), 'PORT': env('DB_PORT'), }, } # ADDING ROUTE TO SPECIFY DB ROUTING SPECIFIC user RELATED CHANGES TO REFLECT Into auth_db database not inside default db DATABASE_ROUTERS = ["main_Project_directory.db_routers.UserAuthRouter"] Now this is the db_routers.py file class UserAuthRouter: """ A router to control all database operations on models in the auth and contenttypes applications. """ route_app_labels = {"auth_user", 'contenttypes'} # Apps to be include inside auth_db def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return "auth_db" return None def db_for_write(self, model, **hints): """ Attempts to write auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return "auth_db" return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the auth or contenttypes apps is involved. """ if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label … -
In Django the error is, TypeError at /Hod/Student/Add 'Course' object is not iterable
(https://i.stack.imgur.com/1qBDd.png) Even if I change the course = Course.objects.get(id = course_id) to course = Course.objects.filter(id = course_id) there seems no error thrown but the message does not get printed that 'Student added successfully'. **Hod_views.py** Even if I change the course = Course.objects.get(id = course_id) to course = Course.objects.filter(id = course_id) there seems no error thrown but the message does not get printed that 'Student added successfully'. from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from app.models import Course, Session_Year, CustomUser, Student from django.contrib import messages @login_required(login_url="/") def HOME(request): return render(request, "Hod/home.html") @login_required(login_url="/") def ADD_STUDENT(request): course = Course.objects.all() session_year = Session_Year.objects.all() if request.method == "POST": profile_pic = request.FILES.get('profile_pic') first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') email = request.POST.get('email') username = request.POST.get('username') password = request.POST.get('password') address = request.POST.get('address') gender = request.POST.get('gender') course_id = request.POST.get('course_id') session_year_id = request.POST.get('session_year_id') if CustomUser.objects.filter(email=email).exists(): messages.warning(request, "Email Is Already Taken!") return redirect('add_student') if CustomUser.objects.filter(username=username).exists(): messages.warning(request, "Username Is Already Taken!") return redirect('add_student') else: user = CustomUser( first_name = first_name, last_name = last_name, username = username, email = email, profile_pic = profile_pic, user_type = 3 ) user.set_password = password user.save() course = Course.objects.get(id = course_id) session_year = Session_Year.objects.get(id = session_year_id) student = Student( admin = user, address = address, session_year_id … -
I am facing problem in connection pgbouncer with postgresql in django
for the configuration of pgbouncer with postgresql in pgbouncer.ini file i have done mydb= dbname=mydb host=**.**.**.** port=5432 listen_addr = * listen_port = 6432 unix_socket_dir = /var/run/postgresql then in userlist.txt file i have "usr" "pass" then in django settings.py `DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydb', #its db name 'USER':'usr', #it's my user name of database 'PASSWORD': 'pass', #it's my password of database 'HOST': 'localhost', #it's my host of database } }` but when i started gunicorn server then in status it is giving me an error that Mar 20 07:35:27 testenv gunicorn[288076]: FATAL: password authentication failed for user "usr" I tried to configure pgbouncer with postgresql to solve the problem of max_connection_pooling but it is constantly giving the same error when i'm tried to start the gunicorn server. I'm expecting to solve django.db.utils.OperationalError: FATAL: remaining connection slots are reserved for non-replication superuser connections -
I want to update the price for a product on Stripe
When a subscription plan is created in DB, it is synced to create a corresponding product and price on stripe. However, now i want to change the price of a plan. How would I go about changing it on stripe? I have read that we can create a new price and make the old one inactive, but how would we link the new price to the product? And what about existing users? Is it easier done using the dashboard? -
Django, Docker, SlickGrid - Can't walk dependency graph: Cannot find module 'slickgrid'
I'm trying to build Django backend based application on Docker using PyCharm with NPM and slickgrid. When in some .js file trying to import slickgrid: import { SlickGrid, SlickDataView } from 'slickgrid'; I'm getting Django error: FilterError at /todo/ Error: Can't walk dependency graph: Cannot find module 'slickgrid' from '/opt/project/eTools/todo/static/todo/js/main.js' For dealing with Django static assets I use: django-compressor django-compressor-toolkit In Dockerfile I have something like: ` Set work directory WORKDIR /code (...) RUN apt-get install -y nodejs npm (...) #Slickgrid RUN npm install -g browserify babelify@8 babel-core babel-preset-env babel-cli babel-preset-es2015 RUN npm install -g slickgrid (...) Copy the Django project COPY ./eTools/ /code/ ` It looks like npm used indirectly by Django does not see 'slickgrid'. In bash for Docker I see following: a) in location where app was copied in last step of Dockerfile (/code/ location) npm has slickgrid: root@f7401a6daac5:/code# npm list slickgrid code@ /code └── slickgrid@5.8.2 b) but for unknown reason (for me at least ;)) npm seems to be called from location from exception ('/opt/project/'). checked in docker bash and there is no 'slickgrid': root@f7401a6daac5:/opt/project# npm list slickgrid eTools_root@1.0.0 /opt/project └── (empty) Could you please advice how I can fix this issue? And why code is … -
Flask TypeError: __init__() got an unexpected keyword argument 'as_tuple'
While I am testing my API I recently started to get the error below. if request is None: > builder = EnvironBuilder(*args, **kwargs) E TypeError: EnvironBuilder.__init__() got an unexpected keyword argument 'as_tuple' Code: @pytest.fixture(autouse=True) def client(): app = my_app() with app.test_client() as client: yield client def test_new_func(client, monkeypatch): monkeypatch.setattr(UnitPricing, 'find_unit_price', find_unit_pricing) monkeypatch.setattr(FullPricing, 'find_full_price', find_full_pricing) response = client.post("/price/calc", json=input_payload) assert response.status_code == 200 assert json.loads(response.data) == output_data In one of the solutions, it was suggested to pin werkzeug version to 2.0.3 and my requirement.txt file is meeting this condition but I'm still getting the error. TypeError: __init__() got an unexpected keyword argument 'as_tuple' Any help would be appreciated. -
Django unit test returning empty response for method of class
I am testing a class that connects to the database, and does some other stuff. Right now I am testing the returned value from a method. But it is returning empty list. class BaseAPISyncTestCase(unittest.TestCase): # overriding variables that are required by the test class @override_settings(DAILY_SYNC_BASE_URL='') @override_settings(DAILY_SYNC_SECRET_APP_KEY='') @override_settings(DAILY_SYNC_APP_NAME='') def test_retrieve_data_success(self): """Tests successful retrieval of data, validation, and sync history creation.""" mock_response = [ {'Id': 1, 'SyncDate': '2024-03-20', 'SyncType': 'UPDATE'}, {'Id': 2, 'SyncDate': '2024-03-20', 'SyncType': 'INSERT'}, ] with patch.object(BaseAPISync, 'retrieve_data', return_value=mock_response) as mock_retrieve_data: class TestSync(BaseAPISync): serializer_class = Mock() serializer_class.return_value.is_valid.return_value = True endpoint_key = 'test_endpoint' sync_category = 'Test Category' bulk_create_records = Mock() bulk_update_records = Mock() prepare_data_to_save = Mock() updatable_fields = Mock() sync = TestSync() sync.retrieve_data() self.assertEqual(mock_retrieve_data.call_count, 1) self.assertEqual(sync.last_retrieved_record, 2) # Last record ID self.assertEqual(len(sync.sync_context['validated_data']), 2) self.assertEqual(len(sync.sync_context['sync_history_dict']), 2) How can I debug this code, the retrive_data method is not being called because I checked by writing print statement. -
citus add node --> "fe_sendauth: no password supplied" error
I am trying to setup multi node schema based sharding for postgresql database using citus extension. I have two azure virtual machines , one is working as worker node('20.40.43.246') and other as coordinator ('20.198.17.232') I am following this documention https://docs.citusdata.com/en/stable/installation/multi_node_debian.html#steps-to-be-executed-on-all-nodes On worker node database is set up and it is running fine. on coordiator node when i run sudo -i -u postgres psql -c "SELECT * from citus_add_node('20.40.43.246', 5432);" I am getting below error. ERROR: connection to the remote node 20.40.43.246:5432 failed with the following error: fe_sendauth: no password supplied What configuration do i need to change in pb_hba.conf on worker node? -
Django Channels WebSocket Authentication with React: Stuck at Handshake
I'm integrating Django Channels WebSockets into my React app and hit a roadblock with user authentication during the WebSocket handshake. Despite setting up everything according to the docs, my WebSocket connection doesn't recognize authenticated users. Here’s what my setup looks like: Django Channels (consumers.py): from channels.generic.websocket import AsyncWebsocketConsumer import json class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() React (Chat.js): import React, { useEffect } from 'react'; import { w3cwebsocket as W3CWebSocket } from "websocket"; const client = new W3CWebSocket('ws://127.0.0.1:8000/ws/chat/room_name/'); const Chat = () => { useEffect(() => { client.onopen = () => { console.log('WebSocket Client Connected'); }; client.onmessage = (message) => { console.log(message); }; }, []); return <div>Chat Component</div>; }; export default Chat; I’m passing the session ID/token via the WebSocket URL, but Django doesn't authenticate the user on the WebSocket connection. I’m missing the part where I can authenticate the WebSocket request in Django Channels based on the session ID or token provided by the React app. Has anyone faced a similar issue, or does anyone know what I might need to do differently here? Any help or guidance would be greatly … -
Can I use django RQ to delay execution of tasks like saving models to the database? When I try It causes weird issues
I have the following code: @job def create_model(): test_text = "Text1" TestModel.objects.create(test_text=test_text) print("Done!") def test_view(request): create_model.delay() return HttpResponse("Ok!") But this produces weird errors in console: (venv) ➜ DjangoRedisQueueTest python manage.py rqworker 08:58:01 Worker rq:worker:e95d3ce3ab82415cb5f9b1eb8dbdad72 started with PID 30490, version 1.16.1 08:58:01 Subscribing to channel rq:pubsub:e95d3ce3ab82415cb5f9b1eb8dbdad72 08:58:01 *** Listening on default... 08:58:01 Cleaning registries for queue: default 08:58:04 default: drq_test.views.create_model() (f3701c9e-63df-42aa-9dd6-5169892c644c) objc[30495]: +[__NSCFConstantString initialize] may have been in progress in another thread when fork() was called. objc[30495]: +[__NSCFConstantString initialize] may have been in progress in another thread when fork() was called. We cannot safely call it or ignore it in the fork() child process. Crashing instead. Set a breakpoint on objc_initializeAfterForkError to debug. 08:58:04 Moving job to FailedJobRegistry (Work-horse terminated unexpectedly; waitpid returned 6 (signal 6); ) How can I use django RQ to delay such tasks like saving models to the database -
my project name as changed as cannot changed back on pycharm
I've created a project called Socialmedia, few days ago suddenly i noticed the name of the project as changed to a file inside the project as you can see, the project name is manage.py on not Socialmedia the main dir I've tried: Resetting to default IDE and opening the dir project Socialmedia Changing the name Opening the project as Socialmedia -
spoonacular API and django
i have a question. Can i add spoonacular API to my django project? I'm doing a recipe-sharing project and would really like to have a database with ingridients, so i can choose them when making new recipe. My question is if i can have like 2 databases, if that makes sense? i would have djangos database db.sqlite3 and this spoonacular API. Thanks I looked at some youtube tutorial, but it doesnt make sense for me. I tried google it, but unfortunately didnt really catch anything. -
How can I ensure synchronized incrementation of two counters in a Celery async task
I'm encountering a scenario where a single endpoint is receiving multiple concurrent requests for image uploads. Upon successful upload, two counters need to be incremented synchronously. Initially, I tried synchronously incrementing the counters, but due to race conditions, the results were incorrect. Consequently, I implemented an asynchronous Celery task to handle this. However, while one counter stays in sync, the other does not. I'm puzzled why only one counter is affected if both are subjected to the same conditions. I am using Postgres as my database. To address the issue of asynchronous counter incrementation, one potential solution is to remove the counters altogether and instead track the number of uploaded images. However, it's crucial to understand the root cause of the asynchronous behavior to prevent similar issues in the future. This is the piece of code that is doing the increment @shared_task def increment_album_and_event_image_count(album_id): try: with transaction.atomic(): album = Album.objects.get(id=album_id) album.image_count_in_album = F("image_count_in_album") + 1 album.save() album.event.number_of_images_across_albums = ( F("number_of_images_across_albums") + 1 ) album.event.save() return True except Exception as e: logger.error(f"Error incrementing image count: {e}, album: {album}") return False Here the number_of_images_across_albums has correct information while image_count_in_album does not. Here are the model details: class Album(TimeStampedModel): image_count_in_album = models.IntegerField(default=0) event … -
Understanding keycloak authentication with mozilla-django-oidc
I am currently trying to use Keycloak with Django. I use the mozilla-django-oidc package for this and have used this tutorial as a guide, but with my own Keycloak server. So far, everything is working fine. The protected view can only be accessed after logging in via Keycloak. However, django rest framework is causing me problems. I have made the configuration as described in the instructions, but I always get 401 (Unauthorized) back for requests to the Django Rest Framework endpoint. And I don't understand why. As far as I understand it, mozilla-django-oidc sets a "sessionid" cookie to authenticate the user. I can also access the protected view. For a request to the Django Rest Framework endpoint, however, I have to send an Authorization header with the access token according to the mozilla-django-oidc documentation. But where do I get this access token in my single page application to set it in the Authorization header? I have tried to read the access token in the SPA from the mentioned "sessionid" cookie. But this cookie is http only. -
Filling the FormMixin form
Is it possible to populate FormMixin form data without passing the form variable to the template? I have a template, but I don't understand how to create a form with Django, so I just specify the name attribute in the template. The form is created, everything is fine, I override the method get_initial() method, but the form is not filled out Is it possible to do this or do I need to pass the form variable? class CommentEditView(View, FormMixin): form_class = EditCommentForm def get_initial(self): initial = super().get_initial() comment = get_object_or_404(Comment, pk=15) initial['review_text'] = comment.review_text initial['grade'] = comment.grade return initial def get(self, request, comment_id): return render(request, 'catalog/review-edit.html') class EditCommentForm(ModelForm): class Meta: model = Comment fields = ['review_text', 'grade'] <form method="POST"> {% csrf_token %} <textarea class="product-detail-reviews-textarea" name="review_text" id="id_review_text"></textarea> {% for error in form.review_text.errors %} <p class="product-detail-reviews-error">* {{ error }} </p> {% endfor %} <div class="product-detail-reviews-row"> <div class="product-detail-reviews-stars"> <p>Stars:</p> <div class="rating-area"> <input type="radio" id="id_grade_five" name="grade" value="5"> <label for="id_grade_five" title="Star «5»"></label> <input type="radio" id="id_grade_four" name="grade" value="4"> <label for="id_grade_four" title="Star «4»"></label> <input type="radio" id="id_grade_three" name="grade" value="3"> <label for="id_grade_three" title="Star «3»"></label> <input type="radio" id="id_grade_two" name="grade" value="2"> <label for="id_grade_two" title="Star «2»"></label> <input type="radio" id="id_grade_one" name="grade" value="1"> <label for="id_grade_one" title="Star «1»"></label> </div> </div> <button type="submit" class="product-detail-reviews-link">Confirm</a> </div> {% … -
My formset is not valid and i cannot retreive the cleaned_data of each form
I have 3 models below class MenuItem(TranslatableModel): item_id = models.UUIDField(primary_key=True, default=uuid4, editable=False) categories = models.ManyToManyField(MenuCategory, related_name='menu_items') translations = TranslatedFields( name=models.CharField(_('name'), max_length=200), slug=models.SlugField(blank=True, null=True, unique=True), description=models.TextField(_('description'), blank=True, null=True) ) price = models.DecimalField(_('price'), max_digits=10, decimal_places=2, default=0) image = models.ImageField(_('image'), upload_to='menu_items/%Y/%m/%d', blank=True, null=True) is_available = models.BooleanField(_('is available'), default=True) created = models.DateTimeField(_('created'), auto_now_add=True) updated = models.DateTimeField(_('updated'), auto_now=True) def __str__(self): return f'{self.name}'.title() def get_absolute_url(self): return reverse('menu_management:item_detail', args=[self.item_id, self.slug]) class MenuOptionGroup(TranslatableModel): group_id = models.UUIDField(primary_key=True, default=uuid4, editable=False) item = models.ForeignKey(MenuItem, on_delete=models.CASCADE, related_name='options_groups') translations = TranslatedFields( name=models.CharField(_('name'), max_length=200), slug=models.SlugField(blank=True, null=True, unique=True) ) is_required = models.BooleanField(_('is required'), default=False) max_choices = models.IntegerField(_('max choices'), blank=True, null=True) created = models.DateTimeField(_('created'), auto_now_add=True) updated = models.DateTimeField(_('updated'), auto_now=True) def __str__(self): return f'{self.name}'.title() class MenuOption(TranslatableModel): option_id = models.UUIDField(primary_key=True, default=uuid4, editable=False) group = models.ForeignKey(MenuOptionGroup, on_delete=models.CASCADE, related_name='options') translations = TranslatedFields( name=models.CharField(_('name'), max_length=200), slug=models.SlugField(blank=True, null=True, unique=True) ) image = models.ImageField(_('image'), upload_to='menu_options/%Y/%m/%d', blank=True, null=True) price_change = models.DecimalField(_('price change'), max_digits=10, decimal_places=2, default=0) created = models.DateTimeField(_('created'), auto_now_add=True) updated = models.DateTimeField(_('updated'), auto_now=True) def __str__(self): return f'{self.name}'.title() From this 3 class I am trying to create a formset that will go through the MenuOptionGroup and pick up their repective menu_option. my form look like the below class MenuOptionGroupForm(TranslatableModelForm): menu_option = forms.ModelChoiceField(queryset=MenuOption.objects.none(), empty_label="No options", required=False) class Meta: model = MenuOptionGroup # Include the fields that …