Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'list' object has no attribute '_committed', Django restframework
I am new to Django in my project, I have to fetch multiple images from a post request. I am doing that using only views.py, I do not use serializers, but I am getting the following Error: AttributeError: 'list' object has no attribute '_committed'. the json structure is like following: { "images":{ "country":[ { "location":"image" }, { "location":"image" } ], "hotel":[ { "location":"image" } ], "room":[ { "location":"image" } ], "bed"[ { "location":"" } ] } } In my views.py: images = data["images"] for country_image in images: country_image_obj = CountryPicture(country=country_obj, location=images["country_images"], ) country_image_obj.save() # hotel images hotel_images = images["hotel"] for hotel_image in hotel_images: hotel_image_obj = HotelPicture(hotel=hotel_obj, location=hotel_image["hotel_images"], ) hotel_image_obj.save() # room images room_images = images["room"] for room_image in room_images: room_image_obj = RoomPicture(room=room_obj, location=room_image["room_images"], ) room_image_obj.save() # bed images bed_images = images["bed"] for bed_image in bed_images: bed_image_obj = BedPicture(bed=bed_obj, location=bed_image["bed_images"], ) bed_image_obj.save() my model.py: class CountryPicture(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True, blank=True) location = models.ImageField(upload_to='images/') class HotelPicture(models.Model): hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE, null=True, blank=True) location = models.ImageField(upload_to='images/') class RoomPicture(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE, null=True, blank=True) location = models.ImageField(upload_to='images/') class BedPicture(models.Model): bed = models.ForeignKey(Bed, on_delete=models.CASCADE, null=True, blank=True) location = models.ImageField(upload_to='images/') -
Alpine Docker Image Problem For Django with MySQL Database
I'm trying to compress the alpine docker image for Django with MYSQL database. But keep getting NameError: name '_mysql' is not defined I have got the Django with Postgres image to 100MB and its working. But with MySQL, the minimum I am able to get is around 500 with non-multi stage builds. -
django rest_framework login system [closed]
I'm using Django and djangorestframework library to make a simple login system in which I get an authentication token if everything is right, but when I'm testing it with Postman, it only accepts the credential when they are in the body section. My questions are: Is this the right thing to send these pieces of information in the body section? If not, how can I change Django to accept these fields in the header section? Also where should I put the authentication token for future uses? (Header or Body) Thank you in advance. -
Get Subscription ID of a PayPal subscription with a trial period
I need to implement a system in which users will have a trial period in their subscription and after that period the user should resume their subscription, I have achieved the same but when a user needs to be deleted the subscription has to be terminated for that when i researched I got an API to cancel a subscription via https://api-m.sandbox.paypal.com/v1/billing/subscriptions/I-BW452GLLEG1P/cancel where I-BW452GLLEG1P in the above is the subscription id, but I don't get a subscription id when I create a subscription via the method suggested on the reference page https://developer.paypal.com/docs/business/subscriptions/customize/trial-period/ please share your thoughts if you encountered similar issues thanks -
Django Serialize a field from a different model
I've 3 models like this: class Category(ClassModelo): description = models.CharField( max_length=100, unique=True ) class SubCategory(ClassModelo): pk_category = models.ForeignKey(Category, on_delete=models.CASCADE) description = models.CharField( max_length=100, ) class Product(ClassModelo): code = models.CharField( description = models.CharField(max_length=200) pk_subcategory = models.ForeignKey(SubCategory, on_delete=models.CASCADE ) and I'd like to serialize the field description in Category Model, I've tried with the below code but it doesn't work (category = serializers.ReadOnlyField(source='pk_subcategory__pk_category_description'): class ProductsSerializer(serializers.ModelSerializer): subcategory = serializers.ReadOnlyField( source='pk_subcategory.description') category = serializers.ReadOnlyField(source='pk_subcategory__pk_category_description') class Meta: model = Product fields = ("id", "description", "category", "subcategory") -
Django Membership Site
Please, what's the easiest way to implement membership functionality in Django and integrate it with Stripe/Paypal? I tried looking into using Groups but still can't figure out how this work either. Any info and/or suggestion(s) would be greatly appreciated. -
install multiple apps by one entry in INSTALLED_APPS in django (dependency)
is the concept of dependencies available in Django apps too? For example, let's say I'm building my own custom Django app "polls" that can be reused in any Django project. so whenever you need to add it to a project, you will have to add INSTALLED_APPS = [ ... 'polls.apps.PollsConfig', ] but let's also say, that this polls app depends on the Django REST Framework, so whenever you use it, you will have to add that as well INSTALLED_APPS = [ ... 'polls.apps.PollsConfig', 'rest_framework', ] And how about if it depends on even way more apps, do I have to list them all again in the settings.py of each and every project? Or, is there some way to add rest_framework as an installed app inside the apps.py of the polls app so that it's automatically installed whenever polls is installed on a project? -
Django custom user admin login session is not created
I have used a custom user model as auth user model. But while trying to login as admin in the Django admin site. The user is getting authenticated and added to the request.user but session is not created and when it redirects I guess the request.user is lost because it shows EmptyManager object. -
MSSQL - DISTINCT ON fields is not supported by this database backend
I have this form class FromToForm(Form): ModelChoiceField(queryset=TblWorkPlace.objects.all().distinct('work_place_name')) Django writes this error message: DISTINCT ON fields is not supported by this database backend Is there some workaround? -
Django: How to make form conditional?
I have a form with two fields. The user should be required to only select one of the two. Not both and not none. I tried solving this by overwriting the clean method as described in the Django Doc: forms.py class ConfigureWorkout(forms.Form): first_exercise = forms.ModelChoiceField(empty_label="select", label="Choose First Exercise", queryset=FirstExercise.objects.all(), required=False) sec_exercise = forms.ModelChoiceField(empty_label="select", label="Choose Sec Exercise", queryset=SecExercise.objects.all(), required=False) def clean(self): first_exercise = self.cleaned_data.get("first_exercise") sec_exercise = self.cleaned_data.get("sec_exercise") if first_exercise and sec_exercise: raise forms.ValidationError("Enter either a First Exercise or a Secondary Exercise.") else: return self.cleaned_data views.py def configure(request): configure_workout = ConfigureWorkout() if request.method == "GET": return render(request, "userprofile/some.html", configure_workout) else: return render(request, "app/other.html") template <form action="{% url 'configure' %}" method="POST"> {% csrf_token %} {{ configure_workout }} <input type="submit" name="configuration_completed"> </form> However, if I test this by selecting both fields in the form, there won't be an error displayed/raised. I pass the form successfully and get sent to "other.html". What am I missing? Thanks so much in advance for any help :) -
When I ran all my tests in a class I get empty database?
Problem: when I client the main green button to execute all the tests the print(x) returns [3,4]. But, when I click test_block_coaches button the print(x) returns [1,2]. I think the problem is when django delete some the delete data it does not start from a fresh database but it act like the deltion part of the test and keep counting the ides. class TestDataBase(TestClass): def setUp(self, *args, **kwargs): super().setUp(*args, **kwargs) x = PlayerFootballStat.objects.create(height=11, player=self.Player) y = PlayerFootballStat.objects.create(height=13, player=self.Player_2) def test_block_coaches(self): x = [i.id for i in Coach.objects.all()] print(x) -
Django app in Azure - OperationalError at /edit_profile/ (1366, "Incorrect string value: '\\xC5\\x9B' for column 'first_name' at row 1")
I have Django app hosted on Azure that is connected to MySQL database (Azure Database for MySQL). I wanted to edit my profile so I put ść (for testing purposes) in First name and I got the following error: OperationalError at /edit_profile/ (1366, "Incorrect string value: '\\xC5\\x9B\\xC4\\x87' for column 'first_name' at row 1") Request Method: POST Request URL: http://127.0.0.1:8000/edit_profile/ Django Version: 3.2 Exception Type: OperationalError Exception Value: (1366, "Incorrect string value: '\\xC5\\x9B\\xC4\\x87' for column 'first_name' at row 1") Traceback Switch to copy-and-paste view C:\Users\myname\Anaconda3\lib\site-packages\django\db\backends\utils.py, line 84, in _execute return self.cursor.execute(sql, params) … ▶ Local vars C:\Users\myname\Anaconda3\lib\site-packages\django\db\backends\mysql\base.py, line 73, in execute return self.cursor.execute(query, args) … ▶ Local vars C:\Users\myname\Anaconda3\lib\site-packages\MySQLdb\cursors.py, line 206, in execute res = self._query(query) … ▶ Local vars C:\Users\myname\Anaconda3\lib\site-packages\MySQLdb\cursors.py, line 319, in _query db.query(q) … ▶ Local vars C:\Users\myname\Anaconda3\lib\site-packages\MySQLdb\connections.py, line 259, in query _mysql.connection.query(self, query) … ▶ Local vars The above exception ((1366, "Incorrect string value: '\\xC5\\x9B\\xC4\\x87' for column 'first_name' at row 1")) was the direct cause of the following exception: C:\Users\myname\Anaconda3\lib\site-packages\django\core\handlers\exception.py, line 47, in inner My server parameners on Azure are: character_set_server = utf8mb4 (utf8 is not working too) collation_server = utf8_general_ci From what I know Django uses utf-8 by default so my question is what can I … -
Django form fields to HTML
I'm crating fields in a for loop and storing them in a list in a Django form. When trying to place the fields in the HTML file, it appears to be printing the object. Something like this: <django.forms.fields.IntegerField object at ...> My HTML looks like this: {% for i in form.list %} {{i}} {% endfor %} How can I convert that string to an actual input? -
How to use the FilteredSelectMultiple Widget correctly with cross-tables in Django Forms?
So I have this very basic model class Student(models.Model): id = models.AutoField(primary_key=True) first_name=models.CharField(max_length=50) last_name=models.CharField(max_length=50) ... class Course(models.Model): id = models.AutoField(primary_key=True) course=models.CharField(max_length=50) description=models.CharField(max_length=50,null=True,default=None,blank=True) ... class StudentInCourse(models.Model): StudentId = models.ForeignKey(Student, on_delete=models.CASCADE) CourseId = models.ForeignKey(Course, on_delete=models.CASCADE) def __str__(self): return str(Student.objects.get(id=self.StudentId.id)) + " in " + str(Course.objects.get(id=self.CourseId.id)) I'd like to use the widget from the admin pages to add users to group. I already found out, that the FilteredSelectMultiple, but I have no Idea on how to declare the proper Form or to get the course_id from into the Form, to select only the which aren't already assigned to a course on the left side of the widget and to populate the right side of the widget with the students already assigned. Can Somebody put me into the right direction ? here is some of the Rest of the Code, I already started, but it's wrong obviously Forms : class StudentToCourseForm(forms.Form): def __init__(self, course_id, *args, **kwargs): super(StudentToCourseForm, self).__init__(*args, **kwargs) self.choosen_students = forms.ModelMultipleChoiceField(queryset=Student.objects.filter(id=StudentInCourse.objects.filter(CourseId=course_id).values("StudentId")), label="Something", widget=FilteredSelectMultiple("Title", is_stacked=False), required=True) class Media: css = { 'all': ('/static/admin/css/widgets.css',), } js = ('/admin/jsi18n',) def clean_drg_choise(self): choosen_students = self.cleaned_data['choosen_students'] return choosen_students Views: @login_required def student_to_course(request,id=None): if request.method == 'POST': form = StudentToCourseForm(request.POST) if form.is_valid(): form.save() return redirect('student_management') else: form = StudentToCourseForm(id) … -
Getting "AuthToken.user" must be a "User" instance. in django-rest-knox
I am creating a login method using Django-rest-Knox. I have created a custom user in app using AbstractBaseUser. This is my views.py class LoginView(GenericAPIView): serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) # Load request body to serializer serializer.is_valid(raise_exception=True) # Validate data in serializer and raise an error if one is found user = serializer.validated_data # Get the validated data from the serializer token = AuthToken.objects.create(user)[1] # Create an Authentication Token for the user return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, # Get serialized User data "token": token }) Serializer.py class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() # class Meta: # model = User # fields = ('username', 'password') def Validate(self, data): user = authenticate(**data) if user: return user raise serializers.ValidationError("Incorrect Credentials") This is my custom user model class User(AbstractBaseUser): _id = models.AutoField email = models.EmailField(verbose_name='email', max_length=255, unique=True) username = models.CharField(verbose_name='username', max_length = 100, unique=True) name = models.CharField(max_length = 100) date_joined = models.DateTimeField(verbose_name="date-joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last-login", auto_now=True) category = models.CharField(max_length=50, default= "teacher") is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_teacher = models.BooleanField(default=False) is_parent = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email',] objects = UserManager() def __str__(self): # return self.email return self.username def … -
What's the best way to use the data audio files to play the audio in Django?
I have audio files and I want to read the directory (path folder) + (path filename) based on the record-id model. I discovered some resources that upload audio files as object models. but I don’t want to handle as the model, I just want to read the path. After that, I want to calling the path audio into HTML for paly/stop audio. -
ValueError at /admin/services/blog/add/blog objects need to have a primary key value before you can access their tags
i'm trying to create a blog by the admin panell. but i'm not able to save. Can you please help. Model.py class blog(models.Model): author = models.ForeignKey(User, null=True, on_delete=models.CASCADE) city_id = models.AutoField(primary_key=True) blog_title=models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) slug = models.CharField(max_length=500, blank=True) tags = TaggableManager() blog_category_name=models.ForeignKey(blog_category,on_delete=models.CASCADE,null=True,blank=True) blog_sub_category_name=models.ForeignKey(blog_sub_category,on_delete=models.CASCADE,null=True,blank=True) written_by = models.CharField(max_length=200, default='sandeep') image_banner= models.ImageField(upload_to='image_banner') medium_thumbnail = models.ImageField(upload_to='medium_thumbnail') content = RichTextField() # RichTextField is used for paragraphs is_authentic=models.BooleanField(default=False) class Meta: # Plurizing the class name explicitly verbose_name_plural = 'blog' def __str__(self): # Dundar Method return self.blog_title def save(self, *args, **kwargs): # Saving Modefied Changes if not self.slug: self.slug = slugify(self.blog_title) For some reason when I'm trying to save the tags and the data I'm getting this error -
How to select UserProfileInfo of a User with a certain PrimaryKey - Django
I'm using Django. In my function accept_request(), I'm trying to select the profile of a user with a certain PrimaryKey. Here's the function: def accept_request(request, pk): book = Book.objects.get(id=pk) print(book.owner.pk) user = request.user user_email = request.user.email owner_profile = UserProfileInfo.objects.get(user=book.owner.pk) owner_house_number = owner_profile.house_number owner_phone_number = owner_profile.phone_number owner_full_name = owner_profile.full_name r = UserRents.objects.get(book_id=pk) r.status = 1 r.save() subject = "{}, your request to rent the book, \"{}\", has been accepted.".format(user, book) body = "You had requested to rent the book, \"{}\". It's been accepted! You can head over to #{} to get the book. You can contact the owner, {}, at +91 {}. Please return the book in the same condition as it was when you got it.\n Hope you enjoy reading the book!".format(book, owner_house_number, owner_full_name, owner_phone_number) sender_email = "pfcbookclub@gmail.com" receiver_email = user_email password = "Zt2.~[3d*.[Y5&5r" # Create a multipart message and set headers message = MIMEMultipart() message["From"] = sender_email message["To"] = receiver_email message["Subject"] = subject message["Bcc"] = receiver_email # Recommended for mass emails # Add body to email message.attach(MIMEText(body, "plain")) text = message.as_string() # Log in to server using secure context and send email context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, text) return redirect("/") This … -
channel_layer.send won't call handler
I have this signal to dispatch an event when a new message is created from django.db.models.signals import post_save from channels.layers import get_channel_layer from asgiref.sync import async_to_sync from django.dispatch import receiver from .serializers import MessageSerializer from base.models import Message @receiver(post_save, sender=Message) def new_message(sender, instance, created, **kwargs): channel_layer = get_channel_layer() if created: chat_group = instance.channel.chat_group for member in chat_group.members: async_to_sync(channel_layer.send)( f"User-{member.user.id}", { "type": "chat_message_create", "payload": MessageSerializer(instance).data, }, ) this is the consumers.py import json from channels.generic.websocket import WebsocketConsumer from api.serializers import UserSerializer class ChatConsumer(WebsocketConsumer): def connect(self): user = self.scope["user"] self.channel_name = f"User-{user.id}" self.send(text_data=json.dumps(UserSerializer(user).data)) def disconnect(self, close_code): pass def chat_message_create(self, event): print("Created") self.send(text_data=json.dumps(event["payload"])) When I create a new message in the admin panel the signal gets called but it does not get dispatched through the websocket, and any debug prints in ChatConsumer.chat_message_create won't even get printed. Thanks in advanced -
Using SearchVectorFields on many to many related models
I have two models Author and Book which are related via m2m (one author can have many books, one book can have many authors) Often we need to query and match records for ingests using text strings, across both models ie: "JRR Tolkien - Return of the King" when unique identifiers are not available. I would like to test if using SearchVectorField with GIN indexes can improve full text search response times - but since the search query will be SearchVector(author__name) + SearchVector(book__title) It seems that both models need a SearchVectorField added. This becomes more complicated when each table needs updating, since it appears Postgres Triggers need to be set up on both tables, which might make updating anything completely untenable. Question What is the modern best practice in Django for adopting vectorised fulltext search methods when m2m related models are concerned? Should the SearchVectorField be placed in the through table? Or in each model? I've been searching for guides on this specifically - but noone seems to mention m2ms when talking about SearchVectorFields. I did find this old question Also, if postgres is really not the way forward in modern Django I'd also gladly take direction in something better … -
Django manytomany filter with contains
I have groups in my app which can have multiple employees and multiple modules class GroupModels(models.Model): model_choices = (('Product', 'Product'), ('Kit', 'Kit'), ('Vendor', 'Vendor'), ('Warehouse', 'Warehouse')) model = models.CharField(max_length=500, choices=model_choices) class Group(models.Model): name = models.CharField(max_length=500, default=0) modules = models.ManyToManyField(GroupModels) employees = models.ManyToManyField(Employee) owner = models.ForeignKey(User, on_delete=models.CASCADE) Now while creating permissions for a particular module e.g. Product, I want to check if the user i.e. employee in any of the groups have this module. How do I do that ? I created two groups with the user, one contains the product and other doesn't and use this : abc = Group.objects.filter(employees__pk=request.user.pk, modules__model='Product').exists() print('abc', abc) return abc Is this the right way to do this? -
Django3 + Apache2. When I use the administrator to upload image in the background, I got Server Error (500)
I'm beginner in Django. In Django3 + Apache2, when I use the administrator to upload image in the background, I got Server Error (500). I go to check the accesslog, it show ""POST /admin/mainapp/product/add/ HTTP/1.1" 500 417". But when I use command "python3 manage.py runserver" to runserver, it work well. I don't know how to solve this probelm, Please help! Following is my code: setting.py from pathlib import Path import os SECRET_KEY = 'django-insecure-ppa-x(eyccb857-@uq$5qx$srwf#%$j4i-j7s=&m8mf0l@0#9_' DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mainapp', ] 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', ] ROOT_URLCONF = 'web_2T4GAME.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'web_2T4GAME.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static'), ] STATIC_ROOT = '/var/www/staticfiles' this DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_URL = '/media/' MEDIA_ROOT = '/var/www/media' … -
Django rest framework - problem with set in settings subb app name
I have the same problem what is in this question, we're doing the same tutorial . I working on python 3.10.1, Django 4.0, django rest framework 3.13.0. When i try to change name in my category apps.py like Ankit Tiwari wrote, i get a error: ImportError: cannot import name '_Descriptor' from 'functools' (C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.496.0_x64__qbz5n2kfra8p0\lib\functools.py) But when I try like Jeet Patel nothing happens -
Update context of FormView only in certain condition
I have a code in my FormView in Django: class SearchView(LoginRequiredMixin, FormView): template_name = "dic_records/search_form.html" form_class = KokyakuForm success_url = 'search' fetched_data = [] def form_valid(self, form): print(form.cleaned_data) kokyaku_instance = FetchKokyaku(form.cleaned_data['name_search']) err_check = kokyaku_instance.connect() kokyaku_instance.get_data() if err_check is False: messages.error(self.request, "データを出力できませんでした") return super(SearchView, self).form_valid(form) kokyaku_list = list(kokyaku_instance.get_data()) if len(kokyaku_list) == 0: messages.error(self.request, "検索のデータを見つけられませんでした") return super(SearchView, self).form_valid(form) self.fetched_data = kokyaku_list return super(SearchView, self).form_valid(form) def get_context_data(self, **kwargs): """Use this to add extra context.""" context = super(SearchView, self).get_context_data(**kwargs) context['list'] = self.fetched_data return context And I would like to provide a list of value kokyaku_list to my context variable, but only if my form is valid and data are fetched from kokyaku_instance.get_data(). The code above wont pass values -
Django, anonymous user/not authenticated
I am anonymous user even though i logged in, here is views.py: class LoginView(views.APIView): def post(self, request): data = serializers.LoginSerializer(data=request.data) print(data.is_valid()) print(data.errors) print(f" HEEERE::: {data}") if self.request.method == 'POST': if data.is_valid(): auth = authenticate( username=data.validated_data['email'], password=data.validated_data['password']) print(f" email check : {data.validated_data['email']}") print(f"auth:: {auth}") if auth is not None: login(request, auth) print("Hello World") return redirect("/somelink") else: return HttpResponse("Invalid Credentials") else: return HttpResponse("Data not being validated :O") class LogoutView(views.APIView): def post(self, request): logout(request) serializers.py class LoginSerializer(serializers.Serializer): email = serializers.EmailField() password = serializers.CharField(write_only=True) def validate(self, data): email = data.get("email") print(f" email here : {email}") password = data.get("password") user = authenticate(username=email, password=password) print(f"{user} username serializer ") print(f"this is data : {data}") if user is not None: return data raise serializers.ValidationError("Incorrect Credentials") in frontend side (React): login component: import React, { useState } from 'react'; import { Link , Redirect} from 'react-router-dom'; import { connect } from 'react-redux'; import { login } from '../actions/auth'; import axios from 'axios'; import Cookies from 'js-cookie'; function Login(){ let [login,setLogin,isLoggedin] = useState({ email: '', password:'' }); let cookie = Cookies.get('csrftoken'); const { email, password } = login; function handleChange(e){ console.log(e.target.value); setLogin({ ...login, [e.target.name]: e.target.value }); } function handleSubmit(e){ e.preventDefault(); axios.post(' http://127.0.0.1:8000/login/',login,{withCredentials:true},{headers: {'Content-Type': 'application/json', 'X-CSRFToken': cookie,'Access-Control-Allow-Origin':'*'}}) .then(res => { console.log(res.data); …