Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'>' not supported between instances of 'decimal.Decimal' and 'QuerySet' How do you cange a QuerySet to a decimal or get access to the values in it?
I am trying to make an e-commerce site (CS50 Project 2) that allows the user to make a bid if their bid is greater than or equal to the listing price and greater than all other bids. I have been able to check if the bid is greater than the listing price but need help checking if it is greater than the other bids. I am receiving this error message. '>' not supported between instances of 'decimal.Decimal' and 'QuerySet'. I know that means I am comparing two different types of values, but how do I get change the QuerySet to a decimal or get direct access to the values within the QuerySet? views.py def listing(request, id): #gets listing listing = Listings.objects.get(id=id) #code for forms listing_price = listing.bid comment_obj = Comments.objects.filter(listing=listing) comment_form = CommentForm() bid_form = BidsForm() comment_form = CommentForm(request.POST) bid_form = BidsForm(request.POST) bid_obj = Bids.objects.filter(listing=listing) other_bids = bid_obj.all() if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.listing = listing comment.user = request.user comment.save() if bid_form.is_valid(): new_bid = bid_form.cleaned_data.get("bid") if (new_bid >= listing_price) and (new_bid > other_bids): bid = bid_form.save(commit=False) bid.listing = listing bid.user = request.user bid.save() else: return render(request, "auctions/listing.html",{ "auction_listing": listing, "form": comment_form, "comments": comment_obj, "bidForm": bid_form, "bids": bid_obj }) else: return … -
Why is Django questionnaire app not recognizing answer choices after deploying with Apache and MySQL?
I am currently trying to deploy my Django project through Apache and MySQL. All of my project apps are working well except for my questionnaires app. I am not able to record responses in the database and getting an error that says [{'id': ['Select a valid choice. That choice is not one of the available choices.']}]. I am confused because this app was working well when I was running my project through my local server and Django's default SQLite database. There are two questionnaires in my app: one is a mood board where the user selects a picture that best represents how they are feeling (I am not trying to record the actual image, just the name of the image), and the second is the Edinburg Postnatal Depression Scale, it is a multiple-choice survey that has no pictures. Can someone please give me advice as to why the app is not recognizing the answer choices? Here is my models file: User = settings.AUTH_USER_MODEL class Questionnaire(models.Model): name = models.CharField(max_length=255) text = models.CharField(max_length=200) def __str__(self): return self.name class Question(models.Model): text = models.CharField(max_length=200) questionnaire = models.ForeignKey(Questionnaire, on_delete=models.CASCADE, related_name='questions') def __str__(self): return self.text class Answer(models.Model): question = models.ForeignKey(Question, models.SET_NULL, blank=True, null=True, related_name='answerlist') questionnaire = … -
django FieldError: Cannot resolve keyword 'category_name_contains' into field. Choices are: category, description, id, image, name, order, price
I want to build a food delivering app, but facing this error. "FieldError: Cannot resolve keyword 'category_name_contains' into field. Choices are: catego ry, description, id, image, name, order, price" this is the query.py try: model = field.model._meta.concrete_model except AttributeError: # QuerySet.annotate() may introduce fields that aren't # attached to a model. model = None else: # We didn't find the current field, so move position back # one step. pos -= 1 if pos == -1 or fail_on_missing: available = sorted( [ *get_field_names_from_opts(opts), *self.annotation_select, *self._filtered_relations, ] ) raise FieldError( "Cannot resolve keyword '%s' into field. " "Choices are: %s" % (name, ", ".join(available)) ) break this is the view.py from ast import Return from multiprocessing import context from django.shortcuts import render from django.views import View from .models import MenuItem, Category, OrderModel class Index(View): def get(self, request, *args, **kwargs): return render(request, 'customer/index.html') class About(View): def get(self, request, *args, **kwargs): return render(request, 'customer/about.html') class Order(View): def get(self, request, *args, **kwargs): # get every item from each category appetizers = MenuItem.objects.filter( category_name_contains='Appetizer') main_course = MenuItem.objects.filter( category_name_contains='Main Course') desserts = MenuItem.objects.filter(category_name_contains='Dessert') drinks = MenuItem.objects.filter(category_name_contains='Drink') # pass into context context = { 'appetizers': appetizers, 'main_course': main_course, 'desserts': desserts, 'drinks': drinks, } # render the templates … -
currently learning Django and keep getting this error wheni try to runserver
i am a beginner learning using a tutorial. but i keep getting an error that isnt letting me move forward. I have attached an image with the full message ImportError: cannot import name 'Path' from 'django.urls' (C:\Python\Python310\lib\site-packages\django\urls_init_.py) -
Submit Button breaks HTML render with Django
I'm working on a simple site, just for learning some Django. I'm having troubles when trying to submit a form in order to search for something in my database. All the site is working fine, but when I look for something in that request, the web explorer just shows the raw HTML instead of rendering it. Here I share my view: from django.http import HttpResponse from django.shortcuts import render from AppFinal.models import Usuario, Direccion, Estudio from AppFinal.forms import UsuarioFormulario, def buscarUsuario(request): return render(request, 'AppFinal/buscarUsuario.html') def buscar(request): if request.GET['nombre']: nombre=request.GET['nombre'] usuarios = Usuario.objects.filter(nombre__icontains=nombre) return render(request, 'AppFinal/resultadoBusqueda.html', {'usuarios': usuarios}, {'nombre': nombre}) else: respuesta = 'No enviaste datos' return render(request, 'AppFinal/resultadoBusqueda.html', {'respuesta':respuesta}) def resultadoBusqueda(request): return render(request, 'AppFinal/resultadoBusqueda.html') This is the URLs file: from xml.etree.ElementInclude import include from django.urls import path from AppFinal import views import AppFinal urlpatterns = [ path('', views.inicio, name='Inicio'), path('buscarUsuario', views.buscarUsuario, name= 'buscarUsuario'), path('resultadoBusqueda', views.resultadoBusqueda , name= 'resultadoBusqueda'), path('usuario', views.usuario, name= 'usuario'), path('buscar/', views.buscar), ] This is the HTML where you look for a specific item in the database: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="/AppFinal/buscar/" method="GET"> {% csrf_token %} <input type="string", name= "nombre", id= "nombre"> <input type="submit", … -
Django Html and plots to PDF
I am using the Django application to generate some graphs using Plotly so I tried to generate a pdf file of the following plots of my HTML page is: <center> <p class="lead"><strong><em>&nbsp;All Plots&nbsp;</em></strong></p></center> <div class="row"> <div class="col-md-6" > {{ sunburst|safe}} </div> <div class="col-md-6" > {{ sunburst2|safe}} </div> </div> and my url.py : path('export_pdf/', views.export_pdf, name='export_pdf'), and the views.py; def export_pdf(request): df = px.data.gapminder().query("country=='Canada'") fig = px.line(df, x="year", y="lifeExp", title='Life expectancy in Canada') df2 = px.data.gapminder().query("continent=='Oceania'") fig2 = px.line(df2, x="year", y="lifeExp", color='country') chart = fig.to_html() chart2 = fig2.to_html() context= { 'sunburst':chart, 'sunburst2':chart2, } return render(request, 'Home/Reporting/part_pdf.html',context) I tried some code from this page but I can't generate the file any help? https://plotly.com/python/v3/pdf-reports/ are there any other methods for doing that (html page with plots and tables)? All my best -
Understanding CORS cookies
I have been trying for some time to deploy a web application i built, using reactjs for the Frontend and Django for the backend. After struggling with django configurations i managed to make the sessions work when both FE and BE are running locally, so the next step was deploying the BE on a remote host and i chose Heroku, with a docker setup, while i kept the FE running locally to test the BE deployment. This completely broke the django sessions i relied upon, as the BE was sending the relevant cookie to FE, but the FE was not including it in the next request, making it completely useless (include credentials did not solve the issue). After trying to mess with every CORS configuration on the Server side,(cors-headers) i came to the conclusion that browsers simply don't allow these cross-domain cookies. Meaning the FE can receive the Cross-domain cookie from the BE, but no matter what it will not include it in the next request. This leads me to 2 questions: Is my understanding of the issue correct? Meaning it really can't be done with cross-domain BE an FE? If so, is the only approach having FE and BE … -
Getting metrics on a website using django or JS?
I need to get metrics such as: Speed mouse movement, Click rate, and similar. There are 2 questions: How can I get these metrics from the site using JS, Django or other tools. Are there any other metrics that can be tracked? -
I can't find a host for my python and django website
I've created a website using Django framework. I have HTML CSS Python and SQL. I was able to put python into my index.html thanks to : https://docs.djangoproject.com/en/4.0/ref/templates/language/#variables Regarding python I have a script.py that generates a list of numbers L = [120, 140.65, etc] This script updates every 10 minutes because the numbers change L = [122.2, 140.85, etc] Then this list is imported into MySQL. So the DB changes every 10 minutes. Finally, a table is generated on my site using index.html and css with the updated numbers every 10 minutes. My website : --index.html --style.css --script.py --MySQL database The problem is, how can I find a website host who will automatically run my script.py (which will update my website every 10 minutes), which will understand python in html (this: {% for x in story_list %} ) and which will host my database. Thank you for your help! : Sorry for my bad english -
error 'FloatField' object has no attribute 'aggregate' - in a report in Django with sum of totals
I try to generate in a list with the total sales per month in the current year. In my model I have the total field, which is the total of each sale. I generate a loop (for) of 12 passes, one for each month, and I want to obtain the total of each of the months. This is the Model class Sale(models.Model): cli = models.ForeignKey(Client, on_delete=models.CASCADE) date_joined = models.DateField(default=datetime.now) subtotal = models.DecimalField(default=0.00, max_digits=9, decimal_places=2) iva = models.DecimalField(default=0.00, max_digits=9, decimal_places=2) total = models.DecimalField(default=0.00, max_digits=9, decimal_places=2) def __str__(self): return self.cli.names def toJSON(self): item = model_to_dict(self) item['cli'] = self.cli.toJSON() item['subtotal'] = format(self.subtotal, '.2f') item['iva'] = format(self.iva, '.2f') item['total'] = format(self.total, '.2f') item['date_joined'] = self.date_joined.strftime('%Y-%m-%d') item['det'] = [i.toJSON() for i in self.detsale_set.all()] return item class Meta: verbose_name = 'Venta' verbose_name_plural = 'Ventas' ordering = ['id'] This is the view where the error occurs... from django.views.generic import TemplateView from datetime import datetime from django.db.models.functions import Coalesce from django.db.models import * from Curso3App.models import Sale class DashboardView(TemplateView): template_name= 'Curso3App/dashboard.html' def get_GraficoVentasPorMes(self): data=[] year = datetime.now().year for mes in range(1,13): total = Sale.objects.filter(date_joined__year = year,date_joined__month = mes) total = total.aggregate(r = Coalesce(Sum('total'), 0)).get('r',0).output_field=FloatField() #total = total.aggregate(r = Coalesce(Sum('total'), 0)).get('r',0).output_field=FloatField() data.append(total) print('total ',total) return data def get_context_data(self, **kwargs): … -
populate social account extra_data
I am new to Django, and I am trying to add social login with social applications (Facebook, Google, Twitter) for a flutter application with allauth + dj_rest_auth. However I am facing difficulties trying to populate the social account provided by allauth to my custom user model. The User model. (models.py) class UserManager(BaseUserManager): use_in_migrations: True def _create_user(self, email, name, password, **extra_fields): if not email: raise ValueError("The given email must be set") if not name: raise ValueError("The given name must be set") email = self.normalize_email(email) user = self.model(email=email, name=name, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, name, password=None, **extra_fields): extra_fields.setdefault("is_staff", False) extra_fields.setdefault("is_superuser", False) return self._create_user(email, name, password, **extra_fields) def create_superuser(self, email, name, password=None, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) if extra_fields.get("is_staff") is not True: raise ValueError("Superuser must have is_staff=True.") if extra_fields.get("is_superuser") is not True: raise ValueError("Superuser must have is_superuser=True.") return self._create_user(email, name, password, **extra_fields) class Country(models.Model): name = models.CharField(max_length=255) flag = models.ImageField(upload_to="flags") code = models.CharField(max_length=3) def __str__(self): return self.name class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True, verbose_name="Email Address") # name = models.CharField(max_length=255) first_name= models.CharField(max_length=255) last_name= models.CharField(max_length=255) show = models.BooleanField(default=True) brithday = models.DateField(null=True, blank=True) gender = models.CharField( max_length=10, choices=( ("male", "Male"), ("female", "Female"), ("unknown", "Unknown"), ), default="unknown", ) country = models.ForeignKey(Country, on_delete=models.PROTECT) picture = … -
Django ORM: filtering on concatinated fields
In my app, I have a document number which consists of several fields of Document model like: {{doc_code}}{{doc_num}}-{{doc_year}} doc_num is an integer in the model, but for the user, it is a five digits string, where empty spaces are filled by zero, like 00024, or 00573. doc_year is a date field in the model, but in full document number, it is the two last digits of the year. So for users, the document number is for example - TR123.00043-22. I want to implement searching on the documents list page. One approach is to autogenerate the full_number field from doc_code, doc_num and doc_year fields in the save method of Document model and filter on this full_number. Anothe is to use Concat function before using of filter on query. First by concatinate full_code field docs = Document.annotate(full_code=Concat('doc_code', 'doc_num', Value('-'), 'doc_year', output_field=CharField())) and than filter by full_code field docs = docs.filter(full_code__icontain=keyword) But how to pass doc_num as five digits string and doc_year as two last digits of year to Concat function? Or what could be a better solution for this task? -
Possible reason for django template not loading upadted static file
<section> website content here </section> {% load static %} <script src="{% static 'notifications.js' %}" type="text/javascript"></script> <script src="{% static 'presentation.js' %}" type="text/javascript"></script> That code worked as it should ie. loading current versions of .js files. After some time I noticed a typo in notifications.js file. After fixing the typo and saving the file local development server is still loading version without fix. I tried clearing browser cache and history as well as rebooting device and problem still occurs. Any possible fix? -
What is the right way to set up Gunicorn on my Django app?
everyone! Could you please help me with setting up Gunicorn for Django application. I'm going through clear and great digital ocean tutorial and don't know how to access my wsgi.py file for Gunicorn. In example it is shown like this: cd ~/myprojectdir gunicorn --bind 0.0.0.0:8000 myproject.wsgi But my wsgi.py file has another address: ~/myprojectdir/LibrarySite/locallibrary/wsgi.py. So, I did this way: cd ~/myprojectdir/LibrarySite/locallibrary gunicorn --bind 0.0.0.0:8000 locallibrary.wsgi And I get an error: No module named 'locallibrary' I'm sorry for such a dummy question, but what is the correct way to set file address right?Server error -
Django image saving
I wonder what is the best practices in saving images into ImageField in Django? class Image(models.Model): image = ... def save(self, *args, **kwargs): ... # resizing and saving the image super().save(*args, **kwargs) I want to save images but not in original size. I want to save only the resized image. As far as I know the super save method here additionally saves the original image to database. But I want it to save only resized to prevent data overflow. How to do that? -
trying to get wrong parameter on purpose in django unit testing
as part of project management course me and my partners creating a website to simulate buying and selling stock, and we're using yahoo finance API to get the Stocks and their details, and we're developing it in Django In the unit testing I'm sending on purpose a wrong stock name in the search system so I could check if its really showing a message 'Wrong Stock name', I'm doing it with sending a POST request with wrong stock name and the result is that the the specific unit test fails how could I check it? the unit test code: def test_Customer_wrong_stock(self): response = self.client.post(reverse('AgentSignUp:Search_Stock_cust'), data={ 'searchStock':'badStock'}) self.assertEqual(response.status_code,200) and the view function for the search: def SearchStock(response): if response.method == "POST": try: stockTicker = response.POST.get('searchStock') stock = yf.Ticker(stockTicker) stockData = stock.history(period="4y") stockData['Close'].plot(title=f"{stockTicker} stock price (in USD)") graph = plt.gcf() buf = io.BytesIO() graph.savefig(buf,format='png') buf.seek(0) string = base64.b64encode(buf.read()) uri = urllib.parse.quote(string) graph = stockData['Close'] price = stock.info['regularMarketPrice'] symbol = stock.info['symbol'] recom = stock.info['recommendationKey'] website = stock.info['website'] return render(response, "stock_view.html", {"price": price, "ticker": symbol, "recom": recom, "website": website, "graph": uri}) except: messages.error(response, f"Stock named {stockTicker} doesn't found or not exists") if response.user.is_Customer: return redirect('/customer_homepage') elif response.user.is_Agent: return redirect('/agent_homepage.html') elif response.user.is_Admin: return redirect('/admin_homepage.html') else: … -
How to copy data from fixtures to tenant schema table in Django-tenants?
Info: I am using django-tenants. I want to copy data from fixtures file to tenant schema table while creating new tenant. django-celery is handling the task. I want to run fixtures_data_load function after new tenant has been created I don't understand how can i do that! app.task() def fixtures_data_load(self): with open('fixtures/groups.json', encoding='utf-8') as data_file: # Convert json string to python object data = json.loads(data_file.read()) # Create model instances for each item for item in data: # create model instances... item = YourModel(*item) YourModel.objects.bulk_create(items) fixtures.json [ { "model": "auth.group", "pk": 1, "fields": { "name": "admin", "permissions": [] } }, { "model": "auth.group", "pk": 2, "fields": { "name": "producer", "permissions": [] } }, { "model": "auth.group", "pk": 3, "fields": { "name": "copy editor", "permissions": [] } }, { "model": "auth.group", "pk": 4, "fields": { "name": "reporter", "permissions": [] } }, { "model": "auth.group", "pk": 5, "fields": { "name": "anchor", "permissions": [] } }, { "model": "auth.group", "pk": 6, "fields": { "name": "nle", "permissions": [] } }, { "model": "auth.group", "pk": 7, "fields": { "name": "ticker oprator", "permissions": [] } }, { "model": "auth.group", "pk": 8, "fields": { "name": "assignment editor", "permissions": [] } } ] -
Sync on-premises folder with website's static folder in AWS
I have a Django web app deployed with AWS elastic beanstalk. It’s basically a website. The site reads data from a postgres db, combines it with some images located inside a static folder, and gives an outcome according to my needs. It works fine manually but my intention from the beginning was to make it renew its content automatically. Thus, I need to do two things: To upload the data from a csv file periodically (I’m doing it currently through an input form). And more importantly, to sync my on-premises windows server folder where the images are stored, with the above-mentioned static folder. I’m new to Django and web development in general, and my knowledge over cloud services is still limited, so I would appreciate a small guidance. My primary question is if such a thing exists and if it’s something common or at least possible, and secondly how to approach this and where to focus, in order not to waste time. Thanks in advance! -
Server side Processing Django datatables rest framework Query set filtering
I have a website which firstly designed to show dynamically added or removed models in datatables. Now the data increases and i added serverside processing. The issue is I have a custom page for each foreign key to show data that belongs to itself now i am stuck with how to filter queryset for the foreign key id and set an api url for server side processing. I hope i was clear. Thanks for your attention -
Django objects in array shows as its id's
I have an UserProfile, which have OneToOneField User. In UserProfile I have ManyToManyField Orders. When I get the orders from user.profile, it returns the array of it ID's, not the entire objects. UserProfile: class UserProfile(models.Model): user = models.OneToOneField(User, related_name='userprofile', on_delete=models.CASCADE, unique=False) orders = models.ManyToManyField(Order, blank=True) def __str__(self): return self.user.username Order: class Order(models.Model): car_brand = models.CharField(max_length=30) car_model = models.CharField(max_length=30) repair_type = models.CharField(max_length=30) user = models.ForeignKey(User, on_delete=models.CASCADE) Serializers: class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = ['car_brand', 'car_model', 'repair_type', 'user'] class UserProfileSerializer(WritableNestedModelSerializer, serializers.ModelSerializer): orders = OrderSerializer(many=True) class Meta: model = UserProfile fields = ['user', 'orders'] And, the main part, if I making a GET request with Postman, I get this: { "user": 5, "orders": [ { "car_brand": "Ford", "car_model": "Galaxy", "repair_type": "Gearbox", "user": 5 } ] } And yeah, that's exactly what I want. But React GET returns another: 11 in this case, it is a ID of order, which described above. So, the main question: How to save this order not as ID, or read it not as ID. -
Get Queryset with more than one parameters
I have a models below, and in my ListView I want to get a queryset that returns according to the tatuador, total (lista_servico) and total (valor_servico). class servico(models.Model): choices_services = [('1', 'Tatuagem'), ('2', 'Corte de Cabelo')] tatuador = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Funcionário') cliente = models.ForeignKey(Clientes, on_delete=models.CASCADE) lista_servico = models.CharField(max_length=1, choices=choices_services, blank=False, null=False, verbose_name='Lista de serviços') valor_servico = models.DecimalField(default='', max_digits=7, decimal_places=2, verbose_name='Valor do serviço') data_servico = models.DateTimeField(null=False, verbose_name='Data do serviço') marcar_servico = models.BooleanField(default=True) modo_pagamento = models.BooleanField(default=False, verbose_name='Cartão de crédito') -
Django Rest Framework Serializer to filter specific child to be nested under parent
There is a 4 levels nested relation. Country->State->District->road (that has all states in a country , all districts in a state and so on) A user sends data in separated arrays like country:["A","B"] state:["C","F","D"] and same for district and road. I want to have a json structure where only the user sent states are there and same for the other two levels also. Ex - [ { "country":[{ "name":"A", "states":[{ "name":"C", "district":[{ "name":"D"//only the user sent districts "road":[{"name":"saf"}] }] }] },{ "name":"B", .... }] }] How can i achieve this using serializers because serializers are giving me all the states irrespective of what user selected -
Locate the location of bus and student to their parent
I am working on a project in which location of bus and student will be shown to the parent. how can I render location of 2 different users to another user ( all are of different model class). Model classes are: class driver_detail(models.Model): d_user = models.OneToOneField(User, on_delete=models.CASCADE) driver_name = models.CharField(max_length=50) root_no = models.IntegerField() d_location = models.CharField(max_length=50,null=True) def __str__(self): return self.d_user.username class students(models.Model): suser = models.OneToOneField(User, on_delete=models.CASCADE,null=True) roll_no = models.CharField(max_length=10,primary_key=True,default=1) name = models.CharField(max_length=50) root_no = models.ForeignKey(driver_detail, on_delete=models.CASCADE,null=True) created = models.DateTimeField(auto_now_add=True) locations = models.CharField(max_length=200,null=True) def __str__(self): return self.suser.username class parent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) roll_no = models.ForeignKey(students, on_delete=models.CASCADE,null=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username -
Access many to many field from queryset Django
I have two models: class Vineyard(models.Model): name = models.CharField(max_length=255, blank=True) def __str__(self): return self.name class WineRegion(models.Model): name = models.CharField(max_length=255) vineyards = models.ManyToManyField(Vineyard, blank=True) def __str__(self): return self.name And I want to access all vineyards from the wine region. Here is what I've tried: if len(id_list) > 0: wr = WineRegion.objects.filter(id__in=id_list) vineyardList = wr.vineyards.all() But it gives me an error ---> AttributeError: 'QuerySet' object has no attribute 'vineyards' How can I solve this? -
Getting ['WSGIRequest' object has no attribute 'data'] error in DRF login api
Hi I am creating a login api in django restframework, but i got error wile test api in postman getting error WSGIRequest' object has no attribute 'data, i have trying mutiple way can't solve this error models.py class GmsUser(GmsBaseModel): first_name=models.CharField(max_length=255,null=True, blank=True) middle_name=models.CharField(max_length=255,null=True, blank=True) last_name=models.CharField(max_length=255,null=True, blank=True) user_name=models.CharField(max_length=255,null=True, blank=True, unique=True) password=models.CharField(max_length=255,null=True, blank=True) views.py @csrf_exempt @permission_classes((AllowAny,)) def gms_user_login(request): if request.method == 'POST': user=authenticate( request, user_name=request.data['user_name'], password=request.data['password'] ) users=GmsUser.objects.filter(id=request.data['user_name']).values_list('id',flat=True) query=GmsUserRole.objects.filter(user=users[0]).exists() if user is None: return JsonResponse({'error':'unable to login'}, status=400) else: try: if query: token = Token.objects.get(user=user) return JsonResponse({'token': token.key}, status=201) else: return JsonResponse({'error':'User does not have role'}, status=400) except Token.DoesNotExist: token = Token.objects.create(user=user) return JsonResponse({'token': str(token)}, status=200)