Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Password is not hashed on User model update
I have extended the AbstractUser model in django. When I post the SignUp form from Postman, the password gets hashed. But after sending the Put method in Postman for changing the password, the password gets showed in Django admin as it is not getting hashed. Models.py class User(AbstractUser): """This Class is used to extend the in-build user model """ ROLE_CHOICES = (('CREATOR','CREATOR'),('MODERATOR','MODERATOR'),('USERS','USERS')) GENDER_CHOICES = (('MALE','MALE'),('FEMALE',"FEMALE"),('OTHER','OTHER')) date_of_birth = models.DateField(verbose_name='Date of Birth', null=True) profile_image = models.ImageField(upload_to='media/profile_images', verbose_name='Profile Image', default='images/default.webp', blank=True) bio = models.TextField(verbose_name='Bio') role = models.CharField(max_length=10, verbose_name='Role', choices=ROLE_CHOICES) gender = models.CharField(max_length=6, verbose_name='Gender', choices=GENDER_CHOICES) Serializers.py from django.contrib.auth import get_user_model User = get_user_model() class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('first_name','last_name','username','password','email','date_of_birth', 'profile_image','bio','role','gender') extra_kwargs = {'is_active':{'write_only':True}, 'password':{'write_only':True}} def create(self, validated_data): return User.objects.create_user(**validated_data) Views.py from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope, TokenHasScope from users.serializers import UserSerializer from users.models import User class UserAPI(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] I tried it in these way also by overwriting the serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('first_name','last_name','username','password','email','date_of_birth', 'profile_image','bio','role','gender') extra_kwargs = {'is_active':{'write_only':True}, 'password':{'write_only':True}} def create(self, * args, ** kwargs): user = super().create( * args, ** kwargs) p = user.password user.set_password(p) user.save() return user def update(self, * args, ** kwargs): user = super().update( … -
how to resolve (1045, "Access denied for user 'User'@'IP or host' (using password: YES)") when build django docker container?
Well, I have multiple databases in django project. One is default and second istest_dev. i have created docker container. and then everything went well till building the container. after that When I try to call my django app api which is using test_dev db for reading data. I have encountered: OperationalError at /api/projects/ (1045, "Access denied for user 'test_dev'@'133.98.72.111' (using password: YES)") In settings file, my databases configuration: { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': Path(__file__).resolve().parent.parent / 'db.sqlite3', }, "test_dev" : { 'ENGINE': 'django.db.backends.mysql', 'NAME': "test_dev", 'USER': 'user', 'PASSWORD': 'db_password', 'HOST': '?=hosted_domain', 'PORT': '3306', 'SSL': True } } If you know any solution. Please help me out of this. Soon I have to put things on production.. -
Connect django+reactjs+firebase
How to send form data to firebase database via Django I connected Django to firebase ,how would I connect ReactJs to Django to send form data to firebase database using validation in python. If anyone has Github profile please paste it here so that I can take reference. -
Can't install opencv package in a Raspberry pi
So I am doing a face recognition project in a Raspberry Pi. It is a django project and when I run the server I get this error: AttributeError: module 'cv2' has no attribute 'face' I searched for the error and I came up with that I needed to install opencv-contrib-python The problem is that when I try to install it the download gets to 99% and I get this: 'pip3 install opencv-contrib-pyt…' terminated by signal SIGKILL (Forced quit). Does anyone know why this happens? how can I fix this? help is much appreciated -
How to create dynamic URL in Django when form is submitted
I am building a website in django where user search for student data by entering the roll number of the student. For example if user enters the roll number 001 in the form then student data should be fetch from database and Url should be https://www.studentdata.com/001 Similarly if user enters roll number 003 then the url should be https://www.student.com/003 and so on. I want to build website where I need to show thousands of student data. -
JSONDecodeError at / Expecting value: line 1 column 1 (char 0) when try to return response in a django rest_framework
I'm new to python rest_framework. I am trying to create a django website with two Apps. The first App has an HTML form which gets a city name from the user and then sends a request to the API in the second App, calls WeatherApp. In the WeatherApp I read data from database and serialize it but when trying to return response, I get this error: JSONDecodeError at / Expecting value: line 1 column 1 (char 0) This is the first App views: def index(request): context = {'form': form} if request.method == 'POST': form = CityForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] url = "http://127.0.0.1:8000/city/{}" city_weather = requests.get(url.format(name)).json() This is the WeatherApp views: def myfunc(self, cityname): query = City.objects.filter(name = cityname)[0] serializer = CitySerializer(query) return Response(serializer.data) This is the serializer: class CitySerializer(serializers.ModelSerializer): class Meta: model = City fields = ("id", "name", "temperature") And this is my model: class City(models.Model): name = models.TextField(max_length=150) temperature = models.IntegerField(max_length=200, default=40) LastUpdate = models.DateTimeField(default= datetime.now) def __str__(self) -> str: return self.name When I debug the code, the error appears at return self.name in the model. Any help would be appreciated. -
How to upload a folder into a model field(In Admin panel), which will create an object for each file inside of that folder in Django?
I have a folder with 100 plus audio files from the same author. It would take time for me to upload each file separately to create 100 plus objects. What I want to do is in a model of the Author I want to have a field where I can upload a folder with all the audio files, which will then create a separate object for each audio file in that folder. -
Django OneToOneField Default value?
Hello Django OneToOneField Default value Inventory model class Inventory(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) energy = models.OneToOneF`ield(Product, default="Products.energy", null=True, on_delete=models.CASCADE) Products model class Product(models.Model): name = models.CharField(max_length=255) cost_for_sale = models.IntegerField() cost_for_buy = models.IntegerField() def __str__(self): return f'{self.name}' -
Error "ModuleNotFoundError: No module named 'psycopg2'" when deploying Django app to Google App Engine
I'm working on a Django application and using Fabric for deployment. When I deployed the apps to staging in Google App Engine using fab testing, I got this error: Updating service [staging] (this may take several minutes)...failed. ERROR: (gcloud.app.deploy) Error Response: [9] An internal error occurred while processing task /app-engine-flex/flex_await_healthy/flex_await_healthy>2022-01-01T09:48:30.226Z15496.fj.0: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/env/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/env/lib/python3.6/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/opt/python3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/env/lib/python3.6/site-packages/django/contrib/postgres/apps.py", line 8, in <module> from .signals import register_type_handlers File "/env/lib/python3.6/site-packages/django/contrib/postgres/signals.py", line 3, in <module> import psycopg2 ModuleNotFoundError: No module named 'psycopg2' I'm sure the psycopg2 has been installed successfully earlier. Here's the list installed dependencies after checking by pip list: ... platformdirs 2.4.0 prompt-toolkit 3.0.24 … -
django rest frame work, i was trying to create an exchange rate that compare the first currency to the second currency and print the value of second
from Django .shortcuts import render import requests from exchange rate .models import Exchange rate from . serialize import Exchange rate Serialize from rest framework .response import Response from rest_ framework import view sets from .models import Exchange rate class Exchange value(view sets .Model View Set): query set=Exchange rate .objects .all() serialize _class = Exchange rate Serialize def get(request, rate1, rate2): if request .method =='POST': url="https://api.exchangerate-api.com/v4/latest/USD" res=requests .get( URL ) result =res .Jason () try: if rate1 in result: return render(request ,result[rate2]) except Exception as e: print("currency could not be process") -
Why does this show when i try to add image on Django?
Cant add image into user This is what it show in the page : <django.db.models.fields.files.ImageField> add i need the bar that add the picture, the forms and models seem correct and i install the pillow enter image description here -
How to get original host in django using proxy?
I use nginx proxy for a django application. And I want request.META['HTTP_HOST'] parameter to get my real host. So I use USE_X_FORWARDED_HOST setting parameter. But request.META['HTTP_HOST'] still gets wrong value from proxy. nginx location / { proxy_set_header X-Forwarded-Proto http; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://backend:8000; } django settings USE_X_FORWARDED_HOST = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') parts of request.META variable 'HTTP_HOST': 'backend:8000', 'HTTP_X_FORWARDED_PROTO': 'http', 'HTTP_X_FORWARDED_HOST': 'localhost', 'HTTP_X_FORWARDED_SERVER': 'localhost', 'HTTP_X_FORWARDED_FOR': '192.168.240.1' Why USE_X_FORWARDED_HOST setting doesn't work? I use Django 4.0. -
About TailwindCSS with Django
I want to use Tailwind CSS in Django project. When googling, I found following two ways. Use CDN Use Tailwind CLI tool Using CDN is simpler, so I will use CDN, but doc says that CDN is not the best way. Then I have questions. Why Using CDN is not the best choice? Which is better? -
django: html submit form and display result in smae page without jumping/rereshing into new page
I am new to django and html. below is my first test web page of a simple online calculator. I found a problem that when clicking the "submit" button, it tends to jump to a new web page or a new web tab. this is not what I want. Once the user input the data and click "submit" button, I want the "result" field on the page directly show the result (i.e. partially update only this field) without refresh/jump to the new page. Also I want the user input data kept in the same page after clicking "submit". I saw there might be several different ways to do this work, iframe/AJAX. However, I have been searching for answers for 5 days and none of the answers really work for this very basic simple question!! html: <form method="POST"> {% csrf_token %} <div> <label>num_1:</label> <input type="text" name="num_1" value="1" placeholder="Enter value" /> </div> <div> <label>num_2:</label> <input type="text" name="num_2" value="2" placeholder="Enter value" /> </div> <br /> <div>{{ result }}</div> <button type="submit">Submit</button> </form> view.py def post_list(request): result = 0 if request.method == "POST": num1 = request.POST.get('num_1') num2 = request.POST.get('num_2') result = int(num1) + int(num2) print(request.POST) print(result) context = { 'result': result } return render(request, 'blog/post_list.html', … -
Import "django.urls" could not be resolved from sourcePylancereportMissingModuleSource
I am getting default django homepage while I have linked urls perfectly. and if i run it is saying that django module is not present (Import "django.urls" could not be resolved from sourcePylancereportMissingModuleSource). While I have started the project with Django, -
Why the ip address captured by HTTP_X_FORWARDED_FOR is diferrent from the address shown in the device
I want some clarification regarding ip address captured by HTTP_X_FORWARDED_FOR. In my website I am storing the ip address of the visitors to count the number of visits. The code that I am using for this is this function is used to capture the ip def get_ip(request): try: ip_forward = request.META.get('HTTP_X_FORWARDED_FOR') if ip_forward: ip = ip_forward.split(",")[0] print("returning forwarded for ip address", ip) elif request.META.get('HTTP_X_REAL_IP'): ip = request.META.get('HTTP_X_REAL_IP') print ("returning REAL_IP ", ip) else: ip = request.META.get('REMOTE_ADDR') print("returning remote address ", ip) except: ip= "" return ip after the above function is called on the index view it is then passed to this function for storing the ip def visitor_count(ip): visitor = VisitorCount() visitor.ip = ip visitor.date_of_record = datetime.now() if VisitorCount.objects.all().filter(ip = visitor.ip ,date_of_record__icontains= datetime.today().date()).exists(): pass print("the ip", visitor.ip,"recorded on", visitor.date_of_record ,"already exists and wil not be saved") else: print('this is the ip address of the user that has been saved', visitor.ip) visitor.save() return "saved" as you can see it prints what it is doing. My site is hosted in heroku (if that metters). I went through some satckoverflow questions but could not find an ans to what I wanted to. Now suppose when I am going to the site, and … -
resubmitting some fields inside a form resets choicefields
I made a form inside a user detail page where the superuser can fill them or update them. this is the model form I'm using: class PsychologicInfo(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) question1 = models.TextField(null=True, blank=True) question2 = models.TextField(null=True, blank=True) question3 = models.TextField(null=True, blank=True) info1 = models.CharField(max_length=64, choices=SURVEY_INFO1_CHOICES, blank=True) info2 = models.CharField(max_length=64, choices=SURVEY_INFO2_CHOICES, blank=True) info3 = models.CharField(max_length=64, choices=SURVEY_INFO3_CHOICES, blank=True) final_assessment = models.TextField(null=True, blank=True) is_interviewed = models.BooleanField(default=False) def save(self, *args, **kwargs): if self.info1: self.is_interviewed = 'True' super(PsychologicInfo, self).save(*args, **kwargs) however, when I enter the user detail page and try to update some fields, for instance, the final assessment field, all the choice fields(info1,info2,info3) get reset! but other fields stay the same so whenever I want to edit a field, I need to fill those choice fields again. this is the view I wrote: class PsychologicInfoView(FormMixin, DetailView): model = PsychologicInfo template_name = 'reg/psychologic-info.html' form_class = PsychologicInfoForm def get_success_url(self): return reverse('psychologic-info', kwargs={'pk': self.object.pk}) def get_context_date(self, **kwargs): context = super(PsychologicInfoView, self).get_context_data(**kwargs) context['form'] = PsychologicInfoForm() return context def post(self, request, pk): self.object = self.get_object() form = PsychologicInfoForm(request.POST, instance=get_object_or_404(PsychologicInfo, id=pk)) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): f = form.save(commit=False) f.user = self.object.user f.save() return super(PsychologicInfoView, self).form_valid(form) and this is my … -
django.core.exceptions.ImproperlyConfigured: Set the DATABASE_URL environment variable
I annotate text data (building data sets for named entity recognition models) using AlpacaTag, which was designed using Python on Django. I followed the steps of GitHub's[[AlpacaTag]][1] Reamde. When I run the command python manage.py migrate (I come to find information, to know this is the Django's command of database migration), The program threw an exception: Traceback (most recent call last): File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/environ/environ.py", line 367, in get_value value = self.ENVIRON[var] File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/os.py", line 669, in __getitem__ raise KeyError(key) from None KeyError: 'SECRET_KEY' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/core/management/base.py", line 86, in wrapped saved_locale = translation.get_language() File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 254, in get_language return _trans.get_language() File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/utils/translation/__init__.py", line 57, in __getattr__ if settings.USE_I18N: File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/home/duzx21/miniconda3/envs/alpacatag/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, … -
Auto fill rate field depending on the option selected in django
from django.db import models Create your models here. class Course(models.Model): course = models.CharField(max_length=50, blank=True, null=True) duration = models.CharField(max_length=50, blank=True, null=True) charges = models.IntegerField(default= '0', blank=True,null=True) description = models.CharField(max_length=200, blank=True, null=True) def __str__(self): return self.course class Meta: db_table = "course" class Student_Details(models.Model): gender = ( ("1", "Male"), ("2", "Female"), ("3", "Other"), ) course = models.ForeignKey(Course, on_delete=models.CASCADE,blank=True) roll = models.IntegerField(default= '0', blank=True,null=True, unique=True) dob = models.DateField(blank=True,null=True) stu_name = models.CharField(max_length=50, blank=True, null=True) contact_no = models.CharField(max_length=50,blank=True, null=True) email = models.EmailField(max_length=50,blank=True, null=True) gender = models.CharField(max_length=50, blank=True, null=True, choices=gender) state = models.CharField(max_length=50, blank=True, null=True) city = models.CharField(max_length=50, blank=True, null=True) pin = models.IntegerField(blank=True, null=True) address = models.CharField(max_length=50, blank=True, null=True) admission_date = models.DateField(auto_now_add=False, auto_now=False, blank=True, null=True) last_updated = models.DateTimeField(auto_now_add=False, auto_now=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) def __str__(self): return self.stu_name class Meta: db_table = "student_detail" class StudentResult(models.Model): select_student = models.ForeignKey(Student_Details, on_delete=models.CASCADE,blank=True) # name = models.CharField(max_length=55,blank=True, null=True) course = models.CharField(max_length=55,blank=True, null=True) marks = models.IntegerField() full_marks = models.IntegerField() def __str__(self): return self.name class Meta: db_table = "student_result" -
Search Functionality
django, this search functionality is working but data is not displaying on the template. I'm beginner in django. Please help me view.py: def search(request): search_machinename = request.GET.get('q') if (search_machinename is not None) and search_machinename: machinename = Item.objects.filter(QuerySet(machinename__icontains=search_machinename) | QuerySet(operationno__icontains=search_machinename)) if not machinename: machinename = Item.objects.all() context = {'machinename': machinename} return render(request, 'usermaster/item-form.html', context) Template file: item-form.html: Webpage of this template <form action="{{url.search}}" method='get' value='{{ request.get.q }}' enctype="multipart/form-data"> {% csrf_token %} {{fields}} <input type="text" name="q" value='{{ request.GET.q }}'> <button type="submit">Search</button> <table> {% for data in machinename %} <tr> <td>{{ data.machine_name }}</td> <td>{{ data.operation_no }}</td> </tr> {% endfor %} </table> </form> code is working but it is not displaying on webpage -
Django customising template for form
SuspiciousOperation at /signup/ ManagementForm data is missing or has been tampered. Request Method: POST Request URL: http://localhost:8000/signup/ Django Version: 3.2.9 Exception Type: SuspiciousOperation Exception Value: ManagementForm data is missing or has been tampered. Exception Location: C:\Users\arund\Desktop\Code\Django\portfolio-project\venv\lib\site-packages\formtools\wizard\views.py, line 282, in post I was trying to change my templates by adding 2 buttons for the forms and got this error. It displays the two buttons but everytime I click one it doesn't submit correctly. I want to make the is_doctor field in the modal set to false or true depending on the button click. from django.shortcuts import redirect, render from .forms import PickUserType, SignUpForm, UserProfileForm from django.contrib.auth import login, authenticate from formtools.wizard.views import SessionWizardView def show_message_form_condition(wizard): # try to get the cleaned data of step 1 cleaned_data = wizard.get_cleaned_data_for_step('0') or {} # check if the field isDoctor was checked. return cleaned_data.get('is_doctor')== False def process_data(form_list): form_data = [form.cleaned_data for form in form_list] print(form_data) return form_data WIZARD_FORMS = [("0", PickUserType), ("1" , SignUpForm), ] TEMPLATES = {"0": "pickUserType.html", "1": "createUser.html"} class ContactWizard(SessionWizardView): def done(self, form_list, **kwargs): process_data(form_list) return redirect('home') def get_template_names(self): return [TEMPLATES[self.steps.current]] forms.py from django import forms from django.core.files.images import get_image_dimensions from django.forms.widgets import RadioSelect from pages.models import Profile from django.contrib.auth.forms import UserCreationForm … -
Django + Channels: message interrupted by posting
I am coding a page that contains a form to create a game (several field) and just below a list of all the created games. When I post the new game, I would like the list of games to refresh for all the connected users of the page. My consumer.py: def receive(self, text_data): games = serialize_games() # Send new game info to Lobby async_to_sync(self.channel_layer.group_send)( 'Lobby', { 'type': 'message_to_lobby', 'message': games, }) def message_to_lobby(self, event): print('messages sent to lobby') message = event['message'] self.send(text_data = message) In my template I have a jquery portion of code that sends message to the websocket just prior the post is submitted: $("#create_game_form").submit(function(e) { alert('sent');LobbySocket.send(JSON.stringify({ 'message': 'reload' }));}); During the posting, the receive function is well called, whereas the message handler (message_to_lobby) is not, since the rendering in the view section disconnect the websocket before... Would it help to use async functions instead (I don't really see why...)? Or maybe Django + Channels are not meant to make POST and channels work together? Otherwise, I may have the possibility to ask for the consumer to send an update signal to group users very 2sec or something like this, but I don"t find it very elegant. -
How to create blob url from normal url in react
I'm building a website that provides quality videos for students. So I want a feature that is students don't see the URL of the video. How I implement that feature on Reactjs. I used technologies Django and ReactJS. -
What traffic level is good for Sqlite?
I'm using Sqlite3, and I want to be sure it's good for me. The traffic I kinda get will be 'round 2500 - 5000 people * how many apartments choose to use the service, because this is for communities, like an apartment complex, to use. I'm using Django, and the things that I had developed using Sqlite on my local don't work well with the Postgres I have on my server. So I thought that I could just use Sqlite and migrate to Postgres only later. So I want to know until when can I use Sqlite? -
DRF - Using custom permission class as default permission class
In my django project, I have created an app called 'base' in which the files are structured as follows: backend | |--app (created via startproject) | | | |--settings.py | |--base (created via startapp) | |--permissions | | | |--init.py | | | |--IsActivatedAccount.py | |--views |--serializers As you can see, I have created a 'permissions' package in which I have created a custom permission class called 'IsActivatedAccount'. Here is how the files look: init.py: from .IsActivatedAccount import * IsActivatedAccount.py: from rest_framework.permissions import BasePermission from ..models import * class IsActivatedAccount(BasePermission): message = 'Email verification pending' def has_permission(self, request, view): return request.user.status != User.Status.PENDING_ACTIVATION Now, I am trying to use this permission as the default permission class in combination with IsAuthenticated permission class from django-rest-framework. Here is how I have added it in settings.py of the project. settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', 'base.permissions.IsAccountActivated', ], } Due to 'base.permissions.IsAccountActivated', the server is failing to start and here is the error that I am getting: Exception in thread django-main-thread: Traceback (most recent call last): File "/home/mouli/.local/share/virtualenvs/backend-yIk9pObI/lib/python3.8/site-packages/django/utils/module_loading.py", line 30, in import_string return cached_import(module_path, class_name) File "/home/mouli/.local/share/virtualenvs/backend-yIk9pObI/lib/python3.8/site-packages/django/utils/module_loading.py", line 16, in cached_import return getattr(modules[module_path], class_name) AttributeError: module 'base.permissions' has no …