Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to implement SSO (Azure AD) on Django admin login but cant figure out how to do that
I'm required to implement SSO on the admin login in a django application. say xyz(dot)com/admin where xyz is my application. so instead of default login procedure I need it through azure ad sso. How should i implement this? I'm fairly new to django and couldent find relevent resources to do so. -
How can I update a OnetoOne related models instance in restframework?
I have two related model a user model and profile model. here's how the data looks like { "id": 2, "phone_number": 9843945748, "email": "someEmial@gmail.com", "profile": { "first_name": "Updated", "last_name": "Updated", "avatar": null, "date_of_birth": "1995-22-01" } } How do I override update() method in serializer to just updated the profile fields. bypassing the USER MODEL required field which is email, phone_number. -
Django and Xcode exception when running website locally
I have a functioning Django site, but when I run the website locally, I get the following exception error. It doesn't appear to occur on the hosted site. Nothing I can find is not working, it is just a puzzle to me why this error is coming up and I would like to fix it because it is annoying - but I don't know where to start looking. Is there a common XCode Django connection that I am overlooking? ---------------------------------------- Exception occurred during processing of request from ('127.0.0.1', 56089) Traceback (most recent call last): File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/socketserver.py", line 683, in process_request_thread self.finish_request(request, client_address) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/socketserver.py", line 747, in __init__ self.handle() File "/Users/u1123114/Documents/projects/kinbank_website/website/myvenv/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File "/Users/u1123114/Documents/projects/kinbank_website/website/myvenv/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/socket.py", line 704, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer ---------------------------------------- -
Image files were deleted by itself in AWS S3 bucket [closed]
I'm using python Django framework for server and AWS-S3 for store uploaded image. Also, i'm using django-storages library for handle S3. But sometimes images were deleted by itself not through django server. Image urls were still exist in DB. So i changed create, put, delete, get action to get in bucket policy But still deleted by itself. What should i do to solve my problem? -
Django Rest Framework settings to allow Authentication from Flutter using Authroization key
I am currently trying to fetch data using Flutter from Django rest framework with the following: final response = await http.get( url, headers: { HttpHeaders.authorizationHeader: 'Authorization: Bearer ......bla bla ..........', }, ); but I keep getting {detail: Authentication credentials were not provided.} and from the Django Rest Framework terminal it is showing: Forbidden: /api/dj-rest-auth/user/ Here is the Django settings.py: INSTALLED_APPS = [ ....................... 'rest_framework', 'users', 'corsheaders', 'django.contrib.sites', 'rest_framework.authtoken', 'dj_rest_auth', 'allauth', 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth.registration', ] # REST_FRAMEWORK = { # 'DEFAULT_PERMISSION_CLASSES': [ # 'rest_framework.permissions.AllowAny', # # ]} REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } CORS_ALLOW_ALL_ORIGINS=True AllowAny =True When I tried to use 'rest_framework.permissions.AllowAny' it returned forbidden when used 'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework.authentication.TokenAuthentication',), 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',) returned Unauthorized here is the views.py: @csrf_exempt def aPage(request): user:User=User.objects.get(pk=1) username=request.POST.get("username") email=request.POST.get("email") print(email) print(username) return JsonResponse({"Username":username , "email": email}) How can I send authenticate a logged in user using their Token to allow them to get data from api? What am I doing wrong that is returned these errors? -
Django ORM How to query and get values when multiple conditions are fulfilled
I have following model class TimePeriod(BaseModel): product = models.ForeignKey(to=Product, on_delete=models.CASCADE) min_travel_days = models.PositiveIntegerField() max_travel_days = models.PositiveIntegerField() value = models.DecimalField(max_digits=19, decimal_places=10) is_business = models.BooleanField() insurance_period_min_days = models.PositiveIntegerField( null=True, blank=True) insurance_period_max_days = models.PositiveIntegerField( null=True, blank=True) and Product model is as class Product(BaseModel): name = models.CharField(max_length=255) I have the following sheet to calculate the min_days and max_days and insurance min max days. Insurance_period Travel days Value 1-92 days 1-30 days 30 1-183 days 1-90 days 45 1-365 days 1-90 days 50 1-365 days 1-180 days 60 My problem is suppose I have 29 days as travel days and 90 days as Insurance days How do I calculate the value by using django query? As the actual value for 90 days of insurance days and 29 days travel time is 30. I tried doing this way TimePeriod.objects.filter(is_business=True,product__name='silver',insurance_period_min_days__lte=90,insurance_period_max_days__gte=90, min_travel_days__lte=29,max_travel_days__gte=29).values('value').first() I am getting 4 different result as my query satisfies all condition of above table any way I can do to satisfy above table conditon? to get 30 as value? -
Is there a way to install Django Rest Application as a single installable file [.exe]?
Looking for a encrypted way of installation for Django rest application. Is there a way to install it as binary or encrypted format or as a class files like Java. Currently source code is being copied into server path and executing below command python manage.py runserver I was trying to do with below package pyconcrete - Unable to install using pip command. pyinstaller - Only migration folder and files are copying to dist folder not the other files in each module. pyinstaller --name=application-name application-name/manage.py ./dist/application-name/application-name.exe runserver localhost:8000 --noreload -
django channels on railway no supported websockets library detected
I'm migrating my portfolio projects from heroku to railway, they're all asgi and use django channels and redis. They work fine on heroku, but not on railway. All of my api endpoints are working and connecting to postgres. But when I got to the chat part of my application it won't connect. The deploy logs in railway say the following: [2022-11-11 02:19:58 +0000] [11] [WARNING] Unsupported upgrade request. [2022-11-11 02:19:58 +0000] [11] [WARNING] No supported WebSocket library detected. Please use 'pip install uvicorn[standard]', or install 'websockets' or 'wsproto' manually. I've double checked my requirements.txt and updated my packages. I've uninstalled and reinstalled locally ( I made sure to use uvicorn[standard] which supports sockets). I've used railway cli to manually pip install install the packages and none of the above has worked. I'm not using any heroku buildpacks. Any body else having this issue? -
ModuleNotFoundError while running '$ python manage.py collectstatic --noinput'
I tried to solve this problem by searching a lot but couldn't find any solutions. I am trying to deploy my django app to heroku from heroku-CLI but got this error while running '$ python manage.py collectstatic --noinput'. ModuleNotFoundError: No module named 'my_app.settings.local'; 'quiz_api.settings' is not a package !Error while running '$ python manage.py collectstatic --noinput'. This error happened after settings.py is divided into base.py, local.py and product.py. Before this, there was no problem at all. root my_project -my_app -settings __init___.py "in settings dir" base.py local.py production.py __init__.py "in my_app dir" wsgi.py etc... .env manage.py etc... base.py (BASE_DIR might be the problem) from pathlib import Path import os import json BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cloudinary_storage', 'cloudinary', 'my_app', 'rest_framework', 'django_filters', 'debug_toolbar', 'django_cleanup.apps.CleanupConfig', 'djoser', 'corsheaders' ] REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'], 'DATETIME_FORMAT': "%Y-%m-%d %H:%M", 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE':8, } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' INTERNAL_IPS = ['127.0.0.1'] ROOT_URLCONF = 'quiz_api.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'quiz_api.wsgi.application' CORS_ALLOW_CREDENTIALS = True import dj_database_url MAX_CONN_AGE = 600 … -
I am not able to delete a specific item from a table in Django template/view
I have a list of wallet addresses in my template. When I tried deleting an address by clicking on the delete button, it returns an error message. I think it is an error from the way my template was structured. But, I don't really know. When I try deleting an address by manually inputting the id of the address in the delete view URL, it gets deleted. Here is the error message that is returned. Traceback (most recent call last): File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\fields\__init__.py", line 2018, in get_prep_value return int(value) The above exception (invalid literal for int() with base 10: 'Btc') was the direct cause of the following exception: File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\admin\Documents\Django\crypto\dashboard\views.py", line 275, in del_wallet wallet.delete() File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\base.py", line 1137, in delete return collector.delete() File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\deletion.py", line 475, in delete query.update_batch( File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\sql\subqueries.py", line 78, in update_batch self.get_compiler(using).execute_sql(NO_RESULTS) File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\sql\compiler.py", line 1819, in execute_sql cursor = super().execute_sql(result_type) File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\sql\compiler.py", line 1382, in execute_sql sql, params = self.as_sql() File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\sql\compiler.py", line 1785, in as_sql val = field.get_db_prep_save(val, connection=self.connection) File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\fields\related.py", line 1146, in … -
Any way to get nested groups of users in Django rest framework with user[0]=id&user[0]=id&user[1]=id
Need to somehow handle the user[0]=id&user[0]=id&user[1]=id use case and return [[users], [users]] from db in django -
Concatenate gettext_lazy translated string with a normal string in Django 4.1.x
The question seems dummy, but I wish I could append some language-invariant string to a translated string in Django: from django.utils.translation import gettext_lazy as _ class House(models.Model): height_m = models.IntegerField( verbose_name=_("height")+" [m]", null=False, ) Here, the unit [m] is from the SI so I don't need to translate it. But by doing so in my model, the result in other languages desperately stays in English. How could I concatenate a normal string with a translated string in Django 4.1.x? -
Enable a signal only for google log in
I have a customer panel in which customer can sign up by filling a user creation form or via sign in with google. To enable the user to sign in with google I have created a signal as following: @receiver(post_save, sender = CustomUser) def customer_create(sender, instance, created, *args, **kwargs): if created: instance.is_customer = True instance.save() customer = Customer.objects.create(user=instance) customer.username = instance.username customer.email = instance.email customer.first_name = instance.first_name customer.last_name = instance.last_name customer.save() it works fine for the user who are signed with via google. But when user tries to sign up via form a duplicate key value violation arises as it also works with the signal. How can I enable the signal only for the users who are signed in via google? -
Business and IT
Model class schooldetail(models.Model): schoolbranch = models.CharField(max_length=100, unique=True,blank=False) name = models.CharField(max_length=100,blank=False) description = models.TextField(blank=True) email=models.EmailField(max_length=50,blank=True) contactno=models.CharField(max_length=50,blank=True) accountname=models.CharField(max_length=50,blank=False) bsb=models.CharField(max_length=6) accountno=models.CharField(max_length=10) def __str__(self) -> str: return self.schoolbranch class studentdetails(models.Model): first_name =models.CharField(max_length=50,blank=True, null=True) last_name = models.CharField(max_length=50,blank=True, null=True) dob=models.CharField(max_length=15,blank=True, null=True) MALE=1, FEMALE=2 OTHER=3 STATUS_CHOICES=( ('MALE','Male'), ('FEMALE','Female'), ('OTHER','Other') ) sex=models.CharField(max_length=10,choices=STATUS_CHOICES,blank=True, null=True) CITIZEN = 1 PERMANENT = 2 WORKING = 3 STUDENT = 4 TRAVEL = 5 RESIDENTAL_STATUS = ((CITIZEN, 'Australian Citizenship'), (PERMANENT, 'Permanent Resident.'), (WORKING, 'Working Visa'), (STUDENT, 'Student Visa'), (TRAVEL, 'Travel Visa'),) residental_status=models.CharField(max_length=50,choices=RESIDENTAL_STATUS,blank=True, null=True) user=models.ForeignKey(to=User,on_delete=models.CASCADE) def __str__(self) -> str: return self.first_name class EnrollmentModel(models.Model): student=models.ForeignKey(studentdetails,on_delete=models.CASCADE) YES=1 NO=0 COND_STATUS=( ('YES','Yes'), ('NO','No') ) medical_condition =models.BooleanField(default=False) medication_routine = models.BooleanField(default=False) any_restriction = models.BooleanField(default=False) agree_condition = models.BooleanField(default=False) agree_declaration = models.BooleanField(default=False) PROCESS='p', CANCEL='c' APROVED='a' ENROLLED='e' SUBMIT='s' ENROLLMENT_STATUS=( ('PROCESS','Process'), ('CANCEL','Cancel'), ('APROVED','Aproved'), ('ENROLLED','Enrolled'), ('SUBMIT','Submit'), ) enrolment_status=models.CharField(max_length=20,choices=ENROLLMENT_STATUS) FULL='f', UNPAID='n' PARTIAL='p' PAYMENT_STATUS=( ('FULL','Full'), ('UNPAID','UnPaid'), ('PARTIAL','Partial') ) payment_status = models.CharField(max_length=10,choices=PAYMENT_STATUS) application_date=models.DateTimeField(auto_now=True) school = models.ForeignKey( schooldetail, on_delete=models.CASCADE, blank=True, null=True, ) Serializer from rest_framework import serializers from enrolments.models import studentdetails,schooldetail from .models import EnrollmentModel from enrolments.serializers import StudentDetailSerializer,SchoolDetailSerializer class EnrollSerializer(serializers.ModelSerializer): school= serializers.SerializerMethodField('get_school') def get_school(self, instance): school=instance.schoolbranch return school student= serializers.SerializerMethodField('get_student') def get_student(self, instance): student=instance.first_name return student class Meta: model:EnrollmentModel fields=['id','school','student','enrolment_status','payment_status'] --views @api_view(['GET']) @permission_classes((AllowAny,)) def full_list(request): try: school_queryset = EnrollmentModel.objects.all() serializer = EnrollSerializer(school_queryset, many=True) return Response(serializer.data) except schooldetail.DoesNotExist: return Response(status … -
Django model conditionally based on two abstract classes
I have more of a conceptual question, but with practical implications. In a Django 4.1.x app, I have one owner class which can be either a person or an organization, but never both together. These two classes doesn't need to be registered in the database, only the owner has to: from django.db import models class Person(models.Model): first_name = models.CharField( max_length=256, verbose_name=_("First name"), null=False, ) # other person attributes class Meta: abstract = True def __str__(self): return self.first_name class Organization(models.Model): full_name = models.CharField( max_length=256, verbose_name=_("Full name"), null=False, ) # other organization attributes class Meta: abstract = True def __str__(self): return self.full_name Whatever the owner instance is, it must have a name attribute: In the case of a person, the owner's name has to be the first_name and in case of an organization, the full_name. Also, if an owner object is an instance of a Person: I only want to expose those other attributes of Person. Same goes if owner is an instance of an Organization. I certainly miss some concepts here / maybe I'm not looking in the right direction, but how to build the owner model based on a type of "conditional or parametrized inheritance", let's say? Please, note that … -
access django-apscheduler's jobs properties programmatically
I use the django-apscheduler package to run cron (scraping) jobs. the package stores the past jobs with some information/properties (e.g. local runtime, duration etc.) somewhere on the database for display on the admin backend. When I want to access these information/properties about the jobs programmatically in the views.py (e.g. to show the last runtime of a job in the context/template), how would I do that? -
How to optimize queries in Django Rest Framework serializers (DRF)?
info: I have component model with search_tags field which is a many to many field with Search model and i have a serializer for Component model which is ComponentSerializer and i using get_videos method to get videos for each component and i want to get videos for each search tag in search_tags field and store them into a filtered_data_list and return it as a response The response time is very slow and i want to optimize it and i don't know how to do it (I am new to django and rest framework) These are methods i studied but i don't know how to use them in my case and i don't know if they are the best way to do it or not: prefetch_related and select_related but it didn't work. Use raw sql query but i don't know how to do it. Use django cache but i don't know how to do it. Use django cache and raw sql query but i don't know how to do it. class ComponentSerializer(serializers.ModelSerializer): ''' component serializer ''' videos = serializers.SerializerMethodField() class Meta: model = Component fields = ['title', 'slug', 'videos'] def get_videos(self, obj): filtered_data_list = [] for search in obj.search_tags.select_related('component').filter(is_active=True): ''' Thumbnails … -
Stylesheets to use in django-ckeditor
I'm using django-ckeditor which is a TextArea WYSIWYG editor for creating and editing posts in a future blog. The editor produces beautiful posts, but when I save to the database and go to view it, it appears without the style I initially created in the editor. See the following code: {%load static%} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>MyDomain | {{post.title}}</title> <link href="{% static 'ckeditor/ckeditor/contents.css'%}" rel="stylesheet"> </head> <body> <h1>{{ post.title }}</h1> <p class="date"> Published {{ post.publish }} by {{ post.author }} </p> {{ post.body|safe|linebreaks }} </body> </html> My question is: which styles do I import to present the same view as when I created the post? -
Optimizing dynamic filter
I have this funciton def get_documents_by_metadata(self, params): filters = {} result_filtered = None for index, key in enumerate(params.keys()): filters["metadocument__meta_config__field"] = key filters["metadocument__value__contains"] = params.get(key) if index == 0: result_filtered = super().get_queryset().filter(**filters) else: result_filtered = result_filtered.filter(**filters) return result_filtered I need to filter by dynamic values ( KEY/VALUE metadata registered in my DB), I can't predict what keys Im goint to recieve. My first idea is filter and filter again the result, but I'm sure that exist better way. Ty! -
what are best solutions for hold OTP
I want to create a no password system so user login with email and i sent verification code to the user. user enter email and send request server check email if exist send the otp number to user’s email server need hold otp number so later on compare with user number i want to now in the server side what is the best solution for hold otp code db, file, etc I want to achieve best security and speed for APIs. -
Looking for best practices for Django queries in Python classes
Say I have a Django model Model1 and I have a python class Class1. Class1 has some properties that are derived from values in Model1. What is the best way to accomplish this? Gain access to Mode1 in the Class1 __init__ method, or access Model1 in the Class1 property? Not sure how to define "best way" - more pythonic, more efficient, etc? A very contrived example of what I am asking: class Model1(models.Model): model_id = models.AutoField(primary_key=True) field1 = models.CharField() field2 = models.CharField() class Class1: def __init__(self, value1, value2): self.value1 = value1 self.value2 = value2 self._model1 = Model.objects.get(model_id=self.value1) @property def value3(self): return self._model1.field1 * 10 @property def value4(self): field2 = Model.objects.get(model_id=self.value2).field2 return field2 * 22 Which paradigm is "better" - the property for value4 or value3? I am going to guess the the property for value4 is more efficient because the Model1 query set does not hang around in memory as it does when it is contained in the Class1 __init__. Thanks! -
html2pdf Resize and Fix Copying Onto Same Page
I have the following below: <div> <button id="btn">screenshot</button> </div> <script src="https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/html2canvas@1.0.0-rc.7/dist/html2canvas.min.js"></script> <script> window.onload = function () { console.log("Window is loaded") document.getElementById('btn').addEventListener("click", function () { html2canvas(document.getElementById('test')).then(function (canvas) { document.body.appendChild(canvas); var imgdata = canvas.toDataURL("image/jpg"); var doc = new jspdf.jsPDF(); doc.addImage(imgdata, "JPG", 10, 10); doc.save("sample.pdf"); }); }) } </script> It works BUT not well. The two problems I can't solve are: It opens a PDF with a screenshot of a small section of the page, like it's too zoomed in. It also puts a screenshot of the page on the page itself, this screenshot is stored in my browser session and goes away on a fresh reload. I don't know which part of the code is responsible for that, so I don't how to stop it from doing this. If there was a way to get that screenshot copied to another .html page and the user can view it from there, that might be a workaround. However, I don't know how to manipulate the code to get it to do that and I am only a beginner with javascript/html2pdf; Python is the only language I know right now. I am using DJANGO as my framework if this matters. Thank you! I … -
Django is not rendering my static file (css, images, etc)
I am able to view my site (html)in the browser but none of my mark-up is working. I have checked my stylesheet links for types, settings.py, but I am at a lost. When I run my site I am getting the below responses in my terminal. `[10/Nov/2022 20:46:23] "GET / HTTP/1.1" 200 168 [10/Nov/2022 20:46:23] "GET /static/css/main.css HTTP/1.1" 404 1795 [10/Nov/2022 20:46:23] "GET /static/images/6%2Bcart.png HTTP/1.1" 404 1810` I have tried going over everything possible but cannot locate the issue, any and all feedback would be greatly appreciated. I am not allowed to post images yet so unfortunately, I could not include. I have re-coded, deleted and remade static folder, scoured the internet with no luck yet. -
JWT token authentication in Github Social Authentication
I am working with django github social authentication using dj_rest_auth. I am trying to add JWT token authentication in it. I am trying to get access_token and refresh_token. To get it i want to enter username and password in api view.In social authentication login there is no password. we have Only username and mail id. Is it possible to access token by using only username? If Yes. How is it possible? -
Restrict users to see detailview based on model field value in Django
I am learning and have a change management project where my model contains field confidential which is by default False, however during instance creation so called initiator could tick it as True. This basically means that only users which are part of current record so called signees could open and see the instance. I am trying to apply get_queryset override on my DetailView: # MOC DetailView class MocDetailView(LoginRequiredMixin, DetailView): model = Moc template_name = 'moc/moc_detail.html' def get_queryset(self, *args, **kwargs): qs = super().get_queryset(*args, **kwargs) for obj in qs: print(obj) confidential = obj.confidential initiator = obj.initiator coordinators = obj.coordinators.all() reviewers = obj.reviewers.all() approvers = obj.approvers.all() preimplements = obj.preimplements.all() authorizers = obj.authorizers.all() postimplements = obj.postimplements.all() closers = obj.closers.all() if initiator and initiator == self.request.user and confidential == True: qs = qs.filter(Q(confidential=True) & Q(initiator=self.request.user)) return qs for signee in coordinators: coordinator_name = signee.coordinator_name if coordinator_name and coordinator_name == self.request.user and confidential == True: qs = qs.filter(Q(confidential=True) & Q(coordinators__coordinator_name=self.request.user)) return qs for signee in reviewers: reviewer_name = signee.reviewer_name if reviewer_name and reviewer_name == self.request.user and confidential == True: qs = qs.filter(Q(confidential=True) & Q(reviewers__reviewer_name=self.request.user)) return qs for signee in approvers: approver_name = signee.approver_name if approver_name and approver_name == self.request.user and confidential == True: qs = qs.filter(Q(confidential=True) …