Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is sequence of ERD and models generation?
When going to define relational database tables, what is sequence of generating ERD and django models? Why almost discussions are about converting django models to ER diagram? It not should be first creating ERD, then generating django models from this concepts? -
What is the best car history check application in the UK?
I am looking for cost efficient and extensive car history check application for the UK based cars. What is the best car history check application ? The car history report should include if the vehicle Used Before First Registration data and It should also provide MOT history, tax information, Mileage issues, Exported, Type Approval Category and other vehicle basic informations as free I've tried so much application but they are generally very expensive and do not contains requested informations -
Selected field only some users
I have a Tasks model. One of its fields is status. How can I make the NEW and COMPLITED statuses be selected only by the author of the task, while these statuses were not available to performers? models.py class Tasks(models.Model): STATUS_CHOICE = ( ('new', 'new'), ('in progress', 'in progress'), ('on finish', 'on finish'), ('completed', 'completed') ) title = models.CharField(max_length=255) text = models.TextField() status = models.CharField(max_length=255, choices=STATUS_CHOICE) author = models.ForeignKey(User, on_delete=models.CASCADE) performers = models.ManyToManyField(User, blank=True, related_name='performers') date_create = models.DateField(default=now) date_update = models.DateField(blank=True, null=True) serializers.py class TasksSerializer(ModelSerializer): author = SlugRelatedField(read_only=True, slug_field='username') performers = SlugRelatedField(many=True, read_only=True, slug_field='username') class Meta: model = Tasks fields = '__all__' views.py class TasksViewSet(ModelViewSet): permission_classes = [IsAuthenticated, IsPerformers] queryset = Tasks.objects.all() .select_related('author') .prefetch_related('performers') serializer_class = TasksSerializer filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filterset_fields = ['status'] search_fields = ['title', 'text'] ordering_fields = ['date_create', 'date_update', 'author', 'status'] Can you tell me how to implement this? -
How to fetch and post data with DRF and Jquery
I am very new to using API and JS so please go easy on me. I have done tons of trouble shooting but I can't seem to find any reliable information that I can personally comprehend. I have all of my viewsets and serializers set up and the API works perfectly. I am trying to get it work on the front end now. I am currently at the point where I can Post my cart to the database and it generates an ID, but the items aren't been added. I am not asking for anyone to do it all for me but any guidance would be very much appreciated, at the very least a decent guide to follow. Here is my current JS: const updateBtns = document.querySelectorAll('.update-cart'); const user = '{{request.user}}'; for(let i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ event.preventDefault(); // prevent page from refreshing const productId = this.dataset.product; const action = this.dataset.action; console.log('productId:', productId, 'action:', action); console.log('USER:', user); createCart(productId, action); // Pass cartId to the function }); } function createCart(productId, action){ var csrftoken = getCookie('csrftoken'); console.log('User is logged in, sending data...'); const url = `http://127.0.0.1:8000/api/carts/`; fetch(url, { method: 'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}), mode: … -
Django Login system breaks the javascript
So I am creating a Django application and so far I have a nice template using HTML, CSS, and Javascript, however once I implemented an authentication system the javascript only works when a user is logged in but stops working once they are logged out. Before I implemented the login system, the javascript used localStorage in order to store theme preferences and it worked perfectly but now the javascript only works if a user is currently logged in, so I decided to try to use cookies in order to store a user's theme preferences but that also only works once user is logged in. I'm not sure how to proceed any help is much appreciated. Here is the javascript file using localStorage const body = document.body; const themeToggleBtn = selectElement('#theme-toggle-btn'); const currentTheme = getCookie('currentTheme'); // Check to see if there is a theme preference in the cookie, if so add the light theme to the body if (currentTheme) { body.classList.add('light-theme'); } themeToggleBtn.addEventListener('click', function () { // Add light theme on click body.classList.toggle('light-theme'); // If the body has the class of light theme then add it to cookie with a longer expiration time, if not remove it if (body.classList.contains('light-theme')) { setCookie('currentTheme', … -
Python Django Model.save() saved wrong value in column
I'm new in Django, and maybe question is dumb, but anyway... I've problems with MyModel.save() saving in database, i'm trying to save some specific column which is used as filter in another part of my code... but this calue is not saving properly in Database as i expected from saving query... models.py: class MyModel(models.Model): ..other code.. country = models.CharField('countryName', max_length=5, default='CH') views.py, here I'm trying to save specific column in database: template = MyModel.objects.get(id=template_id) currentCountry = settings.COUNTRY template.country = currentCountry template.save() but when I'm doing SELECT country from table I got different value from what I'm saving in views.py... also this value is different from SQL query which I've got from logging queryies in Django console... logged query: (0.005) UPDATE "my_app_templateadvert" SET "profile_id" = 60, "category_id" = 14, "category2_id" = 213, "category3_id" = 2120, "category4_id" = NULL, "subject" = 'test comment LV', "description" = 'test comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment LVtest comment … -
Can I use Django as backend framework for my blockchain website
I am a beginner and wanted to make a blockchain project. I don't have any knowledge of blockchain as of now. I have a basic understanding of Django and have made a few projects. I was wondering can I make a blockchain website with react.js as the front-end and Django as the backend framework. Is Django viable for web3 or should I use Node.js (I don't know Node.js)? This is my final year of college and I have to make a decent project, so learning a new library like node.js will be very time-consuming. -
waiting for websocket connection in django channels consumer
I am using Celery and Channels to notify a user when a certain action is performed on the server by another user. On the browser, I am using WebSockets to connect the user to the consumer. Unfortunately, if the user is not online (which means the WebSocket is closed) when an event occurs, they will miss the notification, which I store in the database. How can I check if the user is still connected and send the information, or if not, wait for the connection to be established and then send the notification? consumer.py class MyConsumer(AsyncWebsocketConsumer): async def connect(self): self.user_inbox = f'inbox_{self.scope["user"].username}' # Check if user is anonymous and close the connection when true if self.scope["user"].is_anonymous: await self.close() self.connected_user = self.scope["user"] 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() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard(self.room_group_name, self.channel_name) async def chat_message(self, event): """FIRES WHEN MESSAGE IS SENT TO LAYERS""" event_dict = { "message_header": event["message_header"], "message_body": event["message_body"], "sender": event["sender"], "subject": event["subject"], } # Send message to WebSocket await self.send(text_data=json.dumps(event_dict)) tasks.py @shared_task def send_notification_to_ws(ws_channel, ws_event): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)(ws_channel, ws_event) signals.py ws_event = { "type": "chat_message", "message_header": message_header, "message_body": message_body, "sender": … -
Converting from Flask to Django
What is Django's equivalent of the data type flask.wrappers.Response? if request.method == "GET": data = open("print.txt","r") response_r = app.response_class( response=data, status=200, mimetype='text/plain' ) As shown in the code above, response_r's datatype() is flask.wrappers.Response and I want to use this code in Django (not flask). -
FUNCTION_INVOCATION_FAILED Error when deploying django application to vercel, but on localhost everything works
I connect freedb remote mysql database, it is works on localhost, but not on vercel. Displayed this error in vercel logs And this is Js Console errors, but I think that the server cannot fail to start because of this this is my first time uploading django to versel and i can't imagine what could be causing this error. I would really appreciate your help, thanks in advance I changed the database, because already vercel not suported sqlite database.Connect the remote mysql database.If it works, it should show a screen like this -
Correct way to handle database errors in Django
I have doubts about how to implement certain things in a Django Rest API (I'm using DRF), and I want to ask you for guidelines. Imagine two models, for example, Employee, and Department. Each employee belongs to a Department, so the model should contain a foreign key in Employee pointing to the Department to which he belongs. We cannot save an Employee if we do not assign a valid Department. So, the scenarios we need to handle are, from the top of my head: An Employee with no Department An Employee with an invalid Department Now, because this is a REST API, I assume that the data that feeds the application came from the POST call. So, both scenarios can be represent as: bad_payload = { "employee_name": "John Doe", } inconsistent_payload = { "employee_name": "John Doe", ... "department": "Invalid Department" } Assuming Invalid Department is not on the database. So, my questions: Would the view be the best place to validate, or would it be better to trust the error that the database will throw when trying to insert the data into the table? (Remember, the foreign key has the NOT NULL restriction. If the validation is done on the … -
Generating and storing sitemaps for a django-tenants project
I am currently working on a Django SaaS project powered by django-tenants having a few tenants. What is the best way to generate sitemaps for a multi-tenancy app? Is it preferable to save the sitemap file for each tenant in disk storage or to cache each sitemap in memory? -
Cannot reinitialise DataTable in Django
I'm confused on how can I infuse my json format from django to Datatable , what I tried below using loop in the script {% for json in company %} <script>..</script> {% endfor% } but It persist error DataTables warning: table id=DataTables_Table_0 - Cannot reinitialise DataTable. Is there's any wrong with my implementation, Am I correct? to fetch all data from views.py json to datatable , is there anyway? Javascript {% block footer_scripts %} {% for row in company %} <script> $(function () { var dt_basic_table = $('.datatables-basic'), dt_complex_header_table = $('.dt-complex-header'), dt_row_grouping_table = $('.dt-row-grouping'), dt_multilingual_table = $('.dt-multilingual'), dt_basic; // DataTable with buttons // -------------------------------------------------------------------- if (dt_basic_table.length) { dt_basic = dt_basic_table.DataTable({ ajax: assetsPath + 'json/table-datatable_example.json', //I want to infused here the json format from views.py columns: [ { data: '' }, { data: 'id' }, { data: 'id' }, { data: 'full_name' }, { data: 'email' }, { data: 'start_date' }, { data: 'salary' }, { data: 'status' }, { data: '' } ], columnDefs: [ { // For Responsive className: 'control', orderable: false, searchable: false, responsivePriority: 2, targets: 0, render: function (data, type, full, meta) { return ''; } }, { // For Checkboxes targets: 1, orderable: false, searchable: false, … -
Unable to display continuous output from a python script to HTML view in django
I am trying to display the continuous output from a python script on the HTML page but the output is being displayed once the entire execution of the script is completed. I have used subprocess to run the python script(test.py) and when I execute the python script independently I could see the output line by line but the same is not working when I use it along with websockets. Can anyone please help me fix the problem? Here is my code: consumers.py import os import subprocess from channels.generic.websocket import AsyncWebsocketConsumer class MyAsyncWebsocketConsumer(AsyncWebsocketConsumer): async def connect(self): print("Websocket connected") print("Channel name...", self.channel_name) print("Channel layer...", self.channel_layer) await self.channel_layer.group_add('programmers', self.channel_name) await self.accept() async def receive(self, text_data=None, bytes_data=None): print("Message received from the client", text_data) current_dir = os.getcwd() script = current_dir + '/' + 'test.py' try: p = subprocess.Popen(['python', script], stdout=subprocess.PIPE, bufsize=3) for line in iter(p.stdout.readline, b''): line = line.decode("utf-8").strip() await self.send(text_data=line) except subprocess.CalledProcessError as e: print(e) async def disconnect(self, code): print("Websocket disconnected", code) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Index</title> </head> <body> <h3>Count Page</h3> <textarea id="chat-log" cols="100" rows="20"> </textarea><br> <input type="button" value="Submit" id="script-run-submit"> <script> var ws = new WebSocket('ws://127.0.0.1:8000/ws/awsc/') ws.onopen = function() { console.log("Websocket connection opened") } ws.onmessage = function(event) { console.log("Message received … -
Django Package on virtual environment Malfunction after a certain time after reinstallation on cPanel share hosting server on deployment
I'm hosting a django project on a Shared hosting server cpnal that use CloudLinux. I've respect all the step and requirements to host a django project on a shared hosting server using passanger_wsgi.py. When I create a python application, getting a virtual enviromnent and installing all required package for my django project to work properly everything work very well and my application itself doesn't have any error and I have done all the test. But after a certain time, takes one or two weeks my python app get some packages error, some of them(mysqlclient, pillow, ....) and I'm obliged to delete the application, recreate it again and reinstall all the package to make everything work again. I've try to solve the error with the hosting service admin -> installing the lsapi and also install the python development package for Mysql. By my side I've tried to change the Mysql client package with pymsql and other. But still getting that error but it's periodic after one or two weeks after reinstallation. So please what can I do. I need some help before taking the decison of trying another hosting service. Is there something i'm missing, please help me. -
uwsgi harakiri is set but it doesn't work
I have configured the django project for run in the uwsgi.ini file and also set harakiri to increase timeout, but it doesn't work. Help me please [uwsgi] chdir = /app static-map = /static=/app/static module = svms.wsgi:application env = DJANGO_SETTINGS_MODULE=svms.settings uid = 1000 master = true # threads = 2 processes = 5 harakiri = 5000 max-requests = 1000 # respawn processes after serving 1000 requests vacuum = true die-on-term = true -
ImportError: attempted relative import beyond top-level package
I am using django framework, Here i have created the first_app application in django, i have created a simple view which will return hello world http response, I am trying to map this url in the urls.py, but it throws import_error by saying that " attempted relative import beyond top-level package", i have attached the project folder structure below for reference, How do i need import that view in urls.py file which are in above attached folder structure. I am using this pattern "from ..first_app import views" which throws error like attached format -
How does Django QuerySet cache work from get() method
I understand that query sets are cacheable and they get evaluated (DB gets hit) when the data set is first iterated on. But what happens with get() method (ex: MyModel.objects.get(id=1)). When does the DB get hit and when do we use a cached result? I am specifically interested in a flow with an API GET request (if that makes a difference). If I have several MyModel.objects.get(id=1 calls within the request lifecycle, will I be hitting the DB every time I call that get() or will I be using cached results ? -
some text always appear to replace my form when I try to upload my file in Django
[<InMemoryUploadedFile: istockphoto-147642455-612x612.jpg (image/jpeg)>, <InMemoryUploadedFile: istockphoto-157120359-612x612.jpg (image/jpeg)>, <InMemoryUploadedFile: istockphoto-160146563-612x612.jpg (image/jpeg)>] This text above appears to replace my file field when I click the upload button, and the form was working perfectly before and now this is happening Before I click the upload button After I click the upload button #model.py class CarImage(models.Model): make = models.ForeignKey(Makes, on_delete=models.CASCADE, related_name='makes') other_images_of_car = models.FileField(upload_to="car_images/", null=True) # views.py class ProductImages(forms.ModelForm): # other_images_of_car = forms.ImageField(widget=forms.ClearableFileInput(attrs={'class': 'form-control tick form-control-user', 'id':'formFile','multiple':True})) class Meta: model = CarImage fields =['other_images_of_car'] widgets = { 'other_images_of_car': forms.FileInput(attrs={'multiple': True}), } @login_required def cars_upload_all(request): if request.method == "POST": product_upload_more_image = request.FILES.getlist("other_images_of_car") product_upload = ProductsUpload(request.POST, request.FILES) product_upload2 =ProductsUpload2(request.POST, request.FILES) other =others(request.POST, request.FILES) if product_upload.is_valid() and product_upload2.is_valid() and other.is_valid(): car = product_upload.save(commit=False) car2 = product_upload2.save(commit=False) other2 = other.save(commit=False) car.owner = request.user car.save() car2.car = car car2.save() other2.others = car other2.save() for i in product_upload_more_image: CarImage.objects.create(make=car, other_images_of_car=i) messages.success(request, "Updated Successfully") return redirect("mobil:add") else: product_upload = ProductsUpload() product_upload_more_image = ProductImages() product_upload2 = ProductsUpload2() other =others() return render(request, "mobil/uploadcar.html", { "product_upload":product_upload, "product_upload_more_image":product_upload_more_image, "product_upload2": product_upload2, "other":other, }) Please help!!!!!!!!!! This stuff have been given me hard times THANKS I have removed all the attr properties I add, in the form class and widget I change from FileField to ImageField too -
How to get first record group by non relational join query, Django?
Model: class AD(model.Model): serial = models.CharField(unique=True, max_length=50) po_number = models.IntegerField(blank=True, null=True) class IDA(model.Model): serial = models.CharField(unique=True, max_length=50) class POR(models.Model): po_number = models.IntegerField(unique=True) is_closed_po = models.BooleanField(default=True) Raw Query: Select MIN(a.serial) as first_value, a.po_number From AD a Join IDA i ON a.serial=i.serial Join POR p ON a.po_number=p.po_number Where p.is_closed_po=0 Group By a.po_number What I'm trying to do in Django: AD.objects.extra( select={'is_closed_po': 'por.is_closed_po'}, tables=['por', 'ida'], where=['ad.po_number = por.po_number', 'ad.serial = ida.serial', 'is_closed_po = 0' ], ).values('serial', 'po_number') How can I achieve this in Django? Any help would be much appreciated. -
CS50 Web Project 2: How to save the starting bid
I am working on Project 2 for CS50 Web Programming course (an eBay-like e-commerce auction site in Django) and I would like to save the starting bid of an auction in order that compare it with later auctions. Please see my code below: models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Category(models.Model): categoryName = models.CharField(max_length=20) def __str__(self): return self.categoryName class Bid(models.Model): bid = models.IntegerField(default=0) # Bid for the listing # User who made the bid user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="userBid") class Listing(models.Model): title = models.CharField(max_length=30) description = models.CharField(max_length=100) imageUrl = models.CharField(max_length=500) isActive = models.BooleanField(default=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="user") category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True, related_name="category") price = models.ForeignKey(Bid, on_delete=models.CASCADE, blank=True, null=True, related_name="bidPrice") watchlist = models.ManyToManyField(User, blank=True, null=True, related_name="listingWatchlist") def __str__(self): return self.title class Comments(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="userComment") listing = models.ForeignKey(Listing, on_delete=models.CASCADE, blank=True, null=True, related_name="listingComment") comment = models.CharField(max_length=200) def __str__(self): return f"{self.author} comment on {self.listing}" Function for adding a bid (into views.py) def addNewBid(request, id): currentUser = request.user listingData = Listing.objects.get(pk=id) isListWatchList = request.user in listingData.watchlist.all() allComments = Comments.objects.filter(listing=listingData) newBid = request.POST['newBid'] isOwner = request.user.username == listingData.owner.username # The bid must be at least as large as … -
How to load manifest.json in django from react build folder? manifest.json not found error
Im developing a website using react bundled inside django servic static files. Everything appears to be working but my react is not working properly due to django not finding the manifest.json files. I have tried a few solutions that i found here in StackOverflow: mainly adding: path('manifest.json', TemplateView.as_view(template_name='manifest.json', content_type='application/json'), name='manifest.json') to my Django urls.py file and that worked to an extent, but then the error i get changes to: http://localhost:8000/logo192.png 404 (Not Found) Error while trying to use the following icon from the Manifest: http://localhost:8000/logo192.png (Download error or resource isn't a valid image) I also noticed that the react favicon was not loading so I found a fix here for that by using: <link rel="icon" href="http://localhost:8000/media/favicon.ico" /> instead of <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> Where the media folder is the folder im serving my urls.py file in django as my media root. That got the favicon working but the logo192.png not found error still persists, but when I tried the same method for the png file i get the same error. How do I fix it? -
Django Value Error: Cannot Assign Queryset must be instance, ManyToMany Relationship
I have built a model,OpeningDays, to manage a ManyToMany relationship (opening_days field in my BookingManagement model), since I wanted to add some additional data to each instance. I am using the 'through' approach as you can see from my models.py. Within my form, I have a CheckboxSelectMultiple, and for each day which is checked I want to create a model instance. However, I am getting the following error message: ValueError at /listings/createlisting/openingdays/b8s43t Cannot assign "<QuerySet [<DaysOfWeek: Monday>, <DaysOfWeek: Tuesday>, <DaysOfWeek: Wednesday>]>": "OpeningDays.daysofweek" must be a "DaysOfWeek" instance. The exception is being raise on this line of my code: if form.is_valid(): In order to try and solve this I have attempted to iterate through the queryset in my view with a for loop. However this hasn't worked either and I get the same error message. Any ideas how I can fix this? My models.py: class DaysOfWeek(models.Model): day = models.CharField(max_length=13) def __str__(self): return str(self.day) class BookingManagement(models.Model): listing = models.ForeignKey(Listing, verbose_name="Listing", on_delete=models.CASCADE) opening_days = models.ManyToManyField(DaysOfWeek, verbose_name="Opening Days", through="OpeningDays") booking_slots_per_day = models.IntegerField(verbose_name="Available booking slots per day", blank=True) max_bookings_per_time_slot = models.PositiveIntegerField(verbose_name="Maximum bookings per time slot", blank=False) standard_booking_duration = models.PositiveIntegerField(verbose_name="Standard booking duration in minutes", blank=False) min_booking_duration = models.PositiveIntegerField(verbose_name="Minimum booking duration in minutes", blank=True) max_booking_duration = models.PositiveIntegerField(verbose_name="Maximum … -
Django: Traceback error when running project
i keep this traceback even tho i have no modules called 'sitee' in my project, i double-checked, i don't even have a word that starts with 'sit' anyway. but i don't have any model named sitee My professor and I already tried lot of methods, such us reinstalling django, python and so on, i remember that i made another project called 'sitee' but it was on a different folder , in a different directory,already deleted it!!! i don't understand why it keeps showing it PS D:\djangoo\ECOMMERCE\backend> python manage.py runserver >> Traceback (most recent call last): File "D:\python\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "D:\python\Lib\site-packages\django\core\management\commands\runserver.py", line 74, in execute super().execute(*args, **options) File "D:\python\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\python\Lib\site-packages\django\core\management\commands\runserver.py", line 81, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: ^^^^^^^^^^^^^^ File "D:\python\Lib\site-packages\django\conf\__init__.py", line 102, in __getattr__ self._setup(name) File "D:\python\Lib\site-packages\django\conf\__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\python\Lib\site-packages\django\conf\__init__.py", line 217, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\python\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1128, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in … -
Role Based Access using groups in django and drf
I have 2 models named Menu-Items and Category. class Category(models.Model): slug = models.SlugField() title = models.CharField(max_length= 255, db_index=True) class MenuItem(models.Model): title = models.CharField(max_length= 255, db_index=True) price = models.DecimalField(max_digits=6, decimal_places=2, db_index=True) featured = models.BooleanField() category = models.ForeignKey(to=Category, on_delete=models.PROTECT) I have 3 types of users (Managers, Delivery Crew, and Customers). Manager-> Can perform CRUD on Menu-items. Delivery Crew (DC) -> can only view(get and list) menu-items. Customer -> can only view category and menu-items I have done authentication using Djoser. I have created 3 groups of users(managers, dc, and customers) and have added the necessary permissions to the groups. Now how do I ensure that when a manager logs in he is able to perform the actions that he is allowed to and the same for Dc and customers? Here's what I did. I created 2 permissions isManager, and isDC. class IsManager(BasePermission): def has_permission(self, request, view): return request.user.groups.filter(name= "Manager").exists() class IsDeliveryCrew(BasePermission): def has_permission(self, request, view): return request.user.groups.filter(name= "Delivery Crew").exists() and in my views class MenuItemManagerView(ModelViewSet): queryset = MenuItem.objects.all() serializer_class = MenuItemSerilaizer permission_classes = [IsAuthenticated, IsManager] class MenuItemDeliveryCrewView(ListAPIView, RetrieveAPIView): queryset = MenuItem.objects.all() serializer_class = MenuItemSerilaizer permission_classes = [IsAuthenticated, IsDeliveryCrew] Now, it is doing the basic task of checking if the logged-in user is …