Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django using model from another app doesn't change grappelli django-admin
I have a Django project whose structure is like that: project |___app1 |___app2 | |____models.py | |____admin.py |___app3 |____models.py |____admin.py I defined a lot of models in app2/models.py and I need to reuse in app3/models.py and app3/admin.py to register. Here is the problem I'm building an admin site with grappelli. As you might know, grappelli builds the /admin page by using as headers Applications and models as elements as you can see in the following picture. Like that everything works OK. Imagine now that I want App_2_Model_3 to be registered on App3. Then what I do is: Unregister Model_3 in App2: Register Model_3 in App3: # App3/admin.py from django.contrib import admin from App2 import models ... @admin.register(models.Model_3) class Model_3Admin(admin.ModelAdmin): ... Like that, in the previous picture Model_3 should appear under App3 and no longer under App2 but after that changes, the structure grappelli is showing is the same... Any idea on how to force grappelli show a model defined under an app under another app? Thanks in advance. -
how to get the value of <tr> on click
i have this code and when i click on the table row i want to get the table row value, how can i do that ? {% for testrun in testruns %} <tr data-toggle="modal" data-target="#testrunproblem" id="testoccasion_id" name="testoccasion_id" value="{{testrun.testoccasion_id}}"> <th>{{testrun.testoccasion_id}}</th> <td>{{testrun.testruns_comment}}</td> <td>{{testrun.testrunwork_time}}</td> <td>{{testrun.testruninit_time}}</td> <td nowrap> <button type="button" class="btn btn-warning btn-sm btn-1" title="Edit" onclick="javascript:editTestrun('{{testrun.testrun_id}}')"><i class="fas fa-edit"></i>Edit</button> <button type="button" class="btn btn-danger btn-sm" title="delete product" onclick="javascript:deleteTestrun('{{testrun.testrun_id}}')"><i class="fas fa-trash-alt"></i> Delete</button> </td> </tr> {% endfor %} -
Django Admin Panel URL GO WRONG
I am trying to add a document file from the admin panel Django but I am getting 404 not found URL errors. admin file from django.contrib import admin from .models import Category, Document # Register your models here. admin.site.register(Category) admin.site.register(Document) from django.db import models class Document(models.Model): doc_name = models.CharField(max_length=100) doc_slug = models.CharField(max_length=100) doc_file = models.FileField(upload_to='docs') doc_price = models.IntegerField() doc_cat = models.CharField(max_length=100) doc_desc = models.TextField() doc_var = models.TextField() What could possibly be the error? -
Django return value from form in form field
Is it possible in Django to give input data into form field and after pressing button get changed data in the same from field? For example: input in form field: Blue Car -> pressing button to accept form -> output in form field: Red Car -
Django 1.7.2 IntegrityError: new row for relation "cms_page" violates check constraint "cms_page_lft_check"
On prod I got an error when trying to publish page, that I can't reproduce on the test environment or local. This is stack trace: ''' Traceback (most recent call last): File "/srv/cms/app-lib/django/core/handlers/base.py", line 111, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/srv/cms/app-lib/django/utils/decorators.py", line 105, in _wrapped_view response = view_func(request, *args, **kwargs) File "/srv/cms/app-lib/django/views/decorators/cache.py", line 52, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/srv/cms/app-lib/django/contrib/admin/sites.py", line 206, in inner return view(request, *args, **kwargs) File "/srv/cms/cms/afl/admin.py", line 412, in publish_page result = super(OwnPageAdmin, self).publish_page(request, page_id, language) File "/srv/cms/app-lib/django/utils/decorators.py", line 29, in _wrapper return bound_func(*args, **kwargs) File "/srv/cms/app-lib/django/views/decorators/http.py", line 41, in inner return func(request, *args, **kwargs) File "/srv/cms/app-lib/django/utils/decorators.py", line 25, in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) File "/srv/cms/app-lib/django/db/transaction.py", line 394, in inner return func(*args, **kwargs) File "/srv/cms/app-lib/reversion/revisions.py", line 297, in do_revision_context return func(*args, **kwargs) File "/srv/cms/app-lib/cms/admin/pageadmin.py", line 1064, in publish_page published = page.publish(language) File "/srv/cms/app-lib/cms/models/pagemodel.py", line 576, in publish public_page = self._publisher_save_public(public_page) File "/srv/cms/app-lib/cms/models/pagemodel.py", line 1212, in _publisher_save_public obj.move_to(public_prev_sib, position="right") File "/srv/cms/app-lib/mptt/models.py", line 781, in move_to self._tree_manager.move_node(self, target, position) File "/srv/cms/app-lib/mptt/managers.py", line 603, in move_node self._move_node(node, target, position=position) File "/srv/cms/app-lib/mptt/managers.py", line 578, in _move_node self._move_child_node(node, target, position) File "/srv/cms/app-lib/mptt/managers.py", line 1005, in _move_child_node self._move_child_within_tree(node, target, position) File "/srv/cms/app-lib/mptt/managers.py", line 1161, in … -
How to add fields to a queryset with only()?
I have a queryset like this: queryset = MyModel.objects.select_related('foreign_key').filter(id__in=id_list).only( 'field_1', 'foreign_key__field' ) Now I want to add a select_related to this queryset, as well as some field too. How do I achieve this? I can use select_related on this queryset, but if I use only(), then it will override the previous only() fields. So how can I add more fields to the given queryset? -
How To Create A Temp File Structure For Testing
During testing files are generated which are not cleaned up afterwards. I have tried using django-cleanup but it does nothing. I figure I need to create a temporary file structure which files can be uploaded to during testing then destroyed after. This is how I created a temp MEDIA_ROOT file: MEDIA_ROOT = tempfile.mkdtemp() @override_settings(MEDIA_ROOT=MEDIA_ROOT) class UnitTest(TestCase): @classmethod def tearDownClass(cls): shutil.rmtree(MEDIA_ROOT, ignore_errors=True) super().tearDownClass() My file structure in my project looks like this MEDIA_ROOT profile_pics default.jpg user_files The problem is that, while I may have created a temporary MEDIA_ROOT folder, it doesn't create the subfolders and files. Prior to executing each test a user is created and during user creation the user is assigned a profile pic 'default.jpg'. This crashes every test as neither the profile_pics folder nor the default.jpg image exist. How can I get around this or create a temporary file structure as well as the default.jpg image within it? Thank you. -
My static files in django are not getting reloaded unless i rename them every time i reboot my pc
I am trying to work on a django project which has static files. Every time I reload my pc and make some changes in the static files those changes don't get applied. Then i rename that static file and also change the static url in my template..Then the change takes place..How can i solve this.. -
Wagtail not using clean method of custom form
I have got a basic page with a custom base_form_class, i want to use the form to add validation to related orderables. It is defined like so class HomePage(Page): ... base_form_class = HomePageForm ... And the form is defined like class HomePageForm(WagtailAdminPageForm): def clean(self): cleaned_data = super().clean() #some added validation return cleaned_data But wagtail keeps using the clean method of the WagtailAdminPageForm, no matter what. Has anyone encountered this issue? When i put a breakpoint in the clean method of wagtailadminpageform i can see that the form is in fact an instance of HomePageForm but it just does not use the correct clean method (or possibly, i am using the wrong clean method) -
How to color code snippet in Django template
I am looking at coloring code on one of my Django page, the way PyCharm does it for instance. def my_function(a): return a + 5 print(my_function(10)) displayed with colors such as (the background doesn't have to be black): Is there an easy solution to capture anything within the <pre><code></code></pre> tags and applies this color code? Writing my own Django filter for this looks like an arduous task. -
Overwriting function in parent class
I was just looking at this example online (https://www.tutorialspoint.com/How-to-override-class-methods-in-Python#:~:text=In%20Python%20method%20overriding%20occurs,do%20not%20come%20in%20play.) class Parent(object): def __init__(self): self.value = 4 def get_value(self): return self.value class Child(Parent): def get_value(self): return self.value + 1 When the function get_value is run in the class Child, does it determine the value of self.value by checking what the value of self.value was in the function init in Class Parent, or by checking what the value of self.value was in the function get_value in class Parent? -
Django clean method not working
Here is my form.py class DepartamentForm(forms.ModelForm): class Meta: model = Department fields = ['name','company','city', 'special_id','active'] def clean_code(self): code = self.cleaned_data.get('special_id') qm = Department.objects.filter(special_id=code) if qm.exists(): raise forms.ValidationError("Email jest już używany!!" ) return code my view.py def dictionary_department_add(request): current_user = request.user if request.method == "POST": form = DepartamentForm(request.POST) if form.is_valid(): x_form = form.save(commit=False) x_form.date_add = now.strftime("%Y-%m-%d %H:%M") x_form.user_add = current_user.username x_form.save() return redirect('/dictionaries/dictionary_department/') else: return render(request, 'add_department.html', {'form': form}) else: form = DepartamentForm() return render(request, 'add_department.html', {'form': form}) when I try add new position department with code wich exists, error not showing, and submit is OK. Please help me. -
Django Deprecation Warning __class__ not set defining 'AbstractBaseUser' as <class [duplicate]
I am in the process of upgrading from django 1.10 to django 1.11, running python 3.6 I am busy dealing with the deprecation warnings, and I have come across a couple of these /home/user/venvs/projectenv/lib/python3.6/site-packages/django/contrib/auth/base_user.py:52: DeprecationWarning: __class__ not set defining 'AbstractBaseUser' as <class 'django.contrib.auth.base_user.AbstractBaseUser'>. Was __classcell__ propagated to type.__new__? There are a couple of these warnings relating to my own models as well. What is really strange is if I downgrade my virtual environment to python3.5 the warning goes away. Does anyone know what might be causing this, and how I can overcome it? -
How to integrate ebook reader in website made in django like play.google.com and openlibrary.org?
I am right now working on library website on top of django framework, where you can download and can read ebook online in website but I have no idea how should I can integrate in-site ebook reader just like books.google.com or openlibrary.org -
I am facing lot of errors while installing channel version 2.1.2.I am using django version 3.0 and python version 3.8 and pip version 20.2.1
I am working in pycharm .I am running the code "pip install channel==2.1.2". The error i am facing is given below. ERROR: Command errored out with exit status 1: 'c:\users\user\pycharmprojects\justchat\venv\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\user\AppData\Local\Temp\pip-install-qwgcgyz5\twisted\setup.py'"'"'; file='"'"'C:\Users\user\AppData\Local\Temp\pip-install-qwgcgyz5 \twisted\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, _file _, '"'"'exec'"'"'))' install --record 'C:\Users\user\AppData\Local\Temp\pip-record-xh49_7m7\install-record.txt' --single-version-externally-managed --compile --insta ll-headers 'c:\users\user\pycharmprojects\justchat\venv\include\site\python3.8\twisted' Check the logs for full command output. -
How to spin up Celery container with SQS usage
I'm trying to setup Celery to talk with AWS SQS. Celery put log as below and after that container is going down and starting up again in loop. Log as below: trim... [2020-08-05 09:32:35,715: DEBUG/MainProcess] Changing event name from creating-client-class.iot-data to creating-client-class.iot-data-plane [2020-08-05 09:32:35,798: DEBUG/MainProcess] Changing event name from before-call.apigateway to before-call.api-gateway [2020-08-05 09:32:35,799: DEBUG/MainProcess] Changing event name from request-created.machinelearning.Predict to request-created.machine-learning.Predict [2020-08-05 09:32:35,801: DEBUG/MainProcess] Changing event name from before-parameter-build.autoscaling.CreateLaunchConfiguration to before-parameter-build.auto-scaling.CreateLaunchConfiguration [2020-08-05 09:32:35,801: DEBUG/MainProcess] Changing event name from before-parameter-build.route53 to before-parameter-build.route-53 [2020-08-05 09:32:35,802: DEBUG/MainProcess] Changing event name from request-created.cloudsearchdomain.Search to request-created.cloudsearch-domain.Search [2020-08-05 09:32:35,802: DEBUG/MainProcess] Changing event name from docs.*.autoscaling.CreateLaunchConfiguration.complete-section to docs.*.auto-scaling.CreateLaunchConfiguration.complete-section [2020-08-05 09:32:35,805: DEBUG/MainProcess] Changing event name from before-parameter-build.logs.CreateExportTask to before-parameter-build.cloudwatch-logs.CreateExportTask [2020-08-05 09:32:35,805: DEBUG/MainProcess] Changing event name from docs.*.logs.CreateExportTask.complete-section to docs.*.cloudwatch-logs.CreateExportTask.complete-section [2020-08-05 09:32:35,806: DEBUG/MainProcess] Changing event name from before-parameter-build.cloudsearchdomain.Search to before-parameter-build.cloudsearch-domain.Search [2020-08-05 09:32:35,806: DEBUG/MainProcess] Changing event name from docs.*.cloudsearchdomain.Search.complete-section to docs.*.cloudsearch-domain.Search.complete-section [2020-08-05 09:32:35,806: DEBUG/MainProcess] Setting config variable for region to {'eu-west-1'} [2020-08-05 09:32:35,808: DEBUG/MainProcess] Loading JSON file: /usr/local/lib/python3.8/site-packages/botocore/data/endpoints.json [2020-08-05 09:32:35,815: DEBUG/MainProcess] Event choose-service-name: calling handler <function handle_service_name_alias at 0x7fed0d144940> [2020-08-05 09:32:35,899: DEBUG/MainProcess] Loading JSON file: /usr/local/lib/python3.8/site-packages/botocore/data/sqs/2012-11-05/service-2.json [2020-08-05 09:32:35,902: DEBUG/MainProcess] Event creating-client-class.sqs: calling handler <function add_generate_presigned_url at 0x7fed096053a0> [2020-08-05 09:32:36,907: DEBUG/MainProcess] removing tasks from inqueue until task handler finished -------------- … -
Django is ignoring database connection in settings.py
I'm trying to deploy a django application in a VPS running ubuntu 20.04. I settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file':'/home/ubuntu/arainc/auth/mysql.cnf' }, } } And the configuration file: #mysql.cnf [client] database = 'dbname' user = 'dbuser' password = 'dbuser@123' default-character-set = 'utf8' While trying to reach the site, I get the below error: Environment: Request Method: GET Request URL: http://208.115.109.194/ Django Version: 3.0.7 Python Version: 3.8.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'araincdb', 'import_export', 'crispy_forms', 'django_filters', 'widget_tweaks'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/ubuntu/arainc/venv/lib/python3.8/site-packages/django/contrib/sessions/backends/base.py", line 199, in _get_session return self._session_cache During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred: File "/home/ubuntu/arainc/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/home/ubuntu/arainc/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/home/ubuntu/arainc/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/ubuntu/arainc/venv/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 233, in get_new_connection return Database.connect(**conn_params) File "/home/ubuntu/arainc/venv/lib/python3.8/site-packages/MySQLdb/__init__.py", line 130, in Connect return Connection(*args, **kwargs) File "/home/ubuntu/arainc/venv/lib/python3.8/site-packages/MySQLdb/connections.py", line 185, in __init__ super().__init__(*args, **kwargs2) Exception Type: OperationalError at / Exception Value: (1045, "Access denied for user 'www-data'@'localhost' (using password: NO)") I can login to the database with the credentials in the configuration file. How … -
django docker selenium headless setup fails with element not found error
I tried printing a get req to google and it printed None. I believe it is a problem with the chrome driver setup itself. here is the code ---------------------------------------------------------------------- Ran 1 test in 7.654s FAILED (errors=1) Destroying test database for alias 'default'... tests>docker-compose run --rm app sh -c "python manage.py test functional_tests" Starting public-site-tests_db_1 ... done Starting public-site-tests_selenium_1 ... done Creating test database for alias 'default'... System check identified no issues (0 silenced). None E ====================================================================== ERROR: test_login (src.functional_tests.test_logIn.LoginTest) Lets test the user login feature ---------------------------------------------------------------------- Traceback (most recent call last): File "/src/functional_tests/test_logIn.py", line 67, in test_login email_field = self.browser.find_element_by_name('username') File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 496, in find_element_by_name return self.find_element(by=By.NAME, value=name) File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element 'value': value})['value'] File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute self.error_handler.check_response(response) File "/usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[name="username"]"} (Session info: headless chrome=84.0.4147.105) and here is the setup chrome_options = Options() chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--headless") chrome_options.add_argument("--window-size=1920,1080") chrome_options.add_argument("--disable-extensions") chrome_options.add_argument("--proxy-server='direct://'") chrome_options.add_argument("--proxy-bypass-list=*") chrome_options.add_argument("--start-maximized") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--ignore-certificate-errors") class LoginTest(StaticLiveServerTestCase): live_server_url = 'http://{}:8000'.format( socket.gethostbyname(socket.gethostname()) ) def setUp(self): # if os.environ.get('CI_JOB_NAME'): # browser_name = webdriver.Chrome(chrome_options=True) # if os.environ.get('CI_JOB_NAME') == 'e2e:chrome' else 'Firefox' # self.browser = webdriver.Chrome(options=chrome_options) settings.DEBUG = True self.browser = webdriver.Remote( … -
TypeError : count() takes at least 1 argument (0 given)
i am getting TypeError: count() takes at least 1 argument (0 given). it would be great if anybody could figure out where i am doing thing wrong. thank you so much in advance. class CommentsSerializer(serializers.ModelSerializer): comment_count = serializers.SerializerMethodField() class Meta: model = Comments fields = [ "id", "title", "name", "subject", "comment_count", ] def get_comment_count(self, obj): return obj.subject.count() -
optimize SerializerMethodField in a serializer
I have a serializer like that : class UserSerializerDetail(UserSerializer): active_projects = serializers.SerializerMethodField() def get_active_projects(self, obj): return obj.projects.filter(project__active=True).count() the problem I am having here is that the SerializerMethodField is calling an extra filter and I wish to use select related to create a join and overcome another hit in the database. The second issue is how can I select_related a count? -
How to include URL parameter for detail view
My models: class Blog(models.Model): title = models.CharField(max_length=500, null=False, default='', blank=True) slug = models.CharField(max_length=200, unique=True) html_text = RichTextUploadingField(null=False, default='', blank=True) author = models.ForeignKey('users.BlogAuthor', on_delete=CASCADE, null=False) category = models.ForeignKey('blogs.BlogCategory') img_main = models.ImageField(upload_to='blogs/') img_main_alt_text = models.TextField(blank=True, default='') created = models.DateTimeField(auto_now=True) posted = models.DateTimeField(null=True, blank=True) class BlogCategory(models.Model): name = models.CharField(max_length=100, null=False) def __str__(self): return self.name View: class BlogsAPIView( mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): permission_classes = (AllowAny,) pagination_class = LimitOffsetPagination serializer_class = BlogSerializer lookup_field = 'slug' filter_backends = [django_filters.rest_framework.DjangoFilterBackend] filterset_fields = ('categories',) text_search_fields = ['title'] def get_queryset(self): .... Routers: router.register('blogs', BlogsAPIView, basename='blogs') Now I'm getting whole list of posts from: /api/v1/blogs and single post from: /api/v1/blogs/some-slug How can I change url for single post (detail url) to be like this: /api/v1/blogs/category/some-slug Where category is a string taken from BlogCategory.name of the related field thanks -
Django RestFramwork how to get child component from inside parent components
I'm using django restframe work as a backend to my React app. when I created a recursive data I filtered the views in order to not showing the child components outside the parent components queryset = Data.objects.filter(main__isnull=True). My problem is when I go to the api_link/1/ it will GET the component if it is a parent but when I say api_link/2/ I get "detail": "Not found." because I filtered them out but i still can see them inside the child that I called itsub as shown in the bellow" HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 1, "tag": "div", "text": "Hello", "src": "", "style": "", "main": null, "sub": [ { "id": 2, "tag": "h1", "text": "test2", "src": null, "style": "", "main": 1, "sub": [] }, { "id": 3, "tag": "h1", "text": "test 3", "src": null, "style": "", "main": 1, "sub": [] } ] }, { "id": 4, "tag": "div", "text": "bla bla", "src": "", "style": "", "main": null, "sub": [] } ] -
How to rectify debugging issue on VSCode where debugger skips line when stepping
Problem I'm trying to debug my Django project via VSCode yet the debugger appears to skip my context definition line and overhang to the next if condition (As if it has shifted by one line). My file is saved as I've validated this via Notepad. Is there any way to fully restart VSCode to try to rectify this issue? Visual -
Django project POST and GET requests not working with Nginx & Gunicorn
I'm new to Django. I have a Django project and in my project, I use multiple APIs such as blockchain API for handling bitcoin transactions and cryptocompare API to get the latest bitcoin price and in my project, I have WebSocket messenger. I have set up the NGINX and Gunicorn for my production. but all of the POST and GET requests in my project don't work and my project cannot communicate with external API and even local service like blockchain wallet API service. but when I run my project only with gunicorn like this : gunicorn --bind 0.0.0.0:80 myproject.wsgi it works fine I'm a little bit confused. here is my Gunicorn service in ubuntu server 18 [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/myproject ExecStart=/home/env/bin/gunicorn --access-logfile - --workers 5 --worker-class gevent --bind unix:/home/myproject/myproject.sock myproject.wsgi:application [Install] WantedBy=multi-user.target And here is my Nginx configuration : upstream channels-backend { server localhost:9001; } upstream django { server myproject:80; } server { listen 80; server_name Domain.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/myproject; add_header X-XSS-Protection "1; mode=block" always; add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; expires 1y; add_header Cache-Control "max-age=31536000"; } location / { include proxy_params; proxy_pass … -
IntegrityError at /auth/login/ NOT NULL constraint failed: authtoken_token.user_id
I am trying to set up a basic API. However, when I try logging in, there seems to be an error. I am using django-rest-auth and tried to customise the login process by creating a login serializer. Somehow everytime I try to login it throws this error. serializers.py <...local imports...> from rest_framework import serializers from django.contrib.auth import authenticate class ToDoSerializer(serializers.ModelSerializer): class Meta: model = ToDo fields = '__all__' extra_kwargs = {'priority': {'write_only': True}} class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = "__all__" class LoginSerializer(serializers.ModelSerializer): email = serializers.EmailField(write_only=True) password = serializers.CharField(write_only=True) class Meta: model = Customer fields = ['email', 'password'] def validate_credential(self, email, password): user = None if email and password: user = authenticate(email=email, password=password) else: raise exceptions.ValidationError('Invalid Credentials') return user def validate(self, attrs): email = attrs.get('email') password = attrs.get('password') user = self.validate_credential(email, password) attrs['user'] = user return attrs models.py from django.db import models from django.contrib.auth import settings from django.contrib.auth.models import AbstractUser # Create your models here. class ToDo(models.Model): text = models.CharField(max_length=120) priority = models.BooleanField(default=False) customer = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='todos') def __str__(self): return f"{self.text} by {self.customer}" class Customer(AbstractUser): username = models.CharField(max_length=120, unique=True) email = models.EmailField(unique=True) priority = models.ForeignKey( ToDo, on_delete=models.CASCADE, null=True, related_name='customers') def __str__(self): return self.email What could be …