Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need to return the object from the celery shared task queue process
I have faced the error "kombu.exceptions.EncodeError: Object of type 'JsonResponse' is not JSON serializable " In my settings.py : CELERY_BROKER_URL = 'amqp://localhost' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_BACKEND = 'django-db' So it only accepts response as a json value. But i need to return the object or instance Example : I need to return file path. Thanks in advance. @shared_task def celery_upload(path, id , user_id): upload = Upload() result = upload.file_generation_validation(path, id , user_id) excel = Excel() file_path = excel.Export(result["error"], "aaa") return file_path if I return result it will be successful, But file_path object throws error. -
Django orm left join return data like mysql
I have two table like this: class Classroom(models.Model): name = model.ChartField() class Student(models.Model): name = model.ChartField() classroom = model.ForeignKey(to='Classroom', related_name='students') there has some data like this: | Classroom | Student | | ----- | ------- | | Classroom_A | student_1, student_2, student_3 | | Classroom_B | (no Student) | Now I want to get the data by Django orm like this (return 4 rows data): | Classroom_name | student_name | | --- | --- | | Classroom_A | student_1 | | Classroom_A | student_2 | | Classroom_A | student_3 | | Classroom_B | null | How can I write the orm? The result is similar this (This is not what I want): data = [] for classroom in Classroom.objects.all(): students = classroom.students.all() if students: for student in students: classroom.student = student data.append(classroom) else: classroom.student = None data.append(classroom) -
Dynamically render select choices Django
I posted a screenshot below to hopefully make this easier to understand so I will reference it in my question. I am trying to create a recipe cost calculator app. I have 3 model namely Recipe, RecipeIngredient and Ingredient The user will add ingredients to the database and then create recipes using those ingredients throught the RecipeIngredient model. When creating an Ingredient the user selects a unit eg. (grams). Now when the user goes to create a Recipe (see screenshot below) I want to only display the units that are relevant to that ingredient and not all of them for eg. A user added Beef and the unit was grams now when the user is adding a RecipeIngredient to the Recipe I want them to only be able to select from the "Weight" category in the example (see screenshot below). The reason for this is because grams can't be converted to milliliters and so it shouldn't even be a choice. If anything is unclear or you need more information just let me know. Models Recipe Models from django.db import models from django.urls import reverse from django.contrib.auth import get_user_model from ingredients.models import Ingredient class Recipe(models.Model): """Store recipe information and costs""" class … -
TypeError: __init__() got an unexpected keyword argument 'service' error using Python Selenium ChromeDriver
When i am running the code on pycharm idle the code is going good without errors. when i converted #into exe file by using pyinstaller or auto-py-to-exe i am getting this type of error. # #i am not getting where i have to change.# ''' import time,datetime from datetime import date import selenium from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys import pyautogui from pywinauto.keyboard import send_keys import calendar import openpyxl import tkinter as tk from tkinter import * from tkinter import messagebox as mb from pywinauto import application import pywinauto import comtypes.client driver = webdriver.Chrome(service=Service(ChromeDriverManager().install())) ''' -
Q object filter returns wrong queryset - inherited foreign key relations
I have the models User, Club, Investment and Match where a User can make multiple Investments related to Clubs who have multiple Matches. I want to query all matches of clubs, where a user is invested in. Models # User is Django base user # Club class Club(models.Model): """ A table to store all clubs participating """ country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=30) # Investment class Investment(models.Model): """ A table to store all investments of an investor/user and associated clubs """ investor = models.ForeignKey(User, on_delete=models.CASCADE) target = models.ForeignKey(Club, on_delete=models.CASCADE) # Match class Match(models.Model): """ A table to store matches and their results """ home = models.ForeignKey(Club, on_delete=models.CASCADE, related_name='home_team') away = models.ForeignKey(Club, on_delete=models.CASCADE, related_name='away_team') Query idea in human language: Query all matches, where 'home' or 'away' club is an 'investment' 'target' of the 'user' View def render_dashboard_overview(request): qs_matches = Match.objects.filter( Q(home__investment__investor=request.user) | Q(away__investment__investor=request.user) ) context = { 'qs_matches': qs_matches } return render(request, 'dashboard/dashboard_overview.html', context) This is what I came up with but it returns a queryset of Clubs rather than matches.. -
Django, DRF: To get two different models in one query set
Two models exist as follows. class Video(models.Model): title = models.CharField(max_length=300) image_url = JSONField() sample_image_url = JSONField(blank=True, null=True) sample_movie_url = models.URLField(max_length=1000, blank=True, null=True) review = JSONField(blank=True, null=True) ... class UserVideo(models.Model): title = models.CharField(max_length=300) thumbnail_url = models.URLField(max_length=1000, unique=True) preview_url = models.URLField(max_length=1000, blank=True, null=True) tags = models.ManyToManyField(Tag, blank=True, db_index=True) ... I would like to retrieve data with two mixed models as follows. We also need to do some sorting, etc. How should I describe the query set? [ { "title": "", "image_url": {}, "sample_image_url": {}, "sample_movie_url": "", "review": {} }, { "title": "", "thumbnail_url": "", "preview_url": "", "tags": [ {} ] } ... ] Also, in this case, only one Model can be specified for the DRF Serializer, but how can Is it possible to give two Models to Serializer? class Video_UserVivdeo_Serializer(serializers.ModelSerializer): class Meta: model = #Video, UserVideo ? fields = '__all__' -
404 Not found Page in Django when deploy with docker and cookiecutter
I'm having a weird problem when deploying to the production of Django. Previously when accessing https://gae-gw.systems. I work very normally, but today when I try to access again all 404 errors. Currently, I use Traefik as a proxy server. Consider the following configs: Traefik.yml entryPoints: web: # http address: ":80" http: # https://docs.traefik.io/routing/entrypoints/#entrypoint redirections: entryPoint: to: web-secure web-secure: # https address: ":443" certificatesResolvers: letsencrypt: # https://docs.traefik.io/master/https/acme/#lets-encrypt acme: email: "khoadautay@gmail.com" storage: /etc/traefik/acme/acme.json # https://docs.traefik.io/master/https/acme/#httpchallenge httpChallenge: entryPoint: web http: routers: web-secure-router: rule: "Host(`gae-gw.systems`) || Host(`www.gae-gw.systems`)" entryPoints: - web-secure middlewares: - csrf service: django tls: # https://docs.traefik.io/master/routing/routers/#certresolver certResolver: letsencrypt middlewares: csrf: # https://docs.traefik.io/master/middlewares/headers/#hostsproxyheaders # https://docs.djangoproject.com/en/dev/ref/csrf/#ajax headers: accessControlAllowOriginList: "*" hostsProxyHeaders: ["X-CSRFToken"] services: django: loadBalancer: servers: - url: http://django:5000 urls.py urlpatterns = [ path("", index, name="index"), path("home/", HomeView.as_view(), name="home"), path(settings.ADMIN_URL, admin.site.urls), path("users/", include("erp_greenwich.users.urls", namespace="users")), path("accounts/", include("allauth.urls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
javascript loop doesn't work for django formset field calculation only calcuate one formset field with id such as id_forms-0-rate
This is the code in my template it takes value from input field id and calculate the value. The code only works for one formset field or item such as one having id= id_form-0-rate. I dont know why loop doesnot work for added formset such as one having id= id_form-1-rate. template.html <script type = "text/javascript" > var id= $("#id_form-TOTAL_FORMS").val(); console.log(id); for(let i=0; i<10; i++) { console.log(i); $("#id_form-" + i + "-quantity").keyup(function () { var rate = parseFloat($("#id_form-" + i + "-rate").val()); var quantity = parseFloat($("#id_form-" + i + "-quantity").val()); var discount = parseFloat($("#id_form-" + i + "-discount").val()); $("#id_form-" + i + "-amount").val(rate * quantity - discount); }); $("#id_form-" + i + "-rate").keyup(function () { var rate = parseFloat($("#id_form-" + i + "-rate").val()); var quantity = parseFloat($("#id_form-" + i + "-quantity").val()); var discount = parseFloat($("#id_form-" + i + "-discount").val()); $("#id_form-" + i + "-amount").val(rate * quantity - discount); }); $("#id_form-" + i + "-discount").keyup(function () { var rate = parseFloat($("#id_form-" + i + "-rate").val()); var quantity = parseFloat($("#id_form-" + i + "-quantity").val()); var discount = parseFloat($("#id_form-" + i + "-discount").val()); $("#id_form-" + i + "-amount").val(rate * quantity - discount); }); } </script> -
"message": "At least one block must be specified" error line-bot-sdk
I am making video component with this sample https://developers.line.biz/en/docs/messaging-api/create-flex-message-including-video/ and this sdk for line messaging app https://github.com/line/line-bot-sdk-python import linebot.models as lm message = lm.FlexSendMessage( alt_text='hello', contents={ "type": "bubble", "size": "mega", "hero": { "type": "video", "url": "https://example.com/video.mp4", "previewUrl": "https://example.com/video_preview.jpg", "altContent": { "type": "image", "size": "full", "aspectRatio": "20:13", "aspectMode": "cover", "url": "https://example.com/image.jpg" }, "aspectRatio": "20:13" } } ) push_message(line_user,message) error message is like this, LineBotApiError: status_code=400, request_id=a7ef5dbd-333e-4a69-b1ea-b8f277829485, error_response={"details": [{"message": "At least one block must be specified", "property": "/"}], "message": "A message (messages[0])\u00a0in the request body is invalid"}, What does it mean? -
why my server django database get Syntex error
why my server django database get Syntex error DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '----' 'USER': 'mai', 'PASSWORD': '----', 'HOST': '----' 'PORT': '26257', } }``` error is : 'USER': 'mai', On Console: 'USER': 'mai', ^ SyntaxError: invalid syntax -
Unable to iterate over all objects in table using objects.all()
I am writing a migration script that will iterate over all objects of a cassandra model (Cats). There are more than 30000 objects of Cat but using Cats.objects.all(), I am only able to iterate over 10000 objects. qs = Cats.objects.all() print(len(qs)) # returns 10000 print(qs.count()) # returns 30000 -
com.vmware.vapi.rest.httpNotFound - Vsphere API
I am trying to get my Vsphere version through API for program I am building. The thing is I keep receiving this error even though it worked previously. It stopped working now. Here is the command I run, but in Python django: curl -H "vmware-api-session-id: b00db39f948d13ea1e59b4d6fce56389" https://{api_host}/api/appliance/system/version Here is the erro: { "error_type": "NOT_FOUND", "messages": [ { "args": [], "default_message": "Not found.", "id": "com.vmware.vapi.rest.httpNotFound" } ] } -
For loop indentation is not taking place in jinja2 templating in vscode
I am writing a for loop or if else using jinja2 templating but it is not giving me indentation in vscode. Fore example, I wrote this: {% extends 'base.html' %} {% block content %} <h2>This is Item List</h2> {% for item in items %} <p>{{items}}</p> {% endfor %} {% endblock content %} But when I press Ctrl s or save it manually, it loses the indentation. The code becomes like this: {% extends 'base.html' %} {% block content %} <h2>This is Item List</h2> {% for item in items %} <p>{{items}}</p> {% endfor %} {% endblock content %} This is happening for for loops, if else and everything inside jinja2 templating. Not happening in normal python codes. This is not giving any error, but I feel distressed. How to solve it. -
'str' object has no attribute 'get' django rest framework
I'm trying to connect rest framework views to a template, the get method is working properly but when posting datas it gives me the error : views.py: class Login(APIView): serializer_class = LoginSerializer permission_classes = [IsAnonymous, ] template_name = 'accounts/login.html' renderer_classes = [TemplateHTMLRenderer] style = {'template_pack': 'rest_framework/vertical/'} def get(self, request): serializer = self.serializer_class() return Response({'serializer': serializer, 'style': self.style}) def post(self, request): payload = request.data serializer = self.serializer_class(data=payload) if serializer.is_valid(): user = authenticate(request, username=payload['username'], password=payload['password'] ) if user: login(request, user) response = { 'message': 'you logged in successfully!' } code = status.HTTP_200_OK else: response = { 'message': 'your username or password is wrong!' } code = status.HTTP_401_UNAUTHORIZED else: response = { 'error': serializer.errors } code = status.HTTP_403_FORBIDDEN return Response(data=response, status=code) I don't know where am I doing wrong , I appreciate if anyone can help me in this case -
Is There a possible way to align the list of apps displayed on the left side of the admin panel in django? [duplicate]
if you run a django website and go to admin panel you can see all the list of the models you created which is sorted in alphabetical order . is there any way i can change the sortnig order? -
Django global variable for all templates or context processor manipulation
I'm working on a website with 2 different languages. Text which should be translated is only in the template.htmls (index.html, accounts.html ... about 20 files) sometemplate.html ... <div>{% if ls == 'at' %}Deutschtext {% else %}english text{% endif %}</div> ... my context processor ... def language_selection(request): return {'ls': 'at'} ... This works, but how can I change the value of the context_processor from template? Or is there any other approach for a 'global variable' which can be changed and is accessible from all templates? -
Django, DRF: Two different models in one query set
How can I get the following two models in one query set? Sorting and searching must be performed. class Video(models.Model): title = models.CharField(max_length=300) image_url = JSONField() sample_image_url = JSONField(blank=True, null=True) sample_movie_url = models.URLField(max_length=1000, blank=True, null=True) review = JSONField(blank=True, null=True) ... class UserVideo(models.Model): title = models.CharField(max_length=300) thumbnail_url = models.URLField(max_length=1000, unique=True) preview_url = models.URLField(max_length=1000, blank=True, null=True) tags = models.ManyToManyField(Tag, blank=True, db_index=True) ... I tried .union(), but I get the following error qs = Video.objects.all() qs2 = UserVideo.objects.all() print(qs.union(qs2)) django.db.utils.ProgrammingError: each UNION query must have the same number of columns By specifying the id in .values(), the union works successfully, but we need to get different fields for both models. Also, since we are using DRF, we need a way to work with ModelSerializer. -
how can i change this SQL to Django ORM code?
select * from sample join process on sample.processid = process.id where (processid) in ( select max(processid) as processid from main_sample group by serialnumber ) ORDER BY sample.create_at desc; models.py class Sample(models.Model): processid = models.IntegerField(default=0) serialnumber = models.CharField(max_length=256) ## class Process(models.Model): sample = models.ForeignKey(Sample, blank=False, null=True, on_delete=models.SET_NULL) Hi I have two models and I need to change this SQL query to Django ORM, Python code. How can I change the SQL query to ORM code? how can i change the subquery to ORM? Thanks for reading. -
how to save multiple forms on the same page, combining text input and uploading multiple files?
let's say I have 3 forms on the same page and each one has its own save button, the last 2 do multiple image loading, how can you write the view combining those 3 forms? I have no idea, I have tried many ways, I have read the django documentation but I cannot understand due to my inexperience, how to solve it <form enctype="multipart/form-data" method="post"> {% csrf_token %} <label for="your_name">Your name: </label> <input id="your_name" type="text" name="your_name" value="{{ form.name }}"> <input type="submit" value="OK"> </form> <form enctype="multipart/form-data" method="post"> {% csrf_token %} <input type="file" name="garantia" class="type-file" multiple="" id="file-inputz" onchange="previewz()" accept="image/*" required=""> <button class="btn btn-primary mb-3" type="submit" value="Post">Save</button> </form> <form enctype="multipart/form-data" method="post"> {% csrf_token %} <input type="file" name="fotosCarro" class="type-file" multiple="" id="file-input" onchange="preview()" accept="image/*" required=""> <button class="btn btn-primary mb-3" type="submit" value="Post">Save</button> </form> -
Django migration gives psycopg2.errors.DuplicateTable: relation error
I have previously restored the database for the system, and while i tried to migrate through the django applicaion, the following error is thrown. What is the possible cause and how can we mitigate such cases. I guess the problem is with the existing table conflict, will it solve the issue by delete/dropping the conflicting tables. Applying introduction.0001_initial...Traceback (most recent call last): File "C:\Users\HG\Desktop\RC\SB\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql) psycopg2.errors.DuplicateTable: relation "introduction_introduction" already exists The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\HG\Desktop\RC\SB\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\HG\Desktop\RC\SB\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\HG\Desktop\RC\SB\venv\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\HG\Desktop\RC\SB\venv\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\HG\Desktop\RC\SB\venv\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\HG\Desktop\RC\SB\venv\lib\site-packages\django\core\management\commands\migrate.py", line 231, in handle post_migrate_state = executor.migrate( File "C:\Users\HG\Desktop\RC\SB\venv\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\HG\Desktop\RC\SB\venv\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\HG\Desktop\RC\SB\venv\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\HG\Desktop\RC\SB\venv\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, … -
whats the right way for read MySQL database with django
I'm new to django I have a local application I wrote in python that writes scientific data to a MySQL database hosted on a digital ocean droplet that also runs django. I'm experiencing an intermittent problem where occasionally (maybe 1 in 3 tries) a page request produces a 'bad gateway' error message. Refreshing the page will normally produces the correct page. A page example is http://104.131.165.99/garage/ The problem is annoying and I'm not sure what the cause is but I never understood models in django and I'm not sure how to even clearly ask my question. My local application uses pymysql to connect to the MySQL database thats part of the server where django is hosted, in otherwords a mysql database thats NOT(?) really associated with the instance of django running on the server. The code in my django app (see below) that runs when a page is requested uses pymysql with a host address of 127.0.0.1 to read and manipulate the MwSQL data. Whether or not this is the cause of my problem, I always wondered if this was the proper way to read mysql data in django considering the app writing to that database is on a different … -
Django serializer errors ('Invalid data. Expected a dictionary, but got {datatype}.')
-I am trying to create assignments (assignment can be created by user). -The API is working fine when i send request from DjangoRest Framework API the assignment is created successfully. -But in the actual form(Frontend form) when i try to post an assignment the following error is being generated. -PLease Help! Error that is being generated models.py def upload_to(instance, filename): return 'assignments/{filename}'.format(filename=filename) class Assignment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='assignments', blank=True, null=True) username = models.CharField(max_length=255, blank=True, null=True) title = models.CharField(max_length=20, blank=False, null=False) subject = models.CharField(max_length=20, choices=subject_choices, default=Statistics, blank=False) assignment_type = models.CharField(max_length=20, choices=assignment_choices, default=Assignment, blank=False) assignment_file = models.ImageField(_("Image"),upload_to=upload_to,default="", blank=False) description = models.CharField(max_length=50, blank=False) created_at = models.DateTimeField(auto_now_add=True) serializers.py class AssignmentSerializer(serializers.ModelSerializer): class Meta: model = Assignment fields = ('user','username','title', 'subject', 'assignment_type', 'assignment_file', 'description') views.py class CreateAssignmentView(APIView): parser_classes = [MultiPartParser, FormParser] serializer_class = AssignmentSerializer def post(self, request, format=None): assignment = request.data print(assignment) serializer = self.serializer_class(data = assignment) if serializer.is_valid(): print("valid") serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response({'Bad Request': 'Invalid data...'}, status=status.HTTP_400_BAD_REQUEST) REACT Function for create assignments const createAssignment = (e) => { e.preventDefault(); let formData = new FormData(); console.log() const data = { user : user.user_id, username : user.full_name, title : assignmentTitle, subject : assignmentSubject, assignment_type : assignmentType, assignment_file : assignmentFile[0].name + " " + "(" … -
Django Rest Framework Postman 'POST' request error
I'm still having this error when trying to do a post request from postman. { "username": [ "This field is required." ], "password": [ "This field is required." ] } I can make the same post request successfully from my DRF localhost, but when i try on postman i get the error above. How can I solve it? Views.py class PlayThingList(viewsets.ModelViewSet): serializer_class = PlayThingSerializer queryset = PlayThing.objects.all() class UserViewset(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer Serializers.py class PlayThingSerializer(serializers.ModelSerializer): class Meta: model = PlayThing fields = '__all__' class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'password'] urls.py router = DefaultRouter() router.register('playthings', PlayThingList, basename='playthings') router.register('users', UserViewset) urlpatterns = [ path('', include(router.urls)), ] -
RegexField validation error not being raised; Postman API request
Upon testing the response of an APIView with Postman, it's returning validated data pertaining to the query string attached to the request. In this case the query string consists of ?username="I___am_not_binny". Yet only strings with single underscores between characters are allowed. Upon making a request to the api endpoint it returns a 200 status yet it's suppose raise a bad request with a 400 status code. Tests ran through DRF with different string variations pass. Why is a 200 status code being returned? Strings tested: ["_This_is_me", "_This_is_me001_", "This_is_me_", "_____This_is_", "This_is_my_full_username", "WhoAm+"] ] Status: 200 OK { "username": "i___am_not_binny" } serializers.py class RegisterSerializer(ModelSerializer): username = RegexField( re.compile("^(_?[a-zA-Z0-9]+)+"), required=False, min_length=6, max_length=20, validators=[ character_validator, total_digits_validator, UniqueValidator(get_user_model().objects.all()) ] ) validators.py def character_validator(string): match = re.search(r"\W", string) if match: raise ValidationError("invalid character found", code="invalid") return string def total_digits_validator(string): match = re.findall(r"\d", string) if match and len(match) > 3: raise ValidationError("only up to 3 digits allowed in username") return string -
Weird behavior with model/object permissions and viewsets
I am experiencing some weird behavior where djangorestframework returns a 404 when trying to browse the browsable API, but attaching a ?format=json at the end returns a normal response. A simplified version of my project setup: #### API views ... class UserRUDViewSet( drf_mixins.RetrieveModelMixin, drf_mixins.UpdateModelMixin, drf_mixins.DestroyModelMixin, viewsets.GenericViewSet, ): """Viewset combining the RUD views for the User model""" serializer_class = serializers.UserSerializer queryset = models.User.objects.all() permission_classes = [permissions.RudUserModelPermissions | permissions.RudUserObjectPermissions] ... #### app API urls ... _api_prefix = lambda x: f"appprefix/{x}" api_v1_router = routers.DefaultRouter() ... api_v1_router.register(_api_prefix("user"), views.UserRUDViewSet, basename="user") #### project urls from app.api.urls import api_v1_router as app_api_v1_router ... api_v1_router = routers.DefaultRouter() api_v1_router.registry.extend(app_api_v1_router.registry) ... urlpatterns = [ ... path("api/v1/", include((api_v1_router.urls, "project_name"), namespace="v1")), ... ] The problem: I am trying to add permissions in such a way that: A user can only retrieve, update or delete its own User model instance (using per-object permissions which are assigned to his model instance on creation) A user with model-wide retrieve, update or delete permissions (for example assigned using the admin panel), who may or may not also be a django superuser (admin) can RUD all user models. To achieve this my logic is as follows: Have a permissions class which only checks if a user has per-object …