Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SAMLRequest and Signature parameters in SSO
I am using django-saml-sp library, I have one working idp and I try to implement SSO log in to my Django project. For doing it, I need to generate SAMLRequest and Signature parameters in the query string to redirecting SSO Log on page. I couldn't find a way to do that. -
How can I get the list of user from group after filtering in Django-template-language
In the below image How can I get filtered users Right now I am rendering the users with : <div class="row-sm-3"> <div class="container d-flex"> <form action="{% url 'search' %}" method="POST"> {% csrf_token %} <select name="select" class="form-control" id="mySelect" onchange="myFunction()"> {% for group in groups %} <option selected="selected" >{{group.name}}</option> {% endfor %} </select> <input class="btn btn-sm btn-primary" type="submit"> </form> </div> </div> -
Django Admin custom field in ModelForm is displayed as blank after being set in get_readonly_fields
I am using python 3.10 and Django 4.1 The model I'm making an admin panel for has a JSONField that will hold values from dynamically created form fields in the Admin panel. The issue is that I should be able to also dynamically set them to readonly from the AdminModel using the get_readonly_fields method. To do that I made a custom ModelForm which adds new fields inside the _init_ method. class CustomForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CustomForm, self).__init__(*args, **kwargs) for name in dynamic_fields_names(): self.fields[name] = forms.ChoiceField(choices=dynamic_fields_values(name)) def clean(self): cleaned_data = super(ExecutionAdminForm, self).clean() for name in dynamic_fields_names(): self.instance.description_fields[name] = cleaned_data.pop(name) class Meta: model = Execution fields = "__all__" @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): form = CustomForm def get_form(self, request, obj=None, **kwargs): kwargs["fields"] = admin.utils.flatten_fieldsets(self.fieldsets) return super(MyModelAdmin, self).get_form(request, obj, **kwargs) def get_fieldsets(self, request, obj): return ( (None, {"fields": ("user", "status")}), ("Description", {"fields": dynamic_fields_names()}) ) def get_readonly_fields(self, request, obj): if can_change_dynamic_fields: return [] return dynamic_fields_names() When I set them to readonly using get_readonly_fields they are rendered as empty inside the browser Not set as readonly Set as readonly -
How to iterate over 2 variables in Django template
I have an app for some quiz with questions and choices. So I'm trying to render all this stuff to Django templates. In my views.py it looks like this def choice(request): question_list = get_list_or_404(Question) page = get_object_or_404(Page, name='about') letters = ["A", "B", "C", "D", "E"] return render(request, 'qview/choice.html', { 'question_list': question_list, 'page': page, 'letters': letters, } ) I have a list of questions and list with letters. All of that I'm sending as context to my template. {% if question_list %} <ul> {% for question in question_list %} <li><a href="#">{{question.question}}</a></li> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.text }}</li> {% endfor %} </ul> {% endfor %} </ul> {% else %} <p>No questions available</p> {% endif %} So here I'm going through all of questions and all of choices connected to this question. But I can't get how I can also go through letters list? I was thinking about zip it all. But in view I have only questions not choices, so I can't zip to it. So what else is possible here? -
Problem with Bind mount on Azure Web App Service for Containers with docker-compose
I have a problem with starting my_app on Azure Web App Service for containers. I followed few tutorials and checked this amswer but I still get the following error: ERROR - Exception in multi-container config parsing: YamlException: (Line: 22, Col: 9, Idx: 498) - (Line: 22, Col: 37, Idx: 526): Bind mount must start with ${WEBAPP_STORAGE_HOME}. My docker-compose file looks like this: version: '3' services: db: container_name: my_app_django_db image: postgres:14.5-alpine volumes: - postgres_data:/var/lib/postgresql/data/ networks: - my_app_network env_file: - ./.env.prod app: container_name: my_app_django_app build: context: ./backend dockerfile: Dockerfile.prod restart: always command: python manage.py runserver 0.0.0.0:8000 volumes: - ./backend/:/usr/src/backend/ networks: - my_app_network ports: - 8000:8000 env_file: - ./.env.prod depends_on: - db react: container_name: my_app_react_app build: context: ./frontend dockerfile: Dockerfile.prod restart: always command: npm start volumes: - ./frontend/:/usr/src/frontend/ networks: - my_app_network ports: - 3000:3000 env_file: - ./.env.prod depends_on: - app redis: container_name: my_app_redis image: redis:7-alpine ports: - 6379:6379 networks: - my_app_network celery_worker: container_name: my_app_celery_worker restart: always build: context: ./backend command: celery -A my_app_settings worker --loglevel=info --logfile=logs/celery.log volumes: - ./backend:/usr/src/backend networks: - my_app_network env_file: - ./.env.prod depends_on: - db - redis - app celery-beat: container_name: my_app_celery_beat build: ./backend command: celery -A my_app_settings beat -l info volumes: - ./backend:/usr/src/backend networks: - my_app_network env_file: - ./.env.prod … -
Django with mqttasgi, how to update the db with contents of received messages
I have a Django project that reads messages from mqtt using mqttasgi I can see the messages in the mqttasgi output mqttasgi --host localhost --port 1883 myapp.asgi:application 2023-01-10 18:08:55.380206 -- Received a message at topic: test/device/online With payload: b'true' And QOS: 1 what I want to do is search for device in the message and then update the model just like I do with the web interaction I tried importing the model into the consumer import json from datetime import datetime from mqttasgi.consumers import MqttConsumer import django import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'boat.settings') django.setup() from .models import Device class MyMqttConsumer(MqttConsumer): async def connect(self): await self.subscribe('sirjames/#', 2) async def receive(self, mqtt_message): print(f"{datetime.now()} -- Received a message at topic: { mqtt_message['topic'] }") print(f"With payload: { mqtt_message['payload'] }") print(f"And QOS: { mqtt_message['qos']}") (site, devicename, topic) = f"{mqtt_message['topic']}".split('/',2) device = Device.objects.get(name=devicename) if topic == 'online': if mqtt_message['payload'].decode('UTF-8') == 'false': device.online = False device.save() else: device.online = True device.save() pass async def disconnect(self): await self.unsubscribe('sirjames/#') but as soon as I do that then mqttasgi complains about it django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. How do I modify the code so that the db update works? -
I'm a newbie to python/Django and getting a value error and no http response error. Please can anyone tell me what's wrong?
ValueError at /update_department/14 The view management.views.update_department didn't return an HttpResponse object. It returned None instead. Request information USER admin GET No GET data POST Variable Value csrfmiddlewaretoken 'XLqZBPhMKImvlfgWsNLeN1Ei8nz5u1HJ15IvAQV4JNwVMeG31rhDOD1q9PJuwXmz' department_code '15' department_name_e 'Finance' department_name_l 'Finance' parent_code '' submit '' These are the details.I don't know why is there error here while all the posted data is right.also the form is not updating. Models: class Departments(models.Model): department_code = models.CharField(db_column='Department_Code', primary_key= True, max_length=20, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase. department_name_e = models.CharField(db_column='Department_Name_E', max_length=50, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase. department_name_l = models.CharField(db_column='Department_Name_L', max_length=50, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase. parent_code = models.CharField(db_column='Parent_Code', max_length=20, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase. is_active = models.BooleanField(db_column='Is_Active') # Field name made lowercase. created_by = models.IntegerField(db_column='Created_By') # Field name made lowercase. created_date = models.DateTimeField(db_column='Created_date') # Field name made lowercase. modified_by = models.IntegerField(db_column='Modified_By') # Field name made lowercase. modified_date = models.DateTimeField(db_column='Modified_date') # Field name made lowercase. class Meta: db_table = 'Departments' unique_together = (('department_code'),) def __str__(self): return str("self.department_name_e") or '' View: @login_required def update_department(request, department_code): dep_up = Departments.objects.get(department_code=department_code) if request.method == "POST": form = DepartmentsForm(request.POST, instance = dep_up) if form.is_valid(): department_code = form.cleaned_data['department_code'] department_name_e = form.cleaned_data['department_name_e'] department_name_l = form.cleaned_data['department_name_l'] parent_code = form.cleaned_data['parent_code'] obj = form.save(commit = False) obj.is_active = True … -
How can I get deleted object? I want to upload the object that has been deleted before but since some fields have unique=True, I get integrity error
this is my model this is my delete function I tried getting the firmware whose field of is_delete=True -
Problem with the JWT token to interact with google cloud
The following code is used to create a JWT for a google cloud service called fleetengine this code was working and suddenly it creates a wrong token the sad thing is that it is working on my friend's device with the same code without any changes. def generate_token(role='server', **kwargs): iat = time.time() exp = iat + 3600 if role == 'consumer': iss = CONSUMER_SERVICE_ACCOUNT_EMAIL sub = CONSUMER_SERVICE_ACCOUNT_EMAIL authorization = { "trackingid": kwargs.get('tracking_id') } elif role == 'driver': iss = DRIVER_SERVICE_ACCOUNT_EMAIL sub = DRIVER_SERVICE_ACCOUNT_EMAIL authorization = { "deliveryvehicleid": kwargs.get('vehicle_id') } else: iss = SERVER_SERVICE_ACCOUNT_EMAIL sub = SERVER_SERVICE_ACCOUNT_EMAIL authorization = { "taskids": ["*"], "deliveryvehicleid": "*", "tripid": "*", "vehicleid": "*" } payload = {'iss': iss, 'sub': sub, 'aud': 'https://fleetengine.googleapis.com/', 'iat': iat, 'exp': exp, "authorization": authorization, } private_key = SERVER_GOOGLE_FLEET_ENGINE_SECRET_KEY.replace('\\n', '\n') additional_headers = {'kid': SERVER_GOOGLE_FLEET_KEY_ID, 'alg': 'RS256', 'typ': 'JWT'} signed_jwt = jwt.encode(payload, private_key, headers=additional_headers) return str(signed_jwt), iat, exp -
Execute function from an already rendered page django - Execute multiple function from an url
Quick question: What’s the best way / practise to execute a function (called from a form with POST) in a page which was render and generated by another function ? Context : Imagine page/id_48/ , all information and even the page is generated and render by a function My question is oriented with the path, as the path of the page is already use in urls.py to to execute the function which render the page Thank’s ! -
How to implement observer pattern the way django signals implements it
there's a design issue i have with a problem i'm currently working that will require a certain observable to emit values whenever it reaches a computation milestone,so i need values emitted intermediately,i discovered django implements something similar with signals which is just an implementation of the observer pattern but i really wanted to implement it the way django signals is implemented because observers subscribing to an observable( e.g after saving a model to the db i.e post_save signal) is very much decoupled in the sense that the observing function only needs to be annotated with the @receiver decorator. So i took a look at django's source code and tried creating a simple version of the signal mechanism i created a signals class in one module with the decorator : class Signal: def __init__(self): self.observers=[] def connect(self,receiver): self.observers.append(receiver.__name__) def send(self,sender,**named): return [ (receiver,mem_dec(signal=self,sender=sender,**named)) for receiver in self.observers ] class Child(Signal): def __init__(self): super().__init__() def mem_dec(signal,**kwargs): def wrapper(func): signal.connect(func, **kwargs) return func return wrapper if __name__ == "__main__": send_signal=Child() send_signal.send(sender="class_child",a="henry") and i placed the decorated function in another module to serve as the observer: from .signals import mem_dec from .signals import Child @mem_dec(Child,sender=Child) def hello(a,**kwargs): print(f'hey {a}') i noticed in my implementation … -
How can I access the values of this object in javascript?
[] I'm building a django webapp. When I access my backend for user information, I get an object in the following format according to console.log: { "email": "foo", "id": 1, "name": "bar" } However when I try to access something like(https://i.stack.imgur.com/Gu5EX.png) "userInfo.name", I get the error : Cannot read properties of undefined (reading 'name') From what I've read this is because this is not actually a JSON object and console.log is 'lying' to me. I've tried multiple other methods and they all throw up similar errors, including: userInfo[name] userInfo['name'] userInfo[0] userInfo[1] Object.keys(userInfo) I've also tried JSON.stringify -ing and JSON.parse -ing the object, as well as doing both. JSON.stringify returns a string that LOOKS like JSON to me: {"email":"foo@gmail.com","id":1,"name":"bar"}, but JSON.parse still will not parse it, and I still cannot access any of the values. -
how to create a GET request using gcloud function python
This is my gcloud function import firebase_admin from firebase_admin import credentials from firebase_admin import firestore import functions_framework if (not len(firebase_admin._apps)): firebase_admin.initialize_app() # Register an HTTP function with the Functions Framework @functions_framework.http def callback(request): db = firestore.client() request_json = request.get_json(silent=True) if not(request_json): return {'response':"Server error: no payload","code":101} ### Define variables sessionId = request_json['sessionId'] serviceCode = request_json['serviceCode'] text = request_json['text'] return text and when i evoke it with postman i get the error That’s an error. Your client has issued a malformed or illegal request. That’s all we know. what might be the problem -
Pylint warn the usage of print statement
I am using pylint_django for my django project. And I want to disable print statement usage or warn about it at least. Because I am using custom logger class. But there is no any warn about usage of print. extension-pkg-whitelist= ignore=CVS ignore-patterns= jobs=1 limit-inference-results=100 load-plugins= persistent=yes suggestion-mode=yes unsafe-load-any-extension=no [MESSAGES CONTROL] confidence= disable=missing-docstring, invalid-name, astroid-error, protected-access, broad-except enable=c-extension-no-member, print-statement [REPORTS] evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) output-format=text reports=no score=yes [REFACTORING] max-nested-blocks=5 never-returning-functions=sys.exit [LOGGING] logging-format-style=old logging-modules=logging .... How can i solve this issue? VsCode settings.json { "python.linting.pylintEnabled": true, "python.linting.enabled": true, "python.linting.flake8Enabled": false, "python.linting.prospectorEnabled": false, "python.linting.pylintArgs": [ "--load-plugins=pylint_django", "--rcfile=.pylintrc", "--enable=print-statement" ] } -
How to change subscription from PlanA to PlanB using Stripe with Python/Django
I can create a Stripe subscription for a customer using the following code : subscription = stripe.Subscription.create( customer=stripe_customer_id, items=[ { "plan": stripe_plan_A }, ] ) I want to change the upgrade the subscription to stripe_plan_B but while keeping rest of the configuration same. I have experimented with the following code to change the plan from stripe_plan_A to stripe_plan_B; however this following command results in having two subscriptions at the same time, rather than a single subscription. stripe.Subscription.modify( subscription.id, items=[ { "plan": selected_membership.stripe_plan_B }, ] ) Is there any suggestion for this, so I can fluently change between the plans ? -
Django - How to navigate between multiple apps
I'm a beginner in Django and don't understand how the templates "dirs" in setup.py works In my project directory, I have 2 apps. I want to reach them via a navigation bar. In the Navigation bar, I have "Home" "Manipulation" "Visualization" I can reach Home and Manipulation page, but when I try to reach the Visualization page, the browser shows me the Manipulation page again. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'manipulation/templates/manipulation'), os.path.join(BASE_DIR, 'visualization/templates/visualization'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Somebody can help me please? Thank you very much In Dirs : [], when I swap the order and put the "Visualization" path before the "Manipulation" path, I get the Visualization page instead of the Manipulation page -
GraphQL file uploads and cURL: json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 188 (char 187)
I have a graphql-server that is running at localhost:3001 I want to send files to a python flask server together with some variables in a cURL request. Here is what i'm sending curl http://localhost:3001/graphql/ -F operations='{ "query": "mutation ConvertDocToPDF($input: ConvertWordDocToPDFInputType!){ convertDocToPDF(input: $input){ success } } ", "variables": { "input" : { "file": null, "saveName": "hello" } ] } }' -F map='{ "0": ["variables.input.file"] }' -F 0=@README.md Surprisingly I'm getting an error which says: json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 188 (char 187) [11/Jan/2023 09:38:31] "POST /graphql/ HTTP/1.1" 500 107387 What may be the problem in this request. Any help input will be appreciated -
Django share common permission across django app
I would like to know if there is a better way to implement common permission that is very similar across django app. For example, app1 need permission_x, app2 need permission_x, and app3 need permission_x too. In order to satisfy this i made permissions.py and create permission_x class which inherits from BasePermission on each app. app1/permissions.py from rest_framework.permissions import BasePermission, SAFE_METHODS class ReadOnly(BasePermission): """Object-level permission to only allow read-only operations.""" def has_permission(self, request, view): # Read permissions are allowed to any request, # hence allow GET, HEAD, or OPTIONS requests. return request.method in SAFE_METHODS app2/permissions.py from rest_framework.permissions import BasePermission, SAFE_METHODS class ReadOnly(BasePermission): """Object-level permission to only allow read-only operations.""" def has_permission(self, request, view): # Read permissions are allowed to any request, # hence allow GET, HEAD, or OPTIONS requests. return request.method in SAFE_METHODS app3/permissions.py from rest_framework.permissions import BasePermission, SAFE_METHODS class ReadOnly(BasePermission): """Object-level permission to only allow read-only operations.""" def has_permission(self, request, view): # Read permissions are allowed to any request, # hence allow GET, HEAD, or OPTIONS requests. return request.method in SAFE_METHODS As you can see, neither app1, app2, nor app3 need these basic permissions. They are exactly the same as each other. I implemented it as above, but is there … -
creating logging for django rest framework
I'm creating a logger for my application. It should create a file day wise and if the file size is cross 100MB it will create a new file for that this is my logger_config.py import logging from logging.handlers import TimedRotatingFileHandler logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Use a TimedRotatingFileHandler to log to a file that rotates every day handler = TimedRotatingFileHandler('loggerFiles', when='D', interval=1, backupCount=30) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) # Logging levels logger.debug("This is a debug message") logger.info("This is an info message") logger.warning("This is a warning message") logger.error("This is an error message") import os filepath = None def check_log_file_size(filepath): """ Check if the log file has exceeded the maximum size """ size = os.path.getsize(filepath) if size > 100000000: # 100000000 bytes = 100MB new_filepath = f'{filepath}_1' os.rename(filepath, new_filepath) that is how I'm using it. class MyView(APIView): def get(self, request): try: # some code that may raise an exception 1/0 except Exception as e: logger.exception("An exception occurred: %s", e) return Response({"error": "An exception occurred"}, status=status.HTTP_400_BAD_REQUEST) but the problem is it is not creating fils as I want. -
Bootstrap not allows to post data from html in django
{% csrf_token %} User name </div> <div class="form-group"> <label class="form-label" for="form2Example2">Password</label> <input type="password" id="form2Example2" class="form-control" name="password" required/> </div> <button type="button" class="btn btn-primary btn-block mb-4">Sign in</button> i try to post data like email id and password in post method , but it sent through get method . I think there may be problem with bootstrap. can u tell me what are the modifications to be done in the bootstrap for post data method. thanks -
Bulk insert on multi-column unique constraint Django
Suppose we have a model from django.db import models class Concept(models.Model): a = models.CharField(max_length=255) b = models.CharField(max_length=255) c = models.CharField(max_length=255) d = models.CharField(max_length=255) class Meta: constraints = [ models.UniqueConstraint( fields=('a', 'b'), name='first_two_constraint'), ] I want to execute bulk_create on this model such that, on a unique constraint violation of 'first_two_constraint', an update would be performed. For sqlite3, the features https://github.com/django/django/blob/main/django/db/backends/sqlite3/features.py#L44 forces that unique_fields be passed to the bulk_create function. However, it's non-obvious to me what that should be. https://github.com/django/django/blob/829f4d1448f7b40238b47592fc17061bf77b0f23/django/db/models/query.py#L701 I tried the constraint's name, however that failed. Tracing, that occurs since this list of unique_fields is specifically the field names, and there wouldn't be a field name for a constraint . https://github.com/django/django/blob/829f4d1448f7b40238b47592fc17061bf77b0f23/django/db/models/query.py#L768 As a result, I'm at a loss of how to approach this issue. Based off of the sqlite3 documentation, https://www.sqlite.org/lang_conflict.html sub-heading 'REPLACE', the functionality should be possible as, even if it's multiple columns, the violation would still be a unique constraint violation "When a UNIQUE or PRIMARY KEY constraint violation occurs..." Does anyone have any insight as to how to deal with multiple column constraints with the bulk_create function or confirmation that the only approach to this is with raw SQL? I don't believe it's to have unique_fields=('a', … -
When I host the code navigation bar is not showing properly, but when I run it in pycharm it works fine. Is anyone know what is the problem?
this is when I run this code at pycharm this is when I host the code -
Django Rest Framework - Why am I getting an error when the function isn't even supposed to do anything
Have this URL: path("products/product/<int:product>/rating/", ProductRating.as_view()), and this view to handle the URL: class ProductRating(APIView): permission_classes = [permissions.IsAuthenticated] serializer_class = ProductRatingSerializer def get(request): breakpoint() In the URL the product in int:product is just the id of the product in question. No matter what I put there whether it be int:pk or int:id I get the same error every time: TypeError: get() got an unexpected keyword argument 'product' I have tried using generic view RetrieveAPIView and just an APIView and i get the same error. Why am I getting an error and not the breakpoint? -
I'm using cv2 in django to open the camera, but there's a problem when refreshing or opening multiple windows
from django.http import HttpResponse from django.shortcuts import render,get_object_or_404,redirect from django.http import StreamingHttpResponse import cv2 import time import threading from queue import Queue import numpy as np import platform from django.views.decorators import gzip class Vis_camera(object): def new(cls) : if not hasattr(cls,'instance'): cls.instance = super(Vis_camera,cls).new(cls) return cls.instance def __init__(self): # self.video = cv2.VideoCapture(0,cv2.CAP_ANY) self.video = cv2.VideoCapture(0) (self.grabbed, self.frame) = self.video.read() self.status = True self.thread = threading.Thread(target=self.update, args=()) self.thread.start() def __del__(self): self.video.release() def get_frame(self): image = self.frame _, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() def update(self): while True: (self.grabbed, self.frame) = self.video.read() def gen(camera): while True: frame = camera.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') @gzip.gzip_page def detect_vis(request): camera = Vis_camera() return StreamingHttpResponse(gen(camera), content_type="multipart/x-mixed-replace;boundary=frame") Every time I turn the page, I run self.video.release() function, but it doesn't seem to work properly. Error : error: (-215:Assertion failed) !image.empty() in function 'cv::imencode' -
I want test an Api endpoint with post request with image file but not seems working
I have uploaded image of my code when I run my test it says object type of bytes is not serializable response = self.client.post(reverse('update_profile_picture/'), data=json.dumps({"user_uuid":str(newdata.user_uuid),'profile_picture':open('../server/api/tests/test.jpg', 'rb').read()}), files={'profile_picture':open('../server/api/tests/test.jpg', 'rb')}, content_type='application/json', **{'HTTP_AUTHORIZATION': f'Bearer {test_access_token}'}, headers={"Content-Type":"multipart/formdata"}) class UpdateProfilePicture(APIView): serializer_class = UpdateProfilePictureSerializer def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) authmeth, auth = request.META["HTTP_AUTHORIZATION"].split(" ", 1) payload = jwt.decode(auth, settings.SECRET_KEY, algorithms=['HS256']) token_user_uuid = payload.get('user_uuid') if serializer.is_valid(): user_obj = User.objects.get(user_uuid=serializer.data['user_uuid']) if str(token_user_uuid) != str(user_obj.user_uuid): return return_response.APIResult(False, "session_id_miss_match", {}, errors["session_id_miss_match"], status.HTTP_400_BAD_REQUEST).to_json() return return_response.APIResult(True, "profile_success", {"user": {"user_uuid":user_obj.user_uuid, "profile_picture":user_obj.profile_picture.url}}, success["profile_success"], status.HTTP_200_OK).to_json() else: error_msg = get_error_message(serializer.errors) return return_response.APIResult(False, "validate_error", {}, errors[error_msg], status.HTTP_400_BAD_REQUEST).to_json() class UpdateProfilePictureSerializer(serializers.ModelSerializer): user_uuid = serializers.UUIDField(label=("uuid"), required=True, error_messages={ "invalid": "uuid_require", "required": "uuid_require", "blank": "blank_uuid"}) profile_picture = serializers.ImageField( label=("Profile Picture"), required=True, error_messages={ "invalid": "invalid_profile", "required": "profile_required", "blank": "blank_profile"})