Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django does not see a change in the primary key data type
In the data model, I changed the data type from INT to VarChar for the ID field. Unfortunately, this change was not noticed by macemigrations and I was forced to do a migrate zero and generate the migration file from scratch. Unfortunately, this didn't help either, as the ID field was still of type INT. Therefore, I modified the file and did the migrations. A table as I expected was created in the database. I even did a manual INSERT into the database which ended up being a succes. Unfortunately, Django has a problem with the insert and throws an error : Field 'id' expected a number but got '230301-001'. Request Method: POST Request URL: http://192.168.1.249:8080/maintenance/new Django Version: 4.1.3 Exception Type: ValueError Exception Value: Field 'id' expected a number but got '230301-001'. I also paste the stack: /home/gaza/projects/django/maintenance/models.py, line 60, in save super(Report, self).save(*args, **kwargs) … Local vars Variable Value __class__ <class 'maintenance.models.Report'> args () id_date '230301' kwargs {} new_id '230301-001' qs <QuerySet []> self <Report: 230301--001> today datetime.datetime(2023, 3, 1, 14, 19, 41, 369941) user <SimpleLazyObject: <User: superadmin>> Below is my model definition and the SQL itself from the database that created the tables. class Report(ModelBaseClass): id = models.CharField(max_length=10, … -
Why gunicorn returns 403 forbidden after nginx proxing?
I have a django app which I run using gunicorn inside docker container. Then I use nginx as proxy server. When I request open container port directly (http://localhost:8899/) it's working OK, but when I trying request http://localhost I/m getting 403 Forbidden error from gunicorn "GET / HTTP/1.0" 403. Do you have any ideas what I'm doing wrong? # nginx.conf upstream django { server web:8000 fail_timeout=30 max_fails=30 weight=50; server web:8000 fail_timeout=30 max_fails=30 weight=50; } ... location = / { root /src; try_files $uri @django; } location / { root /src; try_files $uri @django; } location @django { proxy_pass http://django; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } # docker-compose.yml nginx: ports: - mode: host target: 80 published: "8080" protocol: tcp - mode: host target: 443 published: "443" protocol: tcp ... web: ports: - mode: host target: 8000 published: "8899" protocol: tcp ... -
How to pass value in a Get request in React so I can apply filter on the backend?
I would like to retrieve a list of filtered messages from my API to my React App. On the backend the view for the Message Model looks like this. class MessageView(viewsets.ModelViewSet): """View for the messages""" serializer_class = MessageSerializer queryset = Message.objects.all() permission_classes = [IsAuthenticated] def get_queryset(self): """Retrieve recipes linked to the authenticated user""" return self.queryset.filter(channel = self.request.channel) def perform_create(self, serializer): """ Create a new recipe """ serializer.save(user=self.request.user) It re writes the get_queryset() function so I only retrieve the messages from a given channel which is a ForeignKey of Message. On the React part is there any way to pass the channel object in the request so that channel = self.request.channel would work? Alternatively I could just retrieve all the messages and then filter on the frontend. But I feel like filtering from the api view would be better, or am I completly wrong? Thanks, -
Inlined buttons are forced into a new line when converted to django form fields
Here's what I'm trying to replicate using django form and view classes: * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Roboto', sans-serif } body { height: 100vh; padding: 10px } label[for^='id_choice'], .selectable { display: flex; margin-top: 10px; padding: 10px 12px; border-radius: 5px; cursor: pointer; border: 1px solid #ddd; margin-right: 5px; } .selectable:active { border: 1px solid #0d6efd; } .selectable:hover { background: #0f5132; } input[type='radio'] { width: 22px; height: 22px; margin-right: 10px; } input[type='radio']:before { content: ''; display: block; width: 60%; height: 60%; margin: 20% auto; border-radius: 50%; } input[type="radio"]:checked:before { background: #20c997; } input[type="radio"]:checked { border-color: #20c997; } .selectable:has(input:checked){ border: 1px solid #20c997; } button[type="submit"] { display: block; margin-top: 20px; margin-left: 45%; } .selectable-btn { width: 45px; height: 45px; margin-top: 10px; margin-right: 5px; } <input type="text" class="form-control selectable" placeholder="Title"> <div class="input-group"> <input type="text" class="form-control selectable" placeholder="Selection"> <button class="btn btn-success add-form-row selectable-btn">+</button> <button class="btn btn-danger remove-form-row selectable-btn">-</button> </div> which allows the +/- buttons to be inlined with the second text input. So I use the following form class: from django import forms class SelectionForm(forms.Form): title = forms.CharField( max_length=255, widget=forms.TextInput( attrs={'placeholder': 'Title', 'class': 'form-control selectable'} ), label='' ) selection = forms.CharField( max_length=255, widget=forms.TextInput( attrs={'placeholder': 'Selection', 'class': 'form-control selectable'} ), label='' ) … -
How to create custom validator class for serializer in django python?
I need to remake this validator method, create a custom validator class, check that it is impossible to subscribe to itself. I'm new to this, please help, according to the examples from the documentation, I could not do this. class FollowSerializer(serializers.ModelSerializer): following = serializers.SlugRelatedField( queryset=User.objects.all(), slug_field='username' ) user = serializers.SlugRelatedField( read_only=True, slug_field='username', default=serializers.CurrentUserDefault(), validators=[CheckingYourSubscription] ) def validate_following(self, following): user = self.context['request'].user if user == following: raise serializers.ValidationError( 'Subscriptions to yourself are prohibited!' ) return following class Meta: fields = '__all__' model = Follow validators = [ serializers.UniqueTogetherValidator( queryset=Follow.objects.all(), fields=('user', 'following'), message='This subscription has already been issued.' ), ] -
How to extract and return data from multiple tables via foreign keys with django rest?
I have the following models: class Stock(models.Model): bar_id = models.ForeignKey(Bar, on_delete=models.CASCADE, related_name="bars") stock = models.IntegerField() class Bar(models.Model): name = models.CharField(max_length=200) Note that one Bar can have multiple Stock I would like, for one Bar, to retrieve and return all the stocks that are associated. SO, in my urls, I have: path('stock/<int:pk>/', views.StockListPerBar.as_view()) With the view being: class StockListPerBar(generics.RetrieveAPIView): queryset = Bar.objects.all() serializer_class = StockListPerBarSerializer And the serializer is: class StockListPerBarSerializer(serializers.ModelSerializer): bars = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Bar fields = ["name", "bars"] This provide the following output: { "name": "Some bar name", "bars": [ 4, 5, 6, 7 ] } However, I would like the output to be a bit different, like so (truncated): [ { "id": 4, "stock": 10 }, { "id": 5, "stock": 0 } ] How may I achieve that ? -
Django Form Add user from a specific group
I'm new with Django. There is my model : class Classe(models.Model): title = models.CharField(max_length=25) titulaire = models.ForeignKey(User, related_name='titulaire', on_delete=models.SET_NULL, null=True, blank=True) In a form, I would like add the "titulaire" field and select user from a specific group. Any tips ? Thanks I'll tried something like that.. class ModifyClasse(ModelForm): class Meta: model = Classe fields = ['title' , 'year', 'titulaire', 'cotitulaire'] def __init__(self, *args, **kwargs): qs = User.objects.filter(groups__name__in=['Profs']) titulaire = kwargs.pop('qs', None) super(ModifyClasse, self).__init__(*args, **kwargs) del self.fields['titulaire'] -
Django: import error or possible settings misconfiguration
I am trying to use a model I created in myapp/models.py in another file called store.py, but every attempt to import models.py has failed. Both store.py and model.py are in my Django app folder. Here is what I tried so far: A) from . import models radio = models.Radio(....) ImportError: attempted relative import with no known parent package B) from myapp.models import Radio radio = Radio(....) ModuleNotFoundError: No module named 'myapp' C) from .models import Radio radio = Radio(....) ImportError: attempted relative import with no known parent package D) from models import Radio radio = Radio(....) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Note: manage.py makemigrations && manage.py migrate have already been run after creating the model myapp is installed in settings.py's INSTALLED_APPS as 'myapp.apps.MyappConfig' My tree: ├── base │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── myapp │ ├── __init__.py │ ├── __pycache__ │ ├── admin.py │ ├── apps.py │ ├── fetch.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── __init__.py │ ├── models.py │ ├── scripts │ ├── static │ │ └── … -
DRF - serializer saves data but changes a date?
I have the following output from print(serializer.data): [OrderedDict([('last_price', '62.63'), ('name', None), ('country', None), ('sector', None), ('industry', None), ('ticker', 'VUSA'), ('high_price', 62.7075), ('last_date_time', '2023-03-01T00:00:00+04:00')])] When I go and look in the database(sql and postgres) the last_date_time field is: 2023-02-28 20:00:00. The create statement: def create(self, request, *args, **kwargs): if self.request.user.is_superuser: serializer = self.get_serializer(data=request.data, many=isinstance(request.data, list)) serializer.is_valid(raise_exception=True) print(serializer.data) self.perform_create(serializer) return Response({"Status": "We should be done"}) The model: class UsStockPriceModel(models.Model): ticker = models.CharField(max_length=30, blank=False, db_index=True) name = models.CharField(max_length=150, blank=True, null=True) # mainly for US stocks country = models.CharField(max_length=100, blank=True, null=True) sector = models.CharField(max_length=100, blank=True, null=True) industry = models.CharField(max_length=100, blank=True, null=True) last_price = models.FloatField(blank=True, null=True) high_price = models.FloatField(blank=True, null=True) last_date_time = models.DateTimeField(db_index=True) created_at = models.DateTimeField(auto_now_add=True) The Serializer: class UsStockPriceSerializer(serializers.ModelSerializer): # ticker = models.CharField(max_length=30, blank=False) last_price = serializers.CharField(required=False, allow_null=True, allow_blank=True) name = serializers.CharField(required=False, allow_null=True, allow_blank=True) # mainly for US stocks country = serializers.CharField(required=False, allow_null=True, allow_blank=True) sector = serializers.CharField(required=False, allow_null=True, allow_blank=True) industry = serializers.CharField(required=False, allow_null=True, allow_blank=True) # last_date_time = models.DateTimeField() class Meta: model = UsStockPriceModel fields = '__all__' def validate_last_price(self, value): if not value: return None try: return float(value) except ValueError: raise serializers.ValidationError('Valid integer is required') Not sure what is going wrong here. -
In django dockerization nginx does not listen on port 80 and cannot find static files even though it is in nginx container
Docker-compose.yml version: '3' services: nginx: build: ./nginx ports: - 80:80 depends_on: - "web" volumes: - ./static_volume/:/home/app/web/staticfiles db: image: postgres restart: always volumes: - ./pgdb:/var/lib/postgresql/data/ ports: - "5432:5432" env_file: - .env web: build: . command: gunicorn config.wsgi:application --bind 0.0.0.0:8000 volumes: - .:/app - ./static_volume/:/app/staticfiles ports: - "8000:8000" depends_on: - db - redis - celery env_file: - .env redis: image: redis ports: - "6379:6379" celery: build: . command: celery -A config worker -l info depends_on: - redis env_file: - .env volumes: static_volume: pgdb: external: false nginx.conf upstream hello_django { server web:8000; } server { listen 80; location / { proxy_pass http://hello_django; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /home/app/web/staticfiles; } } Dockerfile for nginx FROM nginx:1.21-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d this is web and nginx container I'm trying to dockerize my Django project and have successfully managed to serve static files without configuring nginx within the container. However, after installing nginx, the static files are not found by nginx even though they exist in the nginx container. Additionally, the site only seems to work on the localhost:8000 port.My Operation system is Windows -
Django/PyCharm - Unresolved attribute reference '' for class 'User'
Just wondering if there's a way to get around this super annoying PyCharm warning without having to ignore it altogether. I have a custom User model with extra fields and methods. When I try to access these attributes in a view (ex. if self.request.user.type == 'foo':) I'll get the warning Unresolved attribute reference 'foo' for class 'User' in the IDE. It seems that PyCharm thinks that I'm still using django.contrib.auth.User even though I've specified AUTH_USER_MODEL = 'user.User' in the project settings. -
Django Channels permissions
Is there any supported way in Django Channels framework to write custom permission to connect to specific consumers? something like DRF: class MyConsumer(generics.APIView): permission_classes = [IsAuthenticated, MyCustomPermission] authentication_classes = [TokenAuthentication] -
403 error when using django with allauth and htmx
I am building a website with django and I use allauth for authentication and htmx to make the site dynamic. On my mainpage when the user clicks on Login an hx-get is issued and the div with id="login-logout-div" is swapped with the response of the allauth Login view. Then the user can enter the credentials and is logged in. The allauth settings are LOGIN_REDIRECT_URL = "hq:index" LOGIN_URL = "account_login" The login process also works, the user stays on the main page and the login div disappears. However, I also have a button that triggers an htmx-post further down that swaps the div with id=empty_entry. This button does not work right after the login and I get a 403 response. When I refresh the page, the user is still logged in and the hx-post request is now accepted when I click the button. I suspect that the csrf token is refreshed when I login but the X-CSRFToken in the hx-header is not updated when I redirect. The token is still sent on the hx-post request but it might be the wrong one. Help is very appreciated. :) index.html <body hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}' hx-boost="true" hx-ext="multi-swap" homepage> <div> <div class="nav-links"> <a href="{% … -
How to change urls for "Add", "Change" etc. buttons in Django Admin?
My Django admin panel on production server has url like https://example.com/app/admin, but when I click on the buttons near my models (on the screenshots), I redirect to https://example.com/admin/metrics/..., without an /app/ part. If I manually go to https://example.com/app/admin/metrics/..., everything works perfectly. Can I somehow override this behaviour without overriding the whole admin panel template? -
Passing no variable in Django url template tag when one is required
Im using Django with htmx. I have set up a url as follows in my urls.py file: urlpatterns = [ path('@/<username>/my_orders/', views.myordersview, name="myorders"), ] and the myordersview function something like this: @login_required def myordersview(request, username): if request.htmx: return render(#something) else: return render(#something else) Now Im making a call to that url with htmx in my frame.html file: <a hx-target="#content" hx-get="{% url 'myorders' user.username %}"> My Orders </a> The <a> tag should also be displayed when a user is not logged in and redirect the unauthenticated user to a login page. The problem is, if a user is not logged in, no variable is passed into the url template tag aka user.username='' and Django spits out this error Reverse for 'myorders' with arguments '('',)' not found. I dont want to do this because its ugly: <a hx-target="#content" hx-get=" {% if user.is_authenticated %} {% url 'myorders' user.username %} {% else %} {% url 'login' %} {% endif %} "> My Orders </a> Is there a simple way to solve this without using a custom template tag? -
Overriding the default class attribute using django-crispy-forms
I am currently learning how to use django crispy forms and can't figure out this issue. I am using it alongside bootstrap5. I have the following form : class CommentForm(forms.ModelForm): class Meta : model = Comments fields = ["comment_content"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False self.fields['comment_content'].widget.attrs['placeholder'] = 'comment here...' self.helper.layout = Layout( "comment_content", ) self.helper.layout.append(Submit("post_comment", "Post comment",css_class="btn-outlined-primary")) The issue is with the last line : instead of replacing the default class (btn btn-primary) by the value of css_class,it simply adds this value afterwards so the resulting html is the following : <input type="submit" name="post_comment" value="Post comment" class="btn btn-primary btn-outlined-primary" id="submit-id-post_comment"> How do I make it so the resulting class is "btn btn-outlined-primary" and not "btn btn-primary btn-outlined-primary" ? Thanks to anyone taking the time to help me ! -
Django GIS - get all PERSONS within at least distance of "n" Points of Interest and annotate with distance
Let's imagine the two following models: from django.db import models from django.contrib.gis.db import models as models_gis class Person(models.Model): name = models.CharField(...) coordinates = models_gis.PointField(srid=4326, geography=True, spatial_index=True) class PointOfInterest(models.Model): name = models.CharField(...) coordinates = models_gis.PointField(srid=4326, geography=True, spatial_index=True) I manage to get all Person objects within a radius of an arbitrary number of PointOfInterest objects. The below seems to work: from django.contrib.gis.geos import MultiPoint # in meters radius = 1000 # *very* approximate conversion to degrees radius_in_degrees = float(radius) / 40010040.0 * 360.0 poi_points = tuple(PointOfInterest.objects.filter( pk__in=[1,2,3] ).values_list('coordinates', flat=True)) poi_multipoint = MultiPoint(*poi_points) persons = Person.objects.filter( coordinates__distance_lte=(poi_multipoint, radius_in_degrees), ) for person in persons: print(f'{person.name} is within {radius} meters of at least one of the specified points of interest') Cool. Now I would also like to annotate the persons queryset with the distance between each of its person and the individual POI of the poi_multipoint geometry it was found being closest to (and within the radius of course). How to do that so I can do: for person in persons: print(f'{person.name} is within {radius} meters of at least one of the specified points of interest. Distance to closest POI is {person.distance}') -
Django - nested modules in app with models don't trigger new migrations
In my Django project, I just created a new app named integrations, which defined an abstract model TwinResource. This integrations app, in turns, has a module called classroom, which also has a models.py file with a model ClassroomCourse which inherits from TwinResource. I have added the following to my INSTALLED_APPS: 'integrations', 'integrations.classroom', and I have created an init.py both in integrations and integrations.classroom, and both directories have a migrations folder with an init.py file. However, when running manage.py makemigrations, I get “No changes detected”. What am I missing? -
How to track that a request is handled by which view in django project?
I am working on a django project which consists of multiple apps and every app has its separate urls.py file. Now when we send a request in a browser, how can we track that the request is handled by which view in our project? e.g. We send a request with this url: http://mywebsite.com:8000/item?id=2 In server , we can see the request as: "GET /item?id=2 HTTP/1.1" 200 How can we track that this request is handled by which view? -
Delete unused tables and fields in django
I'm working on a Django project version 2.2 using Oracle SQL Database. In this database there are some tables that are not managed by Django models and I want to delete these. Because there are nearly 1800 tables in this database, I need to find a way to detect these by some sort of script or query. Also in some tables there are some fields that are always null for any records. Actually, I have got many unusable fields in my database. How can I detect and remove these fields and tables using Django or Oracle SQL? I ran a sql query to list all tables and compare it to output of django command apps.get_models() but it didn't help. -
Forcefully Logout user from frontend in Django
I am using React for frontend and Django for the backend. I have created a button "Force logout" in django admin for each use on click of which I want to logout the user working on the frontend (when he refresh he should be logged out). I want to do this completely in django without touching Reach. I am using djangorestframework-simplejwt for authentication. -
Built-in way to name one specific celery task
I'm using Celery with Django (and django-db as result backend). I know that it's possible to give names to registered tasks using @app.task(name='My Task') but that's only like categorizing. Assume uploading and processing a file "batch-210520.json". I want to be able to identify one running task as the task which is processing that specific file. Obviously I could add my own table to keep track of task ids and their unique names, but if there is a built-in way I want to use it. Unfortunately I only found the solution for naming the whole registered task. -
Add scroll wheel to Ckeditor 5 text editor django
I am quite new to using django. I want to add a rich text editor to my webapp and I saw a tutorial on how to do so using "django-ckeditor-5". I followed these steps: https://pypi.org/project/django-ckeditor-5/ and the editor works fine and everything however, it keeps expanding with the the text, so it just goes of the screen after a while. Is there a way to stop this behavior, and instead add a scroll wheel to the side of the editor so users can use that to see the entire text? I was also wandering how I can install plugins to the editor since I know it's possible but i'm not really sure how. Here is my ckeditor config in the settings.py file: customColorPalette = [ { 'color': 'hsl(4, 90%, 58%)', 'label': 'Red' }, { 'color': 'hsl(340, 82%, 52%)', 'label': 'Pink' }, { 'color': 'hsl(291, 64%, 42%)', 'label': 'Purple' }, { 'color': 'hsl(262, 52%, 47%)', 'label': 'Deep Purple' }, { 'color': 'hsl(231, 48%, 48%)', 'label': 'Indigo' }, { 'color': 'hsl(207, 90%, 54%)', 'label': 'Blue' }, ] CKEDITOR_5_CONFIGS = { 'default': { 'toolbar': ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote' ], }, 'extends': { 'blockToolbar': [ 'paragraph', 'heading1', 'heading2', 'heading3', '|', … -
Custom logger Formatter in Python
I need to use 2 different handlers, one for Elasticsearch and the other for Django. The Elasticsearch handler has already custom formatter (json-like), and is set to ERROR level. I need to pass extra args in order to create indexes in Kibana. The Django logs needs a different formatting: '[%(asctime)s] %(name)s %(levelname)-8s --> %(message)s'. But for the ERROR level I need to take care of the extra, because the message will be: f"[{pid}] {func}() - {msg} - {tb} - [{exc_name} - {exc_args}]" For the INFO i need only f"[{pid}] {func}() - {msg}" So I created a Custom Formatter Class, and it works but: I can not find a way to pass the fmt in order to add asctime and name (package.module). The LogRecord doesn't have by default them. LOG_BASE_PATH = BASE_DIR / 'logs/' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'precise': { '()': utils.DjangoCustomFormatter("[%(asctime)s] %(name)s %(levelname)s: %(message)s"), # 'format': '[%(asctime)s] %(name)s %(levelname)-8s --> %(message)s', }, 'ecs': { '()': 'ecs_logging.StdlibFormatter', }, }, 'handlers': { 'file_django': { 'class': 'logging.handlers.RotatingFileHandler', 'filename': LOG_BASE_PATH / 'django.log', 'formatter': 'precise', 'level': 'INFO', }, 'file_ecs': { 'class': 'logging.handlers.RotatingFileHandler', 'filename': LOG_BASE_PATH / 'test.log', 'formatter': 'ecs', 'level': 'ERROR' }, }, 'loggers': { 'multi_logger': { 'handlers': ['file_ecs', 'file_django'], 'level': … -
Field name `email` is not valid for model `customer`. in Multi User authentication Django Rest Framework
I am trying to create a multiple user authentication system in Django and am using onetoone field and booleans for creating profiles. But when creating serializers it throws the error "Field name email is not valid for model customer." Can someone please clarify what am I doing wrong here? models.py: from django.db import models from django.contrib.auth.models import User,AbstractBaseUser,BaseUserManager # Create your models here. class UserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError("The email must be set") if not password: raise ValueError("The password must be set") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user class user(AbstractBaseUser): is_customer = models.BooleanField(default=False) is_restaurant = models.BooleanField(default=False) email = models.EmailField(max_length=100,unique=True) USERNAME_FIELD = 'email' objects = UserManager class customer(models.Model): user = models.OneToOneField(user,on_delete=models.CASCADE) firstname = models.CharField(max_length=80) lastname = models.CharField(max_length=80) class restaurant(models.Model): user = models.OneToOneField(user,on_delete=models.CASCADE) rest_name = models.CharField(max_length=80) serializers.py:- from rest_framework import serializers from .models import * class userserializer(serializers.ModelSerializer): class Meta: model = user fields = '__all__' class cust_serializer(serializers.ModelSerializer): class Meta: model = customer user = userserializer(read_only=False) email = serializers.StringRelatedField(read_only=False,source = 'user.email') password = serializers.StringRelatedField(source = 'user.password') fields = [ 'id', 'email', 'password', 'firstname', 'lastname', ] def create(self,validated_data): user1 = user.objects.create(self,email=validated_data['email'],password=validated_data['password']) user1.is_customer = True user1.save() instance = customer.objects.create(user=user1,firstname = validated_data['firstname'],lastname = ['lastname']) return …