Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Q object for CheckConstraint
I'm trying to write a Q object that says Either one of these 4 fields is not null, or this field is not true I have a normalized table with 4 category of prices, and an available flag price_A price_B price_C price_D available_on_the_store I want at least one of these prices to be populated before it is possible to mark it as available_on_the_store on a CheckConstraint with a Q object I can easily do this with a huge Q chain or can easily write it in .clean() and force it in the python side, yet I want it to be in the database level; so please answer accordingly. -
Migrations from independent Django application to Django project
I have a django project which has few model files. I also have two non-Django projects which also interact with the same database. To make use of Django's ORM into other projects I have separated models into an independent Django application. This Django application has its own setup.py file and is pushed to private FRS. I have tested this application with all the projects and it works fine. However, I don't know how to handle migrations. What should be the right approach to create and apply migrations? Where should this migration files reside? Here is the example structure of the application. django-model-application | |-----setup.py |-----setup.cfg |-----requirements.txt |-----django-model-application |-------migrations |--------ALL THE INITIAL MIGRATION FILES |-------__init__.py |-------admin.py |-------apps.py |-------models.py |-------models_customer.py |-------models_producer.py |-------tests.py |-------views.py Now I would like to use the above django application in a regular django project. Everything works fine but I am not getting the right way to handle the migrations. I appreciate all the help. Thank you! -
How to configure urls.py in django to redirect to another file's urls?
I'm following a django tutorial that is a little outdated and in the urls.py file of the first app's directory we need to configure where to direct django to for any url starting with 'notes/'. There are two separate 'apps' inside the project. I'm in the first one, not notes. This is the code currently. I added include to import statement: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path(url(r’^notes/‘, include('notes.urls'))), ] Inside the urlpatterns object, on the first line, path('admin/', admin.site.urls), comes predefined, but I need to add a redirect such that django goes to a different app, called 'notes' and searches there for its entry point, since all of the urls will begin with ‘notes/’. The tutorial says to use a regular expression and uses this code: url(r’^notes/‘, include(notes.urls)) so that any url that starts with 'notes/' should be redirected to this other file notes.urls. However the predefined ones that currently come out of the box with a django project start with path. I enclosed my notes/n redirect line in path, but not sure if this is correct. Should I instead directly write: url(r’^notes/‘, include(notes.urls)) Also, do I need to delete the … -
Creating a nested class in django and running a helper method
I've the following User model, class User(AbstractBaseUser, PermissionsMixin, Base): username = models.CharField(max_length=255, null=False) email = models.CharField(max_length=255, null=False, unique=True) user_type = models.CharField(max_length=255, null=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=False) And this is my Meeting model class Meeting(Base): meeting_code = models.CharField(max_length=255) owner = models.ForeignKey(User, related_name='meetings', on_delete=models.CASCADE, null=True, blank=True) members = models.ManyToManyField(User, related_name='meeting_set', null=True, blank=True) start_time = models.DateTimeField(auto_now_add=True) end_time = models.DateTimeField(null=True) When a meeting is created, I want to run this helper function to generate a meeting code def generate_meetingid(): return ''.join(random.choices(string.ascii_uppercase, k=16)) This is my meeting serializer, class MeetingSerializer(serializers.ModelSerializer): owner = UserSerializer(required=True) class Meta: model = Meeting fields = ['id', 'meeting_code', 'owner', 'members', 'start_time', 'end_time', ] My questions is how do I write the Meeting View set that adds the creating user as the owner and also runs the helper method to create the meeting code. In essence, I'm trying to complete this view, class MeetingViewSet(viewsets.ModelViewSet): queryset = Meeting.objects.all() serializer_class = MeetingSerializer def perform_create(self, serializer): serializer.save() -
Django: Integrating recaptcha on LoginView using django-recaptcha
Library used: django-recaptcha forms.py class LoginAuthenticationForm(AuthenticationForm): captcha = ReCaptchaField() urls.py path('login/', auth_views.LoginView.as_view(template_name='warders/login.html', authentication_form=LoginAuthenticationForm), name='login'), Issues I have: Currently the site displays correctly the log in page with its recaptcha box, but it doesn't log in user, it keeps redirecting pages or reloading the same page if information is wrong. -
Django Migrations - how can i make a data migration with Foreign Key
Problem I'm trying to populate a Database using django migrations. My Provincia model works fine, but my Municipio model show me this error: ValueError: Cannot assign "<Provincia: Pinar del Río>": "Municipio.provincia" must be a "Provincia" instance. I have created the migration files using the command manage.py makemigrations --empty app_name and renaming later for a better understanding. Code Here is my models file: class Municipio(models.Model): nombre = models.CharField(verbose_name=_('Nombre'), primary_key=True, max_length=50) provincia = models.ForeignKey(to=Provincia, on_delete=models.PROTECT, related_name='municipios') class Provincia(models.Model): nombre = models.CharField(verbose_name='Nombre', primary_key=True, max_length=60) nombre_corto = models.CharField(verbose_name=_('Nombre Corto'), max_length=3, unique=True) My custom migrations look like this: 0002_populate_table_provincia.py def populate(apps, schema_editor): Provincia = apps.get_model('l10n_cuba', 'Provincia') for provincia in PROVINCIAS: prov = Provincia.objects.create(nombre=provincia['nombre'], nombre_corto=provincia['nombre_corto']) prov.save() class Migration(migrations.Migration): dependencies = [ ('l10n_cuba', '0001_initial'), ] operations = [ migrations.RunPython(populate) ] 0003_populate_table_municipio.py def populate(apps, schema_editor): Municipio = apps.get_model('l10n_cuba', 'Municipio') for municipio in MUNICIPIOS: mun = Municipio.objects.create(nombre=municipio['nombre'], provincia=municipio['provincia']) # mun = Municipio.objects.create(**municipio) # This doesn't work either mun.save() class Migration(migrations.Migration): dependencies = [ ('l10n_cuba', '0002_populate_table_provincia'), ] operations = [ migrations.RunPython(populate) ] PROVINCIAS and MUNICIPIOS are lists loaded from a different file that the migrationg file, that in each row have a dict with the values for the object. I tried to create the object, and put it directly in … -
Using multiple receivers in one Consumers file
I have two notifications that I need to send via websocket to the same user consecutively. However it looks like the data is being overwritten on the JS side and before any conditional logic is firing. I am assuming this is the case because my Consumers logic must be off. The code below results in my js overriding the JSON object before any logic can fire js notifySocket.onmessage = function(e) { let data = JSON.parse(e.data); if (data.requests_count > 0){ //DOES NOT FIRE EVEN THOUGH CONSOLE CONFIRMS REQUEST COUNT } if (data.new_requests > 0){ //FIRES CORRECTLY } View A if form.is_valid(): channel_update_requests_mentions_count(user_to_notify) channel_new_request(user_to_notify) View B if form.is_valid(): channel_update_requests_mentions_count(user_to_notify) notify.py def channel_update_requests_mentions_count(user): ... channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( str(user.id), { "type": "update_count", "requests_count": requests_count, "mentions_count": mentions_count, }, ) def channel_new_request(user): ... channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( str(user.id), { "type": "notify", "new_requests": requests, "new_mentions": mentions, }, ) consumers.py class NotificationConsumer(WebsocketConsumer): def connect(self): if self.scope["user"].is_anonymous: self.close() else: self.group_name = str(self.scope["user"].pk) async_to_sync(self.channel_layer.group_add)( self.group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.group_name, self.channel_name ) def notify(self, event): new_requests = event['new_requests'] new_mentions = event['new_mentions'] # Send message to WebSocket self.send(text_data=json.dumps({ 'new_requests': new_requests, 'new_mentions': new_mentions, })) def update_count(self, event): requests_count = event['requests_count'] mentions_count = event['mentions_count'] # Send message to WebSocket … -
Syntax of passing arguments into args in reverse()
The following is a snippet from Django official tutorial. Link is here https://docs.djangoproject.com/en/3.0/intro/tutorial05/ def test_future_question(self): future_question = create_question(question_text ="future question", days=30) url = reverse('polls:detail',args = (future_question.id,)) args = (future_question.id,) This syntax is very foreign to me. Why do we need brackets and coma here? Thank you for your help! -
Printing a list created by a Python function in Django
I want to take the list created by the following function (listofcounters) and print that out on an HTML Django template. I know that in the HTML I'll need {% for i in listofcounters %} {{ something here maybe? }} {% endfor %} But really the confusion is coming from where the function goes (in views.py? or is it a model?) and then how to get it so the HTML page can read it. Also, I'm aware that what I might be doing isn't the "best" way to present this information, but this is for me to understand Django better by creating a toy project that I'm interested in. It's not for a "real" site. So, in saying that, I ask that you don't suggest anything too far outside my original question. That being "here's my function, how can I get its output in HTML form?" unless you feel it's impossible to do so. from mtgsdk import Card def findcounters(): listofcounters = [] cards_from_set = Card.where(set='iko').all() for card in cards_from_set: if "counter target" in str(card.text).lower(): listofcounters.append(card.name) listofcounters = list(dict.fromkeys(listofcounters)) return listofcounters -
KeyError at /accounts/signup/ 'sociallogin' when using Django All Auth
After I setup Django All Auth, anytime I click on the SignUp button, it gives me this error: KeyError at /accounts/signup/ 'sociallogin' The Login works fine. I have tried downgrading the AllAuth version, but that did not help. This is my first time using the Django Allauth package. Furthermore, is it compulsory I setup providers (e.g. Google) before I can use the Allauth package? Error KeyError at /accounts/signup/ 'sociallogin' Request Method: GET Request URL: http://127.0.0.1:8000/accounts/signup/ Django Version: 3.0.7 Exception Type: KeyError Exception Value: 'sociallogin' Exception Location: C:\Users\user1\.virtualenvs\testproject-L2l8zpjO\lib\site-packages\allauth\socialaccount\forms.py in __init__, line 15 Python Executable: C:\Users\user1\.virtualenvs\testproject-L2l8zpjO\Scripts\python.exe Python Version: 3.8.2 Python Path: ['C:\\Users\\user1\\Documents\\Programming stuff\\django\\testproject', 'C:\\Users\\user1\\.virtualenvs\\testproject-L2l8zpjO\\Scripts\\python38.zip', 'c:\\python37\\DLLs', 'c:\\python37\\lib', 'c:\\python37', 'C:\\Users\\user1\\.virtualenvs\\testproject-L2l8zpjO', 'C:\\Users\\user1\\.virtualenvs\\testproject-L2l8zpjO\\lib\\site-packages'] settings.py (Some lines that I don't think are essential to show have been removed to reduce the amount of code) from decouple import config, Csv import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', cast=bool) ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) INSTALLED_APPS = [ # Default 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # 3rd party # All Auth 'allauth', 'allauth.account', … -
Django My heroku account isn't authorized to change my own app
An error comes up when trying to push changes onto heroku, it says I am not authorized to access my project, even though I created it. I was able to push changes to heroku before logging in, but after I logged in it doesnt allow changes from my bash console. When I log out it still won't accept changes. Heres the error message When trying the command in the Heroku documentation, I receive this error -
How to create a user with flag is_staff = true in djoser
I want to access Django administration after create a user with djoser -
How to use traditional SQL queries in Django (instead of ORM)?
I am learning Django right now, and I've just watched a tutorial on database interaction. The instructor didn't even mention SQL, and simply taught the ORM way of communicating with databases in Django. I dislike ORM a lot, and prefer to use the traditional SQL. Can I? If so, how can I use traditional SQL in a Django Web App (FYI I use PostgreSQL)? Thanks. -
Get Django to return only the first 50 characters of text stored as a models.TextField()
In Python Crash Course chapter 18 we make a Learning Log website. I can't make this return just the first 50 characters of a >50 character long entry when I go into the Learning Log website that we make (through localhost:8000). It doesn't show the ellipsis either, it just shows the whole entry. from django.db import models from django.contrib.auth.models import User class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): """Return a string representation of the model.""" return str(self.text) class Entry(models.Model): """Something specific learned about a topic""" topic = models.ForeignKey(Topic, on_delete=models.PROTECT) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """Return a string representation of the model.""" if len(self.text) > 50: return f"{str(self.text)[:50]}..." else: return f"{str(self.text)}" It is the same whether I include the if len(self.text) > 50 statement or not. My code differs somewhat from the book in that: I use on_delete=models.PROTECT, as I understand that CASCADE can cause weird issues like accidentally getting something deleted that you didn't intend to delete I use str(self.text) instead of just self.text in the __str__ definitions; if I don't it raises a pylint error "Value 'self.text' … -
Create token authentication with the user model rest framework
I am trying to create an authentication token for my model called Persona, but the Token table asks me for a user_id as a foreign key, is there any way I can create tokens with a different User model? This is my Person model: class Person(AbstractBaseUser): first_name = models.CharField('Nombre', max_length = 100) last_name = models.CharField('Apellido', max_length = 100) username = models.CharField('Username', max_length = 50) nickname = models.CharField('Nickname', max_length = 50, null = True) gener = models.IntegerField('Genero') phone = models.CharField('Teléfono', max_length = 13, null = True) birtday = models.DateField('Cumpleaños', auto_now=False, auto_now_add=False, null = True) address_id = models.IntegerField('Dirección', null = True) address_birtday_id = models.IntegerField('Lugar de Nacimiento', null = True) email = models.EmailField('Correo', max_length=254) password = models.CharField('Password', max_length = 700) photo = models.CharField('Foto', max_length=254, null = True) about_me = models.CharField('Biografía', max_length = 1000, null = True) active = models.IntegerField('Activo') connected = models.IntegerField('Conectado') person_type_id = models.IntegerField('Tipo', null = True) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) USERNAME_FIELD = 'username' def __str__(self): return '{0},{1}'.format(self.last_name, self.first_name) This is my view: class LoginPersonAPI(APIView): def post(self, request): serializer = LoginPersonSerializer(data = request.data) if serializer.is_valid(): person = Person.objects.filter(username=serializer.validated_data['username']) token = Token.objects.get_or_create(key = person[0].id) if token: return Response(token[0]) return Response(person[0].id, status = status.HTTP_201_CREATED) else: return Response(serializer.errors, status … -
Confirm Form Resubmission with Context Required Django
I have an account page that lets users edit their accounts. When the save button is pressed, I run the following code: request.user.first_name = request.POST['first_name'] request.user.last_name = request.POST['last_name'] request.user.save() context['alert'] = { 'title': "Your information has been updated", 'color': 'primary', } As you can see, I pass in context that, in my template, renders as an alert. However, when I refresh the page, it says: Confirm Form Resubmission How can I get rid of this error? Thanks! -
Trying to run my Django app using gpc compute engine
I am following this tutorial https://medium.com/@ahmed.dys99/deploying-django-application-on-google-cloud-platform-8eca8f82e7f6 I have followed all steps successfully but when I get to the last part of using the command nohup sudo python3 manage.py runserver 0.0.0.0:80 I am getting the message nohup: ignoring input and appending output to 'nohup.out'. What does this message mean and how can I get my site to run successfully via gpc? -
Is there any way to add makemigration and migrate in any url pattern?
I am creating one site in django, there on an HTML page if someone wants to create a new model table then there will be an option like: model name: MyNewModel model fields: { username = models.CharField(db_index=True, max_length=255, unique=True), email = models.EmailField(db_index=True, unique=True), name = models.CharField(db_index=True, max_length=255, null=True, blank=True), paid_amount = models.FloatField(max_length=10, blank=False, null=False, default=0) } And I want to hit the submit button then this model should add-in my Database. Is there any way to handle this problem? or every time we have to write manually model in our app. -
Post method return false for both valid and invalid data
I'm trying to create a login page but the authentication return same result for both valid and invalid data(it returns 'Invalid Username' for all cases). I checked everything but unfortunately couldn't catch anything. following are my code. I appreciate any help. forms.py: class UserLoginForm(forms.Form): email = forms.CharField(widget = forms.TextInput({'placeholder': 'Enter Your Email', 'class': 'form-control'})) password = forms.CharField(widget = forms.PasswordInput({'placeholder':'Password','class':'form-control'})) views.py: class IndexPage(TemplateView): template_name = 'Athentication/templates/Athentication/index.html' class LoginForm(TemplateView): template_name = 'Athentication/templates/Athentication/login.html' form_class = UserLoginForm def get(self,request): form = self.form_class() return render(request,self.template_name,{'form':form}) def post(self, request): form = self.form_class() if request.method =='POST': email=request.POST.get('email') password=request.POST.get('password') user = authenticate(self.request, email = email, password = password) if user is not None and user.is_valid: login(self.request,user) return HttpResponse('valid Username') else: return HttpResponse('Invalid Username') return render(request,template_name,{'form':form}) urls.py: urlpatterns = [path('', views.LoginForm.as_view(), name='login_page'), path('index/', views.IndexPage.as_view(), name = 'index'), path('admin/', admin.site.urls), ] login.html: <form method="post" > <div class="form-group mb-3"> <div class="input-group input-group-merge input-group-alternative"> <div class="input-group-prepend"> <span class="input-group-text"><i class="ni ni-email-83"></i></span> </div> {{form.email}} </div> </div> <div class="form-group"> <div class="input-group input-group-merge input-group-alternative"> <div class="input-group-prepend"> <span class="input-group-text"><i class="ni ni-lock-circle-open"></i></span> </div> {{form.password}} </div> </div> <div class="custom-control custom-control-alternative custom-checkbox"> <input class="custom-control-input" id=" customCheckLogin" type="checkbox"> <label class="custom-control-label" for=" customCheckLogin"> <span class="text-muted">Remember me</span> </label> </div> <div class="text-center"> <input class="btn btn-primary my-4" type="submit" value="Enter" /> {% csrf_token %} </div> </form> … -
Getting "Count" from annotate in the Django via through-tables
Let's pretend I run a store that takes orders in the form of phone calls or online orders. I'm building a web app to help me run my business and I want to build a "Phone" page for it. This page will include a table with a row for each unique phone number, and the columns will be "Phone Number" and "Customer Count". This will quickly tell me how many orders have placed from each phone number, and it will look something like this: Phone Number | Customer Count (555) 867-5309 | 2 (123) 456-7890 | 10 My approach to implementing this is to add an "annotate" function to the "get_queryset" function of the Phone views file, like this: # phones_view.py class PhonesList(generics.ListCreateAPIView): def get_queryset(self): query_filter = Phone.model_filter(self.request.query_params) q_set = Request.objects.filter(query_filter).annotate(customer_count=Count(order__customer), filter=(Q(order__order_type='PHONE'))) My serializer for the Phone page would include the "customer_count" annotation, like this: # phones_serializers.py class PhoneSerializer: phone_number = serializers.CharField(read_only=True) customer_count = serializers.CharField(read_only=True) I can't wrap my head around how to write the annotation. My models are arranged kind of strangely, so is it even possible to get what I want? How would I write the annotate function to give me the customer-count for each unique phone number … -
TypeError: 'MediaDefiningClass' object is not iterable | summernote integration in django admin
I am trying to intregrate django-summernote in my blog post admin area. when I set summernote_fields = ('description') and register to admin area, I am getting error like below : for model in model_or_iterable: TypeError: 'MediaDefiningClass' object is not iterable My admin.py is given below : from django.contrib import admin from django_summernote.admin import SummernoteModelAdmin from .models import Blog class BlogPostSummerNote(SummernoteModelAdmin): summernote_fields = ('description') @admin.register(Blog) class BlogAdmin(admin.ModelAdmin): list_display = ('title','slug','author','publish','status') prepopulated_fields = {'slug':('title',)} admin.site.register(BlogPostSummerNote) I can't able to figure this out . Can any one tell me why this is happening ?? -
Django extends template tag is written out as text not parsed
I'm a beginner trying to learn Django by following tutorials. I am currently working on template inheritence. When i try to extend a template. {% extends 'accounts/main.html'} {% block content %} <h1>Dashboard</h1> {% endblock %} The file is not extended. Instead this is written as plain text {% extends 'accounts/main.html'} when i view the page. The template i try to extend looks like this. <!doctype html> <html lang="sv"> <head> <meta charset="utf-8"> <title>Base template</title> <meta name="description" content=""> <meta name="author" content=""> </head> <body> {% block content %} {% endblock %} </body> </html> I have searched for this problem but found no solution. Can you please help me? -
Why can't I run django-admin?
So I always have problems installing things. Programming is never a problem, but installing always is. Mainly because I do things the way they are supposed to do according to the official websites but it doesn't work. It's like a cooking recipe, except you can't just improvise if you don't know what "salt" or "sugar" is. (If anyone got advice on that as a general problem, please tell me!) Today I tried getting into the django web framework. I installed and verified the installation as is supposed. When I wanted to start the tutorial, the second thing I was asked to do (after verifying the Version) was to cd into the directory I wanted the code to run in (which I did) and then run: django-admin startproject mysite When I did that, this appeared: Command 'django-admin' not found, but can be installed with: sudo apt install python3-django Alright. Fine I thought. That's what they put this in the tutorial in the next line: If it didn’t work, see Problems running django-admin. So I click that link. Now it says this: command not found: django-admin¶ django-admin should be on your system path if you installed Django via pip. If it’s not … -
Does pytest require a special setting when running from within my virtual environment?
I'm using Python 3.7 with Django 3. I want to use pytest to write some unit tests but am getting a strange configuration error. Here's a basic unit test I have ... import pytest from django.test import TestCase from .factories import CoopTypeFactory, CoopFactory, AddressFactory, StateFactory, EmailContactMethodFactory, PhoneContactMethodFactory from directory.models import Coop, CoopType from directory.serializers import * class SerializerTests(TestCase): @classmethod def setUpTestData(cls): #management.call_command('loaddata', 'test_data.yaml', verbosity=0) pass @pytest.mark.django_db def test_coop_type_create(self): """ Test coop serizlizer model """ name = "Library" serializer_data = { "name": name, } serializer = CoopTypeSerializer(data=serializer_data) serializer.is_valid() print(serializer.errors) assert serializer.is_valid(), serializer.errors coop_type = serializer.save() assert coop_type.name == name But when I go to run the test, I get a configuration error, complaining about an undefined variable, "ERROR test_serializers.py - django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured" (venv) localhost:tests davea$ pytest test_serializers.py ============================================================= test session starts ============================================================= platform darwin -- Python 3.7.2, pytest-5.4.1, py-1.8.1, pluggy-0.13.1 rootdir: /Users/davea/Documents/workspace/chicommons/maps/web/tests collected 0 items / 1 error =================================================================== ERRORS ==================================================================== ____________________________________________________ ERROR collecting test_serializers.py _____________________________________________________ test_serializers.py:3: in <module> from .factories import CoopTypeFactory, CoopFactory, AddressFactory, StateFactory, EmailContactMethodFactory, PhoneContactMethodFactory factories.py:3: in <module> from directory.models import CoopType, Coop, ContactMethod ../directory/models.py:5: in <module> from address.models import Address ../venv/lib/python3.7/site-packages/address/models.py:162: in <module> class Country(models.Model): ../venv/lib/python3.7/site-packages/django/db/models/base.py:107: in __new__ app_config = … -
AttributeError at /login/: Manager isn't accessible via User instances
I have created a python file in my django project with thhe name of signals.py in which i have created two function with are given below: and then I have imported these to functions into userss app(it is my second app name of the project and I am working on it currently)), which is given below: When I remove all these functions then it works properly but it doesn't save the new users into database but when I include them then it gives the error which I mention earlier. @receiver(post_save, sender=user) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.objects.save() class UserssConfig(AppConfig): name = 'userss' def ready(self): import userss.signals