Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Return response statement is not returning any response
I am creating a logout view to logout from my django restframework using simplejwt. There is no direct way to logout so only blacklisting the refresh token is the workarround. Those print statements works expectedly so it does blacklist the tokens but the return statement doesn't return anything, why is that and how may I return a Response?I am guessing the save function doesnt return anything, is it ture? class LogoutSerializer(serializers.Serializer): refresh = serializers.CharField() def validate(self, attrs): self.token = attrs['refresh'] return attrs def save(self, **kwargs): try: RefreshToken(self.token).blacklist() print('done') return Response({'msg':'token has been blacklisted'}) except TokenError: print('not done') return Response({'msg':'token is expired or blacklisted'}) views.py class LogoutAPIView(APIView): serializer_class = LogoutSerializer permission_classes = [IsAuthenticated] def post(self, request): serializer = self.serializer_class(data = request.data) serializer.is_valid(raise_exception = True) serializer.save() return Response(status = status.HTTP_204_NO_CONTENT) -
ForeignKey Reciprocation
I want to be able to see the existance of the ForeignKey, but in the other admin.py app. The one to which is the receiver of the ForeignKey. In this case, I want to be able to see the Email ForeignKey in the Client admin.py. Client App Structure: Project Client model.py Client model.py Code: class Client(models.Model): primary_key = models.AutoField(primary_key=True) unique_num = models.TextField(max_length=30) name = models.TextField(max_length=30, default='Name Not Found') number = models.TextField(max_length=30) email = models.EmailField() Email App Structure: Project Email model.py Client model.py Code: class ScheduledEmail(models.Model): primary_key = models.AutoField(primary_key=True) recipient_name = models.TextField() subject = models.TextField() message = models.TextField() datetime_sent = models.TextField(max_length=20, default='Not Yet Sent') datetime_created = models.TextField(max_length=20) recipient_email = models.EmailField(max_length=50, default='Email Not Found') sent = models.BooleanField(default=False) recipient = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='scheduled_emails_sent') -
Multiple Django sites in the same server with different databases
I'm deploying the same Django project twice in a server with different settings and databases each one. First one is a production project using production.py settings and PostgreSQL database The second one is a test project using development.py settings and Sqlite database Following this tutorial, each one has a different socket, Gunicorn configuration, Nginx site enabled and different subdomain. The problem is that when I'm trying to login into the test's project admin site I have to use the production credentials and see production data. Which is the problem here? -
After hosting the django website showing 502 bad gateway
I deployed django website in gcloud everything is done after deploying when i search the url in google its showing like 502 bad gateway -
Firefox and Chrome not recognising json [closed]
I have a fetch request from an api , that collects data for the user and then pushes that data into arrays inside of my js script. This function works perfectly in Safari , but in Chrome and Firefox it comes back as a '500 Internal error'. I checked the content-type of the Response Headers, in safari it comes back as 'application/json' , but in chrome and firefox its 'text/plain; charset=utf-8' , can someone explain why this is happening and how to fix, I'm still new to JS. Here is my fetch function : var trackNames = []; var trackUrl = []; var albums = []; async function getUserTracks() { try { await fetch("https://www.soundpro.city/music/music_all?format=json", { method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }) .then(response => { const contentType = response.headers.get('content-type'); if (!contentType || !contentType.includes('application/json')) { throw new TypeError("Oops, we haven't got JSON!"); } return response.json(); }) .then(data => { for (item of data) trackNames.push(item['title']), trackUrl.push(item['track']), albums.push(item['artist_name']) }) } catch(error) { console.log(error) } } -
Cannot send kendo-react-pdf from react to django using axios
Currently i'm trying to send a PDF file that is generated when the button is pressed (using kendo-react-pdf) to my Django API but it won't work. Here's my Django View: class quizPdfView(APIView): parser_classes = [MultiPartParser,FormParser] def post(self,request): try: print(request.data) quizPDF.objects.create(user=request.user,pdf=request.data['pdf']) return Response(status=status.HTTP_200_OK) except Exception as e: print(e) return Response(status=status.HTTP_400_BAD_REQUEST) Here's how i generated the PDF using kendo-react: const pdfExportComponent = useRef(null); <PDFExport ref={pdfExportComponent} paperSize="A4" margin="1cm"> # DATA return ( <> </PdfExport> <Button onClick = {saveToPDF} > Save </Button> </> ); And here's 'saveToPDF' function : const saveToPDF = (e) => { var file = pdfExportComponent.current axiosInstance.post('/uploadpdf/',{ pdf:file // Sending the PDF to django }).then((res) => { console.log(res.status) }) .catch((function (error) { console.log(error) })) pdfExportComponent.current.save() //User saves it on his //local computer //**that works properly** } The problem must be caused by kendo-react-pdf because i tested the django endpoint using postman (with a normal .pdf file) and everything works properly. Does anyone know how am i supposed to send the kendo-react-pdf? Thank you! -
Would implementing product images in an e-commerce store as a separate database entity take a long time to query? Is there a better approach?
I am creating an e-commerce store in Django and am currently trying to decide between implementing product images as an entity of their own then linking to the product by a foreign key or putting image fields as attributes in the product entity. I would prefer doing the image as a separate entity because then, I will not have a limit to the number of images I can add to a product. My concern is will this come at a huge speed cost for the customers using my website i.e. for my product listing page, I would have to, for each product, filter (query) the images corresponding to the particular product. Are there better, more optimal approaches to doing this? I would give a number of rows in the images table but, I have no idea how many images I will wind up having for the store. -
Django/Django Rest How do I save user device to prevent tedious 2FA on every login?
Hello I have been working with Django Rest Framework and I successfully made Two factor authentication Login based on Email OTP but one thing I want to improve is I want to improve login and save user's device so that repeated 2FA(Two factor Authentcation) can be minimized? here is certain instance of code I did for sending otp on user email. serializers.py class UserLoginSerializer(serializers.Serializer): email = serializers.EmailField() password = PasswordField() views.py classUserLoginView(generics.CreateWithMessageAPIView): """ Use this end-point to get login for user """ message = _('Please check your email for 6 digit OTP code.') serializer_class = serializers.UserLoginSerializer def perform_create(self, serializer): usecases.UserLoginWithOTPUseCase(self.request, serializer=serializer).execute() usecases.py class UserLoginWithOTPUseCase(CreateUseCase, OTPMixin): def __init__(self, request, serializer): self._request = request super().__init__(serializer) def execute(self): self._factory() def _factory(self): credentials = { 'username': self._data['email'], 'password': self._data['password'] } self._user = authenticate(self._request, **credentials) if self._user is not None: """ Sends email confirmation mail to the user's email :return: None """ code = self._generate_totp( user=self._user, purpose='2FA', interval=180 ) EmailVerificationEmail( context={ 'code': code, 'uuid': self._user.id } ).send(to=[self._user.email]) else: raise PermissionDenied( { 'authentication_error': _('User name or password not matched') } ) I am confused how can I allow or save device to prevent repetitive 2FA. -
verify validation code in django rest framework
I'm trying to verify email by sending a code, the first step is to generate the code wheneever the user enters his email, send him the code in the mail then verify this code and return a response. that's how i'm approaching the problem: I created a model named Email_for_Verification ith two fields (email , code) the code is generated randomly, i create an instance of this model when the user enters his email, i send the generated code on email, in the second step, the user enters the received code, and i'm proceeding to the validation with a View named : Verify_code. but i'm encountring an error 'QuerySet' object has no attribute 'code' i have the follwing auestions is it the true approach ? why am i encountring this error ? Here is my code: Models.py def generate_activation_code(): return int(''.join([str(random.randint(0,10)) for _ in range(6)])) class Email_for_Verification(models.Model): email = models.EmailField( max_length=100, verbose_name='email', unique=True) code = models.CharField(max_length=6, default=generate_activation_code) Views.py class Verify_code(APIView): def post(self, request): data = request.data code = data.get('code') email = data.get('email') email_for_verification = models.Email_for_Verification.objects.filter(email=email) if code == email_for_verification.code: return Response({"valid" : "Valid code", "email": email}, status=status.HTTP_404_NOT_FOUND) Response sent in browsable api: { "email":"dummy@mail.com", "code":487954 } Please note that i … -
Access query parameters using axios
So I am using React in the frontend and Django in the backend and I am currently doing the API integration for which I am using Axios. So in the frontend side I am calling a URL like this http://localhost:3000/attempt/?quiz_id=6 and I want the quiz_id = 6 so that I can use this afterward to access data in the backend. I am not sure how to do this, I am new to Web Development. It would be great if you can tell me what should I do. I am using Functional components if that helps. Thanks in advance -
How to auto increment a class variable on django model instance creation?
I am trying to auto increment a model (class variable ) by using django signals. It is working fine but only each time I do switch off my computer the count restart to zero. I do not know what I am doing wrong exactly. Here is the models.py class Project(models.Model): Count = 0 manager = models.ForeignKey( User, related_name="project_managing", on_delete=models.SET_NULL, blank=True, null=True, ) class Saga(models.Model): status = ( ("Do", "Done"), ("Td", "To do"), ("Ir", "In Review"), ("Un", "Under Review"), ("Ap", "Approved"), ("Ca", "Cancelled"), ) name = models.CharField(max_length=45) epic_project = models.ForeignKey( Project, on_delete=models.CASCADE, related_name="sagas", blank=True, null=True ) epic_status = models.CharField(max_length=2, blank=True, null=True, choices=status) epic_key = models.CharField(max_length=30, blank=True, null=True) Here is the signals.py @receiver(pre_save, sender=Saga) def epicKey(sender, instance, *args, **kwargs): if not instance.epic_key: instance.epic_key = ( instance.epic_project.key + "-" + str(instance.epic_project.Count + 1) ) instance.epic_project.__class__.Count += 1 Don't really know why it is re-initializing the count variable. -
Django API: How to get all objects that match certain value in UUID field
when trying to query objects on their foreignkey field, I dont manage to get any details. The company ID is and uuid (uuid4) field. I have a Model called "contacts": class Contact(models.Model): firstname = models.CharField(max_length=35) lastname = models.CharField(max_length=35) company = models.ForeignKey(Company, on_delete=models.CASCADE) I want to get all Contacts, that work for the same company. Therefore I have created a ListAPIView whitin views.py Views.py class ContactViewSet(viewsets.ModelViewSet): queryset = Contact.objects.all() serializer_class = ContactSerializer class CompanyContactsListView(generics.ListAPIView): serializer_class = ContactSerializer def get_queryset(self): company = self.kwargs['company'] return Contact.objects.filter(company=company) And to get a URL I added the path in urls.py urlpatterns = [ path('', include(router.urls)), path('contacts/<uuid:company>/', CompanyContactsListView.as_view(), name='contacts') ] Problem is, that when i try to go for that path and enter an UUID of an company that exists and has related contacts, I get the following error HTTP 404 Not Found Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Not found." } Is it possible, that my URL is wrong and therefore cant query the ListAPIView? Because I want result like that: [ { "id": 1, "firstname": "Joshuah", "lastname": "Bankhurst", "company": "e871c47b-9b91-4cf9-94a6-e8135510c11d" }, { "id": 2, "firstname": "Clayborn", "lastname": "Sylett", "company": "e871c47b-9b91-4cf9-94a6-e8135510c11d" } ] Thanks in advance! -
Django : Quering data from related models
So i use Django 3.2.7 and i would like to query all orders from a customer. Models.py class Order(models.Model): STATUS=( ('Pending','Pending'), ('Out for Delivery','Out for delivery'), ('Delivered','Delivered'), ) customer = models.ForeignKey(Customer,null=True, on_delete=models.SET_NULL) product = models.ForeignKey(Product,null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=200, null=True, choices=STATUS) Views.py def customer(request,pk): customer = Customer.objects.get(id=pk) orders = customer.order_set.all() my_context={ 'customer':customer, 'orders':orders } return render(request, 'accounts/customer.html', context=my_context) Urls.py path('customer/<str:pk>/', views.customer), Template {% for order in orders %} <tr> <td> {order.product} </td> <td> {order.product.category} </td> <td> {order.date_created} </td> <td> {order.status} </td> <td><a href="">Update</a></td> <td><a href="">Delete</a></td> </tr> {% endfor %} My problem is that instead of printing the actual data on the template is prints the query data. I think the problem is at orders = customer.order_set.all(). What im doing wrong? -
Turning RabbitMQ off makes Django to freeze
I have this class in my project: class CreateReportConsumer(AsyncJsonWebsocketConsumer): async def connect(self): if self.scope['user'].is_authenticated: await self.accept() else: await self.close(401) async def disconnect(self, code): await self.close(code) async def receive_json(self, content, **kwargs): task_id = content.get('task_id') if task_id: result = AsyncResult(task_id) start = datetime.now() while not result.ready(): await sleep(1) if datetime.now() - start > timedelta(seconds=60 * 5): await self.send_json(self.construct_answer([False, 'Connection timed out'])) await self.close(500) break else: if result.state == 'SUCCESS': if len(result.result) == 2: await self.send_json(self.construct_answer(result.result)) await self.close(200) else: await self.close(500) else: await self.send_json(result.result) await self.close(500) else: await self.close(500) def construct_answer(self, data): return {'success': data[0], 'message': data[1]} It gets result from Celery task, when someone using this. But if I turn RabbitMQ off (I am using docker container for that), it freezes. Is there any way of avoiding that? I have tried using pika, but with the same result. Thanks everybody. -
module 'keras.optimizers' has no attribute 'Adam'
when i run this python FlappyBird_AI.py -m train this error occured AttributeError: module 'keras.optimizers' has no attribute 'Adam' -
ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'leads.user', but app 'leads' doesn't provide model 'user'
i'm making crm when i type python manage.py migrate i got this error: ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'leads.user', but app 'leads' doesn't provide model 'user'. if you wan't more detail you can tell me i'm little bit beginner here's settings.py AUTH_USER_MODEL = 'leads.User' here's models.py from django.db import models from django.contrib.auth.models import User, AbstractUser class User(AbstractUser): pass class Lead(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) phone = models.BooleanField(default=False) agent = models.ForeignKey("Agent",on_delete=models.CASCADE, null=True) class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) -
Access data after the Question mark(?) [closed]
Suppose I have a URL like this given below and I want to access the quiz_id parameter. http://localhost:3000/attempt/?quiz_id=6 How do I make this possible using Axios and in Django? -
Question regarding to Reactjs and Django, the use of serializer in django-rest-framework
I have a question regarding to the serializer from Django-rest-framework and Reactjs. My question is that can the serializer work itself without the django model? since I don't need to save anything in database. I just want to do post request to backend, and it will take the data and run the ML model, and show the result back to frontend. After that the record will be cleared. Will it be possible to do so without using model? Can I only save serializer instance and give a get request to show it in the frontend? Thank you! -
how to deploy a django project with apache and basic authentication?
I've finished a django project and i want to deploy that on ubuntu server with public ip. but i don't want this project visible to public and i want to set an basic authentication for that. i thought if i set apache basic authentication for a specefic port (for example 8000) and then run django on this port, everything will be ok, but i faced the Listening port for another service (apache) problem and i can't run django on this port. how i can solve this problem? here is my apache config: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> <VirtualHost *:8000> <Location /> #the / has to be there, otherwise Apache startup fails Deny from all AuthUserFile /usr/local/etc/httpd/users AuthName authorization AuthType Basic Satisfy Any require valid-user </Location> DocumentRoot /var/www/html/project ServerName teamproject.example </VirtualHost> -
Websocket disconnecting again and again in django
I am trying to build a one on one chat application using django channels and websockets.I am following this tutorial https://youtu.be/RVH05S1qab8.I am getting this error when I try http://127.0.0.1:8000/raunak2/ in the url : [Failure instance: Traceback: <class 'ValueError'>: No route found for path 'raunak2/'. C:\Users\lenovo\Envs\lend\lib\site-packages\autobahn\websocket\protocol.py:2841:processHandshake C:\Users\lenovo\Envs\lend\lib\site-packages\txaio\tx.py:366:as_future C:\Users\lenovo\Envs\lend\lib\site-packages\twisted\internet\defer.py:191:maybeDeferred C:\Users\lenovo\Envs\lend\lib\site-packages\daphne\ws_protocol.py:72:onConnect --- <exception caught here> --- C:\Users\lenovo\Envs\lend\lib\site-packages\twisted\internet\defer.py:191:maybeDeferred C:\Users\lenovo\Envs\lend\lib\site-packages\daphne\server.py:200:create_application C:\Users\lenovo\Envs\lend\lib\site-packages\channels\staticfiles.py:41:__call__ C:\Users\lenovo\Envs\lend\lib\site-packages\channels\routing.py:54:__call__ C:\Users\lenovo\Envs\lend\lib\site-packages\channels\security\websocket.py:37:__call__ C:\Users\lenovo\Envs\lend\lib\site-packages\channels\sessions.py:47:__call__ C:\Users\lenovo\Envs\lend\lib\site-packages\channels\sessions.py:145:__call__ C:\Users\lenovo\Envs\lend\lib\site-packages\channels\sessions.py:169:__init__ C:\Users\lenovo\Envs\lend\lib\site-packages\channels\middleware.py:31:__call__ C:\Users\lenovo\Envs\lend\lib\site-packages\channels\routing.py:150:__call__ ] WebSocket DISCONNECT /raunak2/ [127.0.0.1:65338] I didn't get a perfect solution for this problem but I have solutions like removing '$' from the URL from routing.py but this is not working. My routing.py: application= ProtocolTypeRouter({ 'websocket':AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter([ re_path(r"^messages/(?P<username>[\w.@+-]+)", ChatConsumer), ] ) ) ) }) My app urls.py: urlpatterns=[ path("inbox",InboxView.as_view()), re_path(r"^(?P<username>[\w.@+-]+)/", ThreadView.as_view()), ] JS code: <script src="https://cdnjs.cloudflare.com/ajax/libs/reconnecting-websocket/1.0.0/reconnecting-websocket.min.js" integrity="sha512-B4skI5FiLurS86aioJx9VfozI1wjqrn6aTdJH+YQUmCZum/ZibPBTX55k5d9XM6EsKePDInkLVrN7vPmJxc1qA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script> var loc=window.location var formData=$("#form") var msgInput=$("#id_message") var chatHolder=$("#chat-items") var me=$("#myUsername").val() var wsStart='ws://' if(loc.protocol=='https:'){ wsStart='wss://' } var endpoint =wsStart + loc.host + loc.pathname var socket= new ReconnectingWebSocket(endpoint) socket.onmessage=function(e){ console.log("message",e) var chatDataMsg=JSON.parse(e.data) chatHolder.append("<li>"+ chatDataMsg.message +"via"+ chatDataMsg.username +"</li>") } socket.onopen=function(e){ console.log("open",e) formData.submit(function(event){ event.preventDefault() var msgText=msgInput.val() // chatHolder.append("<li>"+ msgText + " via "+me + "</li>") // var formDataSerialized=formData.serialize() var finalData={ 'message': msgText } socket.send(JSON.stringify(finalData)) // msgInput.val('') formData[0].reset() }) } socket.onerror=function(e){ console.log("error",e) } socket.onclose=function(e){ console.log("close",e) } </script> pip freeze: aioredis==1.3.1 asgi-redis==1.4.3 … -
How to update user password and store inside the database using django
I am trying to allow the admin to update the staff password, email address and username but the new password, email address and username is not updated into my database, did I do anything wrong in the code? The images below is how the main page looks like: This images show the next page which is the page that the staff password, username and email address will be updated: views.py def update(request, id): context = {} user = get_object_or_404(User, id=id) if request.method == "POST": user.save() return redirect("/allstaff") return render(request, 'allstaff.html', context) urls.py from django.urls import path from . import views urlpatterns = [ #path('', views.index, name='index'), #path('login/', views.login_view, name='login_view'), path('register/', views.register, name='register'), path('adminpage/', views.admin, name='adminpage'), path('customer/', views.customer, name='customer'), path('logistic/', views.logistic, name='logistic'), path('forget/', views.forget, name='forget'), path('newblock/', views.newblock, name='newblock'), path('quote/', views.quote, name='quote'), path('profile/', views.profile, name='profile'), path('adminprofile/', views.adminprofile, name='adminprofile'), path('', views.login_user, name='login'), path('home/', views.home, name='home'), path('allstaff/', views.allstaff, name='allstaff'), path('delete/<int:id>/', views.delete, name='delete'), path('update/<int:id>/', views.update, name='update'), path('logout/', views.logout_view, name='logout'), path('register/', views.register_view, name='register'), path('edit-register/', views.edit_register_view, name='edit_register'), ] updatestaff.html <!doctype html> {% extends "home.html" %} {% block content %} {% load static %} <html lang="en"> <head> <style> .button { background-color: #38d39f; border-color: #38d39f; color: white; padding: 10px 20px; text-align: center; display: inline-block; margin: 4px 2px; cursor: pointer; … -
Update key value in JSONField()
I'm trying to bulk update lots of records (3.2 million). This is my model: class MyModel(models.Model): stats = JSONField() Where stats is typically saved as: { "my_old_key": [{"hey": "Hello World"}] } I want to update it so that only the key changes it's value and final stats look like this (though there are records with "my_new_key" already so preferably skip those somehow): { "my_new_key": [{"hey": "Hello World"}] } I can do it in Python but it works really slowly.. I've tried on ~10k records with batching approach from this link so that the queryset is not fetched entirely into the memory. Final solution looked like this: def update_queryset(queryset) -> None: for stat in queryset: dictionary = stat.stats if "my_old_key" in dictionary: dictionary["my_new_key"] = dictionary.pop("my_old_key") stat.save() It does work but unfortunately it works too slowly :(. I thought about not fetching it to python at all and working purely on database somewhat like this answer suggested but didn't manage to make it work. Any suggestions on how I can speed it up / write RawSQL / make the jsonb_set approach work? -
You are trying to add a non-nullable field 'agent' to lead without a default; we can't do that (the database needs something to populate existing row
i'm making crm when i type python manage.py makemigrations i got this error: You are trying to add a non-nullable field 'agent' to lead without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit, and let me add a default in models.py Select an option: Here's my models.py: from django.db import models from django.contrib.auth.models import User, AbstractUser class User(AbstractUser): pass class Lead(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) phone = models.BooleanField(default=False) agent = models.ForeignKey("Agent",on_delete=models.CASCADE) class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Here's my settings.py: """ Django settings for crm project. Generated by 'django-admin startproject' using Django 3.1.4. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '#zi%h*+ya0z(xi6j&^3uxvv$ak3=lj5wl5&q$zh3pwv9gwk03x' # SECURITY WARNING: don't run with debug turned on in production! DEBUG … -
how i get primary key in string format in django rest framework
i'm currently working on django rest framework project and the requirement of output of the response is described below. if any one have an idea about this, it will be very helpful for me. currently i'm getting output like this: { "status": true, "message": "User Details", "Detail": { "id": 1, "phone": "9874563120", "first_name": "Crish", "birthdate": "1989-09-16", "age": 32, "email": "crish@gmail.com", } } But i want to get output like this: { "status": true, "message": "User Details", "Detail": { "id": "1", #in string formate "phone": "9874563120", "first_name": "Crish", "birthdate": "1989-09-16", "age": "32", #in string formate "email": "crish@gmail.com", } } what change should i make to gat this type of output! -
Contrib-auth-validate give None even when input is correct
Here is my Code: class LoginSerializer(serializers.Serializer): isd = serializers.IntegerField(write_only=True, required=False) email = serializers.CharField(required=False, source='username') phone = serializers.CharField(required=False) username = serializers.CharField(required=False) password = PasswordField(required=True) def create(self, validated_data: dict): if not validated_data.__contains__('username'): print("validated_data",validated_data) validated_data['username'] = validated_data['phone'] print("validated_data",validated_data) user: AppUser = authenticate(**validated_data) print("user",user) if not user or not user.is_active: raise AuthenticationFailed('Username or password is incorrect.') print("user",user) return user and Here is output: validated_data {'isd': 91, 'phone': '123', 'password': '123'} validated_data {'isd': 91, 'phone': '123', 'password': '123', 'username': '123'} user None Forbidden: /auth/user/login/ Even though im using same username and password From django admin user: AppUser = authenticate(**validated_data) print("user",user) is giving me None Value