Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to provide binary field with Django REST Framework?
Is it possible to provide a backend endpoint where the response is a json containing some field values and a data blob? I have the following model and serializer: class NiceModel(db_models.Model): index = db_models.IntegerField() binary_data = db_models.BinaryField() class NiceSerializer(serializers.ModelSerializer): class Meta: model = models.NiceModel fields = ( "index", "binary_data", ) this serializer produces a json like the following: { "index": 1, "binary_data": "veryveryveryveryveryverylongtext" } Is this very long text a string representation of the binary data handled by DRE? If so, how can I read this data with javascript? Am I doing it the wrong way? should I create an endpoint only for the blob data and forget about the json format? Thanks in advance. -
I just setup python django and Im unable to import
I just finished setup python django I did everything in the video and I wrote the most simple code from django.shortcuts import render from django.http import HttpResponse def hello(request): return HttpResponse("<h1>Hello world!</h1>") I imported it to the url and it works as expected but the issue is I get this:It saying unable to import I dont know why it saying that bc it works well. what is wrong with the program? -
drf - How to filter on 1 item given a many to many relationship
I have 2 tables Product and Price. A product can have multiple prices. This in order to remember the old prices of the product. In my product view I have the following code: products = ProductFilter(filters, queryset=products.all()) ProductFilter is a custom filter class. The filter variable is the same as request.GET. This is what the filter looks like: class ProductFilter(django_filters.FilterSet): ... price__final_price__gte = django_filters.NumberFilter( field_name="price__final_price", lookup_expr="gte" ) price__final_price__lte = django_filters.NumberFilter( field_name="price__final_price", lookup_expr="lte" ) price__currency = django_filters.CharFilter() class Meta: model = Product fields = ["name", "external_id"] This is the problem. If product A has for example 3 prices. Product A: 1. 50$ - 2020/march 2. 20$ - 2019/dec 3. 60$ - 2019/jan When I filter, I would only like to filter on the most recent price. So if my filter had price__final_price__lte: 30 I wouldn't want this product to be selected, because the price on 2019/dec was indeed under 30, but the most current price is not. In what way do I need to change my ProductFilter class to make this possible? (Some ideas I had where to look for the closest date given the current date, but I couldn't get this to work.) Any help would be greatly appreciated. -
Clear Table data on server restart in django
I'm trying to add default data in my table in Django and then create a restful API that changes that data and when I turn the server off and restarts it again the data should be the default one. But it's not working with this code. My Migrations File(0001_initial.py) initial = True dependencies = [ ] def insertData(apps, schema_editor): Login = apps.get_model('restapi', 'Users_Details') user = Login(name="admin", email="abc@gmail.com", password="abcd123456") user.save() operations = [ migrations.CreateModel( name='Users_Details', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('email', models.CharField(max_length=100, unique=True)), ('password', models.CharField(max_length=15, validators=[django.core.validators.RegexValidator('^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.')])), ('confirm_password', models.CharField(max_length=15, validators=[django.core.validators.RegexValidator('^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.')])), ], ), migrations.RunPython(insertData) How can I reset the data to its default(initial) data every time I restart the server. -
Django rest framework csrf exempt when doing ajax post call
I'm trying to pass data via ajax POST request but getting a 403 ERROR. I've tried to use CsrfExemptMixin from braces.views but that doesn't resolve the issue. I'm new to api calls with drf so maybe my methods are incorrect. View class DialogListView(CsrfExemptMixin, viewsets.ModelViewSet): # queryset = Dialog.objects.all() serializer_class = DialogSerializer # http_method_names = ['get', 'delete'] def get_queryset(self): data = self.request.data print('helllo') print(self.request.data) # for k in data: # print(k) try: owner_profile = Profile.objects.get(user=User.objects.get(username=data.get('owner'))) opponent_profile = Profile.objects.get(user=User.objects.get(username=data.get('opponent'))) return Dialog.objects.get(Q(owner=owner_profile, opponent=opponent_profile) | Q(owner=opponent_profile, opponent=owner_profile)) except ObjectDoesNotExist: owner_profile = Profile.objects.get(user=User.objects.get(username=data.get('owner'))) opponent_profile = Profile.objects.get(user=User.objects.get(username=data.get('opponent'))) return Dialog.objects.create(owner=owner_profile, opponent=opponent_profile) -
Image missing in RSS/ATOM with Django
I'm trying to attach an image to my ATOM and RSS syndication feed thanks to the Django's documentation : https://docs.djangoproject.com/fr/1.11/ref/contrib/syndication/ I have to kind of feed : http://example.com/rss and http://mywebsite.com/atom rss.py class LatestEntriesFeed(Feed): title = "MyWebsite" link = "/" description = "Latest news" def items(self): return Articles.objects.filter(published=True).order_by('-date')[:5] def item_description(self, item): return '<![CDATA[ <img src="http://example.com/image.jpeg" /> ]]>' def item_title(self, item): return item.title def item_pubdate(self, item): return item.date def item_updateddate(self, item): return item.update def item_author_name(self, item): return item.author def item_author_link(self, item): item_author_link = Site_URL + reverse('team', kwargs={'username': item.author}) return item_author_link def item_author_email(self): return EMAIL_HOST_USER class LatestEntriesFeedAtom(LatestEntriesFeed): feed_type = Atom1Feed subtitle = LatestEntriesFeed.description So I think I have to use CDATA into the description html tag. However, in Django (version 1.11), item_description doesn't return <description> tag in the XML, but a <summary> tag. Is it fine or is it the source of the issue ? Otherwise, I tried to scan with W3C validator and I get 2 errors (or just warnings ?) 1) Self reference doesn't match document location 2) Invalid HTML: Expected '--' or 'DOCTYPE'. Not found. (5 occurrences) -
RelatedObjectDoesntExist error while trying to get current username through admin model
This is my model: def get_form_path(instance,filename): upload_dir=os.path.join('uploaded',instance.hostname,instance.Class) if not os.path.exists(upload_dir): os.makedirs(upload_dir) return os.path.join(upload_dir,filename) class Book(models.Model): Name= models.CharField(max_length=100) Class= models.CharField(max_length=100) Content =models.FileField(upload_to=get_form_path) hostname=models.ForeignKey(settings.AUTH_USER_MODEL,blank=True,on_delete=models.CASCADE) def __str__(self): return self.Name def delete(self, *args, **kwargs): self.Content.delete() super().delete(*args, **kwargs) This is form.py class BookForm(forms.ModelForm): class Meta: model=Book exclude=('hostname',) fields=('Name','Class','Content') class BookAdmin(admin.ModelAdmin): exclude=('Name','Class','Content',) form=BookForm This is my admin.py: class BookAdmin(admin.ModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'hostname': kwargs['queryset'] = get_user_model().objects.filter(username=request.user.username) return super(BookAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) def get_readonly_fields(self, request, obj=None): if obj is not None: return self.readonly_fields + ('hostname',) return self.readonly_fields def add_view(self, request, form_url="", extra_context=None): data = request.GET.copy() data['hostname'] = request.user request.GET = data return super(NotesAdmin, self).add_view(request, form_url="", extra_context=extra_context) admin.site.register(Book, BookAdmin) Im not getting where I'm going wrong? complete error line is"upload.models.Book.hostnamee.RelatedObjectDoesnotExist:Book has no hostname please guide me through this..Thanks in advance -
How do I input the newline from textarea in HTML and put that to postgresql database through Django?
I am getting an input from the user through an HTML textarea and I need to push that to database. Ex: if user enters -- "hey how are you? \n Its great to have u here." The textarea only takes "hey how are you" and saves only this to the database but I want the whole text instead. Here is the create.html <!doctype html> {% load static%} <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="{% static 'bootstrap-4.4.1-dist/css/bootstrap-grid.min.css' %}" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'bootstrap-4.4.1-dist/css/bootstrap.min.css' %}" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'styles.css' %}"> </head> <body style="background-color: lightskyblue;"> <nav class="navbar navbar-expand-lg navbar-dark bg-dark mynavbar"> <a class="navbar-brand brand" href="index">notify</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse " id="navbarSupportedContent"> <ul class="navbar-nav"> {% if user.is_authenticated %} <li class="nav-item navlinks"> <a class="nav-link" href="logout">Logout</a> </li> <li class="nav-item navlinks" style="margin-top: 9px;"> <span style="color: azure;">Hello</span><a class="nav-link" href="#" style="display: inline;">{{user.first_name}}</a><span style="color: azure;">!!</span> </li> {% else %} <li class="nav-item navlinks"> <a class="nav-link" data-toggle="modal" data-target="#exampleModalCenter2"><svg class="bi bi-person-fill" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" d="M3 14s-1 0-1-1 1-4 6-4 6 3 6 4-1 1-1 1H3zm5-6a3 … -
i'm working on the project where i need to add the operators in the data but it will gives an error to me
MY VIEWS CODE== def addoperator(request): if request.method=="POST": opera = User.objects.create_user( username=request.POST['name'], email=request.POST['email'], password=request.POST['password'] ) s=Operator() s.user=opera s.phonenumber=request.POST['number'] s.gender=request.POST['gender'] s.address=request.POST['address'] s.picture=request.FILES['userimage'] s.document=request.FILES['document'] s.save() return render(request,'Adminside/addoperators.html') else: return render(request,'Adminside/addoperators.html') MY MODELS CODE==== class Operator(models.Model): # This field is required. user = models.OneToOneField(User,on_delete=models.CASCADE,default='') # These fields are optional gender=models.CharField(max_length=200,default='') phonenumber=models.CharField(max_length=200,blank=True) address=models.CharField(max_length=200,blank=True) picture = models.ImageField(upload_to='operator/', blank=True) document = models.ImageField(upload_to='operator/', blank=True) status=models.CharField(max_length=100,default='PENDING') def isActive(self): if self.status=="ACTIVE": return True else: return False def isDisable(self): if self.status=="DISABLE": return True else: return False So, the main thing is that when i add the operator it will gives an error regarding the operator by saying that there is no user_id column in the operator model. but i only gives the user field in the operator model as you can see in the models code and i don't know how to resolve it. and i will show the error below and please help i'm stuck on this for like two to three days. and important thing for doing this i extended the auth_user tabel to enter the other fields like gender,images and phonenumber etc. MY ERROR FOR ADDING THE OPERATOR OperationalError at /admin/Adminside/operator/ no such column: Adminside_operator.user_id Request Method: GET Request URL: http://127.0.0.1:8000/admin/Adminside/operator/ Django Version: 2.2.4 Exception Type: OperationalError Exception … -
how can i configure apache with django
I want to ingrate apache server with django, but i still have error, can anyone help me plz. i install apache i configure variable environnement for apache i install wsgi i modify wsgi.py because i work with windows i make this code in httpd.conf WSGIScriptAlias / "C:/users/akm/downloads/projet/testoreal/testoreal/testoreal/wsgi_windows.py" WSGIPythonPath "C:/users/akm/downloads/projet/testoreal/testoreal/site-packages"; Order deny,allow Allow from all and i steel can't open the server Thanks -
how can I connect with mongoDB container database from Host
I'm using MongoDB container. and I want to connect to MongoDB from host through django I import "djongo"(module to use django with mongoDB) at settings.py at django. I changed many time the value of host and port but I didn't worked. DATABASES = { 'default': { 'ENGINE': 'djongo', 'ENFORCE_SCHEMA': True, 'NAME': 'mongoTest1', 'HOST': 'mongodb://localhost:17017', 'PORT': 27017, 'USER': 'root', 'PASSWORD': 'password', 'AUTH_SOURCE': 'password', 'AUTH_MECHANISM': 'SCRAM-SHA-1', } } container and I got this errors with python manage.py runserver enter image description here I think there are no problem with ports. Because I just simply bind 17017(host)->27017(mongo container) I only created "root" user at mongoDB and create db, collections to use. -
How do I join two models in Django by id?
I have two models as shown below with just a few fields: class Query(models.Model): query_text = models.TextField(blank=True, null=True) variable = models.CharField(max_length=250, blank=True, null=True) class Statistic(models.Model): query = models.ForeignKey(Query, models.DO_NOTHING, blank=True, null=True) processing_time = models.DateTimeField(blank=True, null=True) module = models.CharField(max_length=500, blank=True, null=True) My target is to perform a JOIN using the id of the two models. The SQL query equivalent to it would be : SELECT * FROM statistic S JOIN query Q ON S.query_id = Q.id I understand select_related or prefetch_related could do the trick? I don't know which one to use to perform the join. I'd appreciate some help on that. Thanks. :) -
Where to retrieve used API key in a HTTP request
I'm trying to develop an Endpoint for uploading files that is only accessible using an API key. I use the Django REST Framework API Key and my code in viewsets.py is as follows: class UploadFileViewset(viewsets.ModelViewSet): model = File queryset = File.objects.all() serializer_class = FileSerializer parser_classes = [MultiPartParser] # not sure whether required permission_classes = [HasAPIKey] def create(self, request): serializer = FileSerializer(data=request.data) # converts to JSON if serializer.is_valid(True): # validating the data model_instance = serializer.save() # saving the data into database I'd like to be able to pick out various attributes from request, for example, its source (in this case the API Key). When I debug I can't find the API key in the request. Is it because it's actually not present in the request, but is already "eaten up" beforehand in Django's middleware? I'm a bit confused why I can't retrieve it, and if I can actually get a source from the http request at all. -
Django filter after using select_related query
Going through a troble to filter that i used for select_related This is my model for Purchase: class Purchase(models.Model): amount = models.FloatField(default=1) entry_by = models.ForeignKey( User, on_delete=models.SET_NULL, related_name='ledger_entry_by', ) is_cash = models.BooleanField(default=False) and this is my model of Consume: class Consume(models.Model): amount = models.FloatField(default=1) consumed_by = models.ForeignKey( User, on_delete=models.SET_NULL, related_name='consume_entry_for', ) This is my query user_wise_cost = User.objects.annotate( difference=ExpressionWrapper( Coalesce(Sum('ledger_entry_by__amount'), Value(0)) - Coalesce(Sum('consume_entry_for__amount'), Value(0)), output_field=FloatField() ) ) The above query is working great following my requirement. I want to calculate only the amount that cash paid, i mean, if a entry is_cash=True, it will be calculated My requirement was: for example, A user Purchased 500 USD and he consumed 550 USD, that is mean, he needs to pay another 50 USD another user purchased 440 USD but he consumed 400 USD, that is mean, he will get refund 40 USD. another user example can be: a user didn't purchase anything but he consumed 300 USD, so he needs to pay 300 USD. also if a user didnt purchase anything or consumed anything, yet his data needs to show like 0. Above all the requirement was successfully achieved by that query, there is no issue at all but currently, it's calculating … -
Django Template is saying the user is not authenticated even when it says it is in the views
As the title states I have a Django template that is not authenticating. In my html I have a basic if that says: {% if request.user.is_authenticated %} But that is being evaluated to false when I login, but if I refresh the page it lets me in. Also in my part of my login views I have: if User.object.filter(username=username).exists(): user = User.objects.get(username=username) authenticate(request, username=username) print(request.user.is_authneticated) login(request, user) print(request.user.is_authenticated) return redirect(next_url) And When I check the out puts they print out as: False True Yet in the html it evaluates to False, but when I refresh the page it says it's true. (Also I know I'm authenticating with only username that's fine for the context I'm working in). Also the main issue I'm having is that it failes to login depending on the url. Ex: If I hit the website with base_url I can login as normal no problem If I hit the website with base_url/welcome I login as normal, but then I encounter the problem I described. Hopefully there is enogh info/context to give me a direction of what to do. Sorry I can't give more code -
How can I change the workflow of Django Admin
I am a beginner of Django.I want to use Django Admin to do the following things: 1-upload a excel file 2-read the header of the excel file 3-choose a part of the header to save to the database.(a list of the header with checkbox and submit button) 4-show the result to the user How can I finish the job by Django Admin?I think I should change the default workflow of the Django Admin,but how to do so? -
Django - What does objects.get return
Sorry if this seems like a really stupid question. I am building an app using Django, and at some point I am accessing the db using db.objects.get(var = val) But my question is what type object does this method return? And hw can I access the data in it? Like as a dict, list or sth else? I apologize if it is a duplicate. -
Does django cache files in MEDIA_ROOT by default?
I am using a clean install of Django 3 on a Docker container development server. I have the following settings.py: MEDIA_ROOT = '/vol/web/media/' MEDIA_URL = '/media/' And in urls.py: urlpattens = [ ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) When I upload a file using models.FileField() it displays fine via 127.0.0.1:8000/media/myfile.txt. However, when I shell into the server to find it /vol/web/media is empty. I would expect the file I upload to be in this directory, per the docs, but it is not. I have confirmed the following: 127.0.0.1:8000/media/myfile.txt returns myfile.txt even when browser cache is cleared. 127.0.0.1:8000/media/notmyfile.txt returns /vol/web/media/notmyfile.txt does not exist, so the server appears to be configured correctly I have no CACHE settings set explicitly in settings.py. What could be going on here? Does Django cache MEDIA_ROOT somehow by default? -
Dynamically Change Django Form's Fields
In the django custom registration form I have ChoiceField see in the code below but what I want is to change the fields according to the ChoiceField options. for an example if the ChoiceField is selected as Student then I want to hide the "email field" or might add extra field. I know i can do this with JavaScript but i want to change from the form. class Signup_Form(UserCreationForm): def __init__(self, *args, **kwargs): super(Signup_Form, self).__init__(*args, **kwargs) # below changing on the fields of this form. self.fields['first_name'].label = "First Name" self.fields['last_name'].label = "Last Name" self.fields['email'].label = "Email" SIGNUP_USERS_TYPES = ( ('Student', 'Student',), ('Admin', 'Admin',),) user_type = forms.ChoiceField(choices = SIGNUP_USERS_TYPES, required=True, label="Sign-up as :",) class Meta: model = User fields = ['user_type', 'first_name', 'last_name','email', 'username', 'password1', 'password2' ] -
Is there a way to take JSON from swagger 2.0 in views and convert it into HTML and send it to the template in Django?
I want to use some JSON that coming from a Swagger 2.0 generated website and parse it to send it back to a template page in my Django project. I'm asking if there is a simple way to do it, like an import (I searched but without result), thanks. def swagger_documentation(request): reply = requests.get("http://example.com:5005/swagger.json") content = reply.json() <!-- Transform content into HTML here --> data = ? return render(request, 'features/documentation/doc.html', data) (doc.html) {% extends 'layout/master.html' %} {% load static %} {% block content %} I want to show it here {% endblock %} -
Django model queries; how to join tables on foriegnkey
models.py class Person(models.Model): email = models.CharField(max_length=30) pwd = models.CharField(max_length=30) type = models.CharField(max_length=30) class user_details(models.Model): name = models.CharField(max_length=30) gender = models.CharField(max_length=30) phoneno = models.CharField(max_length=13) u_id = models.ForeignKey('Person', on_delete=models.CASCADE) class User_locations(models.Model): country = models.CharField(max_length=30) state = models.CharField(max_length=30) district = models.CharField(max_length=30) locality = models.CharField(max_length=30) u_id = models.ForeignKey('Person', on_delete=models.CASCADE) i want to query a Person with Person.type='A' and User_locations.locality='B'. i aslo want access name of a person with Person.name in the template. i now use this code in views.py person = Person.objects.filter(type='A', user_locations__location='B') what should a add to this code to access name of the person with person.name in the html template? -
Django-Rest-Framework: No Attribute HelloViewSet
I am trying to build a simple REST API. I tried adding a viewset, somehow I get an error that there is no such attribute. If I remove the viewset and just run using the APIView, it loads just fine. I am stuck. What could be the problem? What should I do to make it work? Here's the rest_profiles.views.py FILE: from django.shortcuts import render from rest_framework import viewsets from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .serializers import HelloSerializer # Create your views here. class HelloApiView(APIView): '''Test API View''' serializer_class = HelloSerializer def get(self, request, format=None): '''Returns a list of API features''' an_apiview = [ 'Uses HTTP methods as functions (get, psot, put, patch, delete)', 'Similar to Django View', 'Mapped manually to URLs' ] return Response({'message': 'Hello from HelloAPIVIew', 'an_apiview': an_apiview}) def post(self, request): '''Create Hello Message''' serializer = HelloSerializer(data=request.data) if serializer.is_valid(): name = serializer.data.get('name') message = 'Hello {0}'.format(name) return Response({'message': message}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def put(self, request): '''Handles Updates''' serializer = HelloSerializer(data=request.data) return Response({'message': 'put'}) def patch(self, request, pk=None): '''Handles partial Updates''' serializer = HelloSerializer(data=request.data) return Response({'message': 'patch'}) def delete(self, request, pk=None): '''Handles deleting items''' serializer = HelloSerializer(data=request.data) return Response({'message': 'delete'}) class HelloViewSet(viewsets.ViewSet): … -
how to assign pointfield to current user location using geolocation API
i'm new to geodjango i want to make real world gis project with geodjango to find locations i tried this class Place(models.Model): user= models.ForeignKey(Account,on_delete=models.CASCADE) address = models.CharField(max_length=100) slug = models.SlugField(unique=True,blank=True,null=True) description = models.TextField() location = models.PointField(srid=4326) views.py class PalceCreateView(CreateView): queryset = Place.objects.all() def form_valid(self,form): lat = self.request.POST['lat'] lon = self.request.POST['long'] coords = Point(lat,lon) form.instance.location = coords form.save() return super(PalceCreateView,self).form_valid(form) my forms.py class PlaceForm(forms.ModelForm): class Meta: model = Place fields = [ 'name','description','location','city','tags' ] read_only_fields = ['location'] my template <form enctype="multipart/form-data" method="post"> {% csrf_token %} <input type="hidden" name="lat" id="lat"> <input type="hidden" name="long" id="long"> {{form}} <input type='submit' value='submit'> </form> <script> navigator.geolocation.getCurrentPosition(function(location) { lat = location.coords.latitude; long = location.coords.longitude; document.getElementById('lat').val = lat document.getElementById('long').val = long }); </script> but when i submit the form it will raise this error Invalid parameters given for Point initialization. how to assign to location field thanks i'm new to geodjango if someone can recommend me an open source project i appreciate it -
How to display with javascript django project's image without static path?
js code on Windows: f_name = '06-55.jpg'; imga = '<img src="static/img/'+f_name+'" >'; $('#loaded').append(imga2); image is located at: /static/img/06-55.jpg On Windows machine it works. On linux I have same paths, but js can't find image. I'm missing something or It's just stupid mistake somewhere? -
pass if code in django, if something in data -> pass
my code is take reques.body and into data var. and if data dic in username or email or telephone then checking password. and if password collect i return token. but my code is just pass all if. i think if @ in dic it is can check key in dic i used httpie and send password and telephone or email or username. but all pass. i dont know what i mistake. plz help me! class UserLoginView(View): def post(self, request): data = json.loads(request.body) check_password = int(data['password']) check_username = 'username' if check_username in data: login_username = data['username'] login_user = User.objects.filter(username=login_username) if login_user is None: return JsonResponse({'message':'have not this ussername User'}, status = 400) elif login_user is login_username: get_user = User.objects.get(username=login_username) if check_password is not get_user.password: return JsonResponse({'message':'Not collect password'}, status = 400) else: encoded_token = jwt.encode({'user': login_user}, 'wecode', algorithm='HS256') return JsonResponse({'token':encoded_token}, status = 200) elif 'email' in data: login_email = data['email'] login_user = User.objects.filter(email=login_email) if login_user is None: return JsonResponse({'message':'have not this emain User'}, status = 400) elif login_user is login_email: get_user = User.objects.get(email=login_email) if check_password is not get_user.password: return JsonResponse({'message':'Not collect password'}, status = 400) else: encoded_token = jwt.encode({'user': login_user}, 'wecode', algorithm='HS256') return JsonResponse({'token':encoded_token}, status = 200) elif 'telephone' in data: …