Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django establish correct relationships between models
I'm new to Django, trying to figure out how to set up my models so that I can accomplish my idea. On my web app, many passengers can book many flights via a form. I want to display all passengers that are associated with a particular flight. Example: London => Paris | [ "Bob", "Alice", "Bill" ] and I will then iterate though that list in my template. Sorry if this is too easy for you. I tried to get the individual flight by id in views.py and then displaying the data in the template: {{ london.passenger.name }} but it returns None views.py def flights(request): london = Flight.objects.get(id=1) context = {'london': london} return render(request, 'flights.html', context) models.py # Passenger model. class Passenger(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name # Flight model. class Flight(models.Model): origin = models.CharField(max_length=50) destination = models.CharField(max_length=50) duration = models.IntegerField(null=True, blank=True) passengers = models.ManyToManyField(Passenger) def __str__(self): return self.origin + " => " + self.destination -
usage of standard backward relation manager in serilizers
Question is about using standard Django backward related manager name in DRF. I have following serializer class ExtraUserSerializer(serializers.ModelSerializer): boatmodel_set = serializers.PrimaryKeyRelatedField(many=True, queryset=BoatModel.objects.all()) class Meta: model = get_user_model() fields = ("id", "username", 'boatmodel_set', ) This serializer represents primary model ExtraUser and boat_model set represents backward relationship to secondary model BoatModel. Related name “boatmodel_set” chosen simply because main core Django site uses this standard “secondarymodel_set” conventional backward related manager name so that in DRF part I had to use related_name = “ boatmodel_set” as well in order to not change code in the main part. Question is - is it possible to keep related_name = “ boatmodel_set” but represent it in rendered json as , for example “boats”?? Thank you -
Django ckeditor can not add youtube plugin
I have seen this tutorial https://samulinatri.com/blog/django-ckeditor-codesnippet-hightlightjs-youtube/ and I have downloaded the youtube plugin here https://ckeditor.com/cke4/addon/youtube Then I created the youtube folder and pushed it into it. Specifically my_project / static / ckeditor / ckeditor / plugins / youtube / After I python manage.py runserver, field ['content'] show normal, field ['content1'] it doesn't work (does not display frames textarea). Someone helped me check, I did something wrong. Thanks !!! File model.py class Posts(models.Model): title = models.CharField(max_length=50) content = RichTextUploadingField() content1 = RichTextUploadingField( config_name='special', extra_plugins=['youtube'], external_plugin_resources=[( 'youtube', '/static/ckeditor/ckeditor/plugins/youtube/youtube/', 'plugin.js', )], ) File setting.py CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', }, 'special': { 'toolbar': 'Special', 'toolbar_Special': [ ['Bold'], ['CodeSnippet', 'Youtube'], ], 'extraPlugins': ','.join(['codesnippet', 'youtube']), } } My_project ├── blog <= This my_app │ ├── view.py │ ├── form.py │ ├── model.py ├── project <= Project settings directory │ ├── __init__.py │ ├── settings.py <= settings │ ├── urls.py │ └── wsgi.py ├── static │ ├── ckeditor │ ├── ckeditor_uploader │ ├── ckeditor │ ├── plugins │ └── youtube │ └── youtube │ └── images │ └── lang │ └── plugin.js │ └── .... │ └── ... │ └── ... -
Post Request to Django Rest Api that has a filter. So messages/?room=4
My Backend is built like this. Every 'Room' has 'Messages' And Every Message has a Sender (person who sends it). I want to make a post request to messages/?room=4. So I want to basically add a message directly to the room with id=4. //models class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'All Users' def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_data(sender, update_fields, created, instance, **kwargs): if created: user = instance profile = UserProfile.objects.create(user=user) class Message(models.Model): sender = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="sendermessage") content = models.CharField(max_length=500) date = models.DateField(default=date.today) canview = models.ManyToManyField(UserProfile, blank=True, related_name="messagecanview") class Meta: verbose_name_plural = 'Messages' def __str__(self): return "{sender}".format(sender=self.sender) class Room(models.Model): name = models.CharField(max_length=50) members = models.ManyToManyField(UserProfile, blank=True, related_name='room') messages = models.ManyToManyField(Message, blank=True, related_name='room') class Meta: verbose_name_plural = 'Rooms' def __str__(self): return "{name}".format(name=self.name) //serializers, views class UserProfileSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username') class Meta: model = UserProfile fields = ('id', 'username') class MessageSerializer(serializers.ModelSerializer): sender_obj = UserProfileSerializer(source='sender', read_only=True) class Meta: model = Message fields = ('id', 'content', 'date', 'sender', 'sender_obj') class RoomSerializer(serializers.ModelSerializer): messages = MessageSerializer(many=True, read_only=True) members = UserProfileSerializer(many=True, read_only=True) class Meta: model = Room fields = ('id', 'name', 'members', 'messages') class UserProfileView(viewsets.ModelViewSet): http_method_names = ['get', 'post', 'put', 'delete', 'patch'] queryset = UserProfile.objects.all() serializer_class = UserProfileSerializer filter_backends = ( … -
What is the simplest way of receiving and then processing a csv on a website?
Essentially I built an application using Python (specifically Pandas) that reads a csv then performs some actions on it then ultimately produces an output graph. I wanted to make this application into a website and I have learnt a bit of HTML, CSS and JavaScript to do this. I want the website to mainly do these 2 things Receive a file Process the file using Python then output the image back to the website What is the best course of action for this problem? Learn Flask? Learn Django? Would I need to learn anything else? -
Signing up Multiple User types in Django
I am doing a project in which I have to deal with two types of users - company , students I have made 2 apps namely company and student to handle this. Now django does not support multiple types of users so i wanted to know the easiest way of doing it. I followed this Multiple User Types In Django but could not understand properly. I found people suggesting to use OnetoOneField for User and create a profile model separately for Company and Students and an option of creating profile ... class company_profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) location = models.CharField(max_length=100) email = models.EmailField() is_company = models.BooleanField(default = True) is_student = models.BooleanField(default = False) ... I tried creating models like this for the company and similarly for the student The problem is that if i allow creation of user first and then ask them to update their profile then It might happen that a student logs in place of the company before the company has updated its profile. I want to check the is_company or is_student attribute at the time of login. To do this I have followed several blogs / tutorials but kept on getting errors Can … -
Python DETAIL: Array value must start with "{" or dimension information
im trying to add a string to an ArrayField and I'm getting DETAIL: Array value must start with "{" or dimension information. error. this is how the model looks like the method update_credential is where im trying to add the merchant_id to merchants ArrayField. class CloverCredential(models.Model): tenant = models.OneToOneField('tenant.Tenant', unique=True, on_delete=models.CASCADE) token = EncryptedCharField(max_length=255, null=True) spreedly_receiver_token = EncryptedCharField(max_length=255, null=True) merchants = ArrayField(models.CharField(max_length=200, blank=True), null=True) def update_credential(self, new_token, merchant_id): self.token = new_token self.merchants = merchant_id self.save() This is the view where im calling update_credential and passing token and merchant_id class OAuthCallback(APIView): def api_request(self, path): return requests.get(path).json() def get(self, request, *args, **kwargs): code = request.GET.get('code', '') state = unsign_state(request.GET.get('state', '')) merchant_id = request.GET.get('merchant_id', '') tenant = get_object_or_404(Tenant, pk=state['tenant_id']) clover_credential, created = CloverCredential.objects.get_or_create(tenant=tenant) url = f'{settings.CLOVER_URL_US}/oauth/token?client_id={settings.CLOVER_APP_ID}&client_secret={settings.CLOVER_APP_SECRET}&code={code}' oauth_response = self.api_request(url) clover_credential.update_credential(oauth_response['access_token'], merchant_id) return redirect(state['redirect']) i also tried to append merchant_id to merchants self.merchants.append(merchant_id) and got this error AttributeError: 'NoneType' object has no attribute 'append' -
Django Rest Framework not retrieving data from my database
I'm creating an API endpoint to retrieve data from a Mongo database, in order to use it on my frontend. On my project, i'm using two DBs: a sqlite db and the Mongo DB. In the Mongo database, there is a collection called tst with some data in it. I created the endpoint, but after opening the api on my browser, i see no json data retrieved from the collection, as if it's not looking in the right place. Can someone help me find what i'm doing wrong? Here is my model: class tst(models.Model): id = models.CharField(max_length=100) ticker = models.FloatField() def save(self, *args, using=None, **kwargs): super(tst, self).save(*args, using='dbtwo', **kwargs) Here is my view: class tstList(generics.ListCreateAPIView): queryset = tst.objects.using('dbtwo').all() serializer_class = tstSerializer Here is the serializer: class tstSerializer(serializers.ModelSerializer): class Meta: model = tst fields = ('id', 'ticker', ) And the url: path('tst/', views.tstList.as_view()), -
Django - RawPostDataException: You cannot access body after reading from request's data stream
I'm really stuck at this problem for a couple of days now. While I understand, what's happening here, I don't really know the best workaround/solution for this. Problem: I'm trying to create a user login endpoint using Django and DRF in general. My login API needs to support a login via password as well as login via OTP. My LoginView looks like: def post(self, request, **kwargs): """ post Method to handle user login :param request: :param args: :param kwargs: :return: """ request_data = request.data login_using_password = request_data.get('login-with-password') is True login_using_otp = request_data.get('login-with-otp') is True if request_data is not None: if all((login_using_password, login_using_otp)): raise accounts_exceptions.InvalidLoginRequestError() if login_using_password: return Response(self._login_with_password(request)) elif login_using_otp: return Response(self._login_with_otp(request)) raise accounts_exceptions.InvalidLoginRequestError() return Response(self._login_with_password(request)) Also my _login_with_password looks like: def _login_with_password(self, request, **kwargs): """ _login_with_password A utility method to handle login with password :param request: :return: """ return getattr(ObtainJSONWebToken.as_view()(request=request._request, ), 'data') When I try to login, Django complains saying RawPostDataException You cannot access body after reading from request's data stream I'm using JWT to authenticate requests. ObtainJSONWebToken is a view provided by DRF-JWT to obtain access tokens to authenticate requests. What is the workaround/solution for this? Is there a better way to support such a login requirement? Thanks … -
How to merge existing Django project into a new one with custom user model?
I've researched this some but haven't yet found an easy way to do this. My current project uses the default User model, but I've realized I need to use a custom user model. Is there an easy way to build a new Django project with custom user model and then copy my existing project into it? I do not have a user base so I don't mind losing it. -
how to compress the size of the picture in django-summernote
The task of tako with how can you compress the image uploaded through django-summernote For example, I have a picture with a size of 5mb after downloading it should have a size somewhere 500kb -
How to filter with date range
Here how can i filter all products which are added from within the past one month to this date. models.py class Product(models.Model): name = models.CharField(max_length=250) description = models.TextField(blank=True) featured = models.BooleanField(default=False) added = model.DateTimeField(auto_now_add=True) def __str__(self): return self.name views.py def all_products(request): all_products = Product.objects.all() recently_added_products = Product.objects.filter(...) context = {'all_products':all_products,'recent_products':recent_products} return render(request,'products_list.html',context) -
DoesNotExist at /admin Category matching query does not exist
I get errors when going to admin panel. Django shows me the error associated with the categories in the product list. I do not understand why the admin panel is waiting for the category? How is this interrelated? Help me please The error looks like this Category matching query does not exist. DoesNotExist at /admin ./shop/views.py in product_list category = Category.objects.get(slug=category) urls.py from django.conf.urls import url, include from django.conf import settings from django.contrib import admin urlpatterns = [ url(r'', include('orders.urls')), url(r'', include('cart.urls')), url(r'', include('shop.urls')), url(r'^admin/&', admin.site.urls), ] shop urls.py app_name = 'shop' urlpatterns = [ url(r'^$', views.product_list, name='product_list'), url(r'^show/(?P<slug>[-\w]+)$', views.product_show, name='product_show'), url(r'^(?P<category>[-\w]+)$', views.product_list, name='lst_by_ctgry'), url(r'^(?P<category>[-\w]+)/(?P<subcategory>[-\w]+)$', views.product_list, name='lst_by_subctgry'), url(r'^(?P<category>[-\w]+)/(?P<subcategory>[-\w]+)/(?P<kind>[-\w]+)$', views.product_list, name='lst_by_knds'), ] settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'shop', 'cart', 'orders', ] product_list - views def product_list(request, category=None, subcategory=None, kind=None): if category: categories = Category.objects.all() category = Category.objects.get(slug=category) subcategories = Subcategory.objects.filter(category=category) products = Product.objects.filter(category=category, available=True) products_quantity = len(Product.objects.filter(category=category, available=True)) kinds = None; kind_last = None if subcategory: subcategory = Subcategory.objects.get(slug=subcategory) kinds = Kind.objects.filter(kind=subcategory) products = Product.objects.filter(category=category, subcategory=subcategory, available=True) if kind: kind = Kind.objects.filter(slug=kind) products = Product.objects.filter(category=category, subcategory=subcategory, kind__in=kind, available=True) kind_last = kind.last() if products: paginator = Paginator(products, 8) page = request.GET.get('page') products = … -
In Django, how to find out what URL pattern matched for a request?
I'm working on an old Django project with a lot of URL patterns. Sometimes, it's not clear for me which view was run by the dispatcher. Is there any way to see what URL pattern matched for a particular request in Django? -
How filter manytoManyfield before pre choice
I have 2 fields team=models.ForeignKey(Team) players=models.ManytoManyField(Player) when creating a match, when I select a team I want to list the players of that team so that I can choose which players will play in the match. (I want to filter because there are hundreds of maybe thousands of players. I don't want to see the players of other teams.) like this; players=models.ManytoManyfield(players,filter=xxx.team.players) -
How I can add a button to django-tables2 to trigger a modal for deleting entries?
So I made a view with django-tables2 to view user entries and I wanted to show a columns of actions So I thought i could use TemplateColumn to add the buton for triggering the modal however it doesn't trigger when i click the button. Tables.py import django_tables2 as tables from django_tables2.columns import TemplateColumn from .models import Patient,UploadedImages from django_tables2.utils import A # alias for Accessor class PatientTable(tables.Table): FirstName = tables.Column(linkify=("patients:patient_detail", {"pk": tables.A("pk")})) LastName = tables.Column(linkify=("patients:patient_detail", {"pk": tables.A("pk")})) Telephone_no = tables.Column(linkify=("patients:patient_detail", {"pk": tables.A("pk")})) edit = tables.LinkColumn('patients:patient_update',text='Edit', args=[A('pk')], attrs={ 'a': {'class': 'btn btn-primary'} }) # delete = tables.LinkColumn('patients:patient_delete', text='Delete', args=[A('pk')], attrs={ # 'a': {'class': 'btn btn-danger'} # }) delete = TemplateColumn('<a class="btn btn-danger" data-toggle="modal" data-target="#modalDelete" >Edit</a>') class Meta: model = Patient attrs = {'class': 'table table-striped table-hover'} exclude = ("user", "Notes", "Adress") template_name = 'django_tables2/bootstrap4.html' views.py @login_required def Patients_list(request): patients = Patient.objects.all() table = PatientTable(patients.filter(user=request.user)) RequestConfig(request).configure(table) return render(request, 'patients/patients_list.html',{ 'table' : table, 'patients':patients, }) and here's the template {% extends 'base.html' %} {% load render_table from django_tables2 %} {% block content %} <div id="content"> {% if user.is_authenticated %} <h1> Patients list: </h1> <br> <a href="{%url 'patients:patient_create'%}" class="btn btn-info" role="button">Add Patient</a> <br> <br> {% render_table table %} {% else %} <h2>please login</h2> {% … -
how to tell which ini file the current uwsgi process is using?
In an operating website with Nginx, Uwsgi and Django. and it has tons of venv and django projects. Is it any way I can tell with .ini file the uwsgi loaded? -
How to let existing entries empty when using auto_now_add?
I added a field to my existing model : creation_date = models.DateTimeField( auto_now_add=True, blank=True, null=True) When applying the migration, auto_now_add is applied to all existing entries. How to avoid that ? creation_date must remain null for all data recorded before the migration is applied. -
How i can calculate sum of n based on id?
I have a QuerySet like this. I want sum of "n" based on "id". this is my queryset: <QuerySet [{'id': 1, 'n': 0}, {'id': 2, 'n': 0}, {'id': 2, 'n': 1}, {'id': 3, 'n': 2}, {'id': 4, 'n': 0}, {'id': 5, 'n': 1}, {'id': 5, 'n': 0}]> and this is my code: drivers = Driver.objects.values('id').annotate( travel_time=Sum(Case( When(car__ride__pickup_time__isnull=False, then=(F('car__ride__dropoff_time') - F('car__ride__pickup_time'))), default=0 )), ).annotate( n=Case( When(Q(travel_time__gt=t) & Q(car__model__gte=n), then=Count('car__ride')), output_field=IntegerField(), default=0 ) ).values('id', 'n') i dont know how to make a group by based on id :( -
Bookmarklets and Django authentication
I have developed 2 bookmarklets for accessing 2 different web services through a sort of "gateway" or "proxy". Since they are addressed to registered users of a learning platform based on Django, I try to limit the access to users that authenticated to said platform and click on the bookmarklets from a tab of the same browser window. In the first of the 2 bookmarklets, which sends a GET request, this trick works, while in the other one, which sends a POST request, it fails. Bookmarklet 1. (inspired from the xAPI Bookmarklet) In the simplest case the user, while navigating the web, wants to declare that it has seen (and found interesting) a web page. When s/he clicks on the bookmarklet button, the javascript code collects some info and sends it to a "view" of the Django platform as URL-encoded data inside the querystring of a GET HTTP request. Django verifies that the user is authenticated and sends an xAPI statement to an xAPI LRS (learning record store) of which it owns the credentials. Bookmarklet 2. The user, while navigating the web, wants to ask a specialized web application to perform some text analysis of the content of a web … -
New field in annotation destroys all field types django
I need to load all stats one by one for each user's account. I used annotate() to connect and calculate other related models fields, but one of the field, while added - destroys all types and multiplies integer by 10 somehow in previous fields in queryset. I have 3 models: AdvertisingAccount, Campaign, UserProfile. I've tried casting for all the fields, but it didn't changed the picture: I need integers to be integers, and decimals to be decimals with 2 decimal places (as set in models). expected: ads_direct 313 303 31.12 2165.18 but recieved: ads_direct 3443 3333 342.320000000000 8441.80000000000 code in views: (I need these fields be calculated) accounts = user.userprofile.advertising_accounts.annotate( clicks=Cast(Sum('campaigns__clicks', filter = Q(campaigns__userprofile = userprofile)), IntegerField()), views=Cast(Sum('campaigns__views', filter = Q(campaigns__userprofile = userprofile)),IntegerField()), ad_spent=Cast(Sum('campaigns__ad_spent', filter = Q(campaigns__userprofile = userprofile)),DecimalField(decimal_places=2)), money_left = Sum('budgetings__deposited', filter = Q(budgetings__userprofile = userprofile)) - (Sum('campaigns__ad_spent', filter = Q(campaigns__userprofile = userprofile))), ) Note If I comment out money_left, all annotations calculates and presents OK (except decimal place: it takes 12 places, instead of 2). I've tried this, but it didnt change situation: accounts = user.userprofile.advertising_accounts.annotate( clicks=Cast(Sum('campaigns__clicks', filter = Q(campaigns__userprofile = userprofile)), IntegerField()), views=Cast(Sum('campaigns__views', filter = Q(campaigns__userprofile = userprofile)),IntegerField()), ad_spent=Cast(Sum('campaigns__ad_spent', filter = Q(campaigns__userprofile = userprofile)),DecimalField(decimal_places=2)), money_left = Cast((Sum('budgetings__deposited', … -
how to send data from the view to the header or the navigationBar
i have django website that have a navigation bar where i need to display the user and the group that belong to it in the navigation bar in order to make it visible on all pages. until now i am bale to send these data to a specific page and not to the header. views.py def home(request): #print(User.groups.get()) print(request.session.keys()) if request.session.has_key('theUser'): authed=request.session['theUser'] if request.session.has_key('group'): sections=request.session['group'] return render(request,'./mainpage.html',{'sections':sections,'authed':authed}) else: authed=None else: authed=None return render(request,'./Login.html',{'authed':authed}) where i am sending {'sections':sections,'authed':authed} to mainpage.html mainpage.html <div id='left-column-Input' class="formInput" include="select()"> {{user.get_username}}|{{sections}} what i need is to send the data to the header or the base file. base.html <!DOCTYPE html> {% load static %} <html> <head> <script type="text/javascript" src="{% static '/js/jquery-3.1.1.min.js' %}"></script> <link rel= "icon" type= "image/png" href="{% static 'img/logo_title/icon-AddressBar.png'%}"> <link rel="stylesheet" type="text/css" href="{% static '/css/search.css'%}"> <link rel="stylesheet" type="text/css" href="{% static '/css/style.css'%}"> </head> <body> <img class="logoMM" src="{% static 'img/logoMM.png' %}" alt="Smiley face" /> <!-- <div class="wrap"> --> <div class="wrap search Horizontal-scale"> <!-- <div class="Horizontal-scale"> --> <button type="submit" class="searchButton"> <svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="search" role="img" viewBox="0 -20 530 530"><path fill="currentColor" d="M505 442.7L405.3 343c-4.5-4.5-10.6-7-17-7H372c27.6-35.3 44-79.7 44-128C416 93.1 322.9 0 208 0S0 93.1 0 208s93.1 208 208 208c48.3 0 92.7-16.4 128-44v16.3c0 6.4 2.5 12.5 7 17l99.7 99.7c9.4 9.4 24.6 … -
Updating model on save vs count objects in the ListView - what's better performance-wise?
I'm creating a forum script. Currently I'm trying to optimize things and looking for answer from more experienced developers. For example - let's assume we are working on ListView of Category, which should list all threads within the same forum category. For every thread in category we are listing fields such as: Thread name Thread author Number of posts Number of views Last post details (a uthor, date) What is the best performance approach to calculate number of posts? Currently I'm thinking about 3 of them. Use annotate() on queryset add IntegerField posts_number to Thread model. Increment the value on save() in Post model and decrement on delete() Use memcache to cache read-only SQL queries and force cache refresh on every save() in Post model. I'm aware this is not an issue with low traffic forums, but I would love to know what's the best approach -
How to change file system encoding in django on centOS
Filesystem encoding (sys.getfilesystemencoding()) in Django returns "ascii", although in centOS system the returning value is "utf-8" As a result of the invalid encoding I get the UnicodeError during the uploading files with Cyrillic name. I've tried: sys.getfilesystemencoding = lambda: 'UTF8' set Django DEFAULT_ENCODING as 'UTF8' In interpreter on CentOS: >>> sys.getfilesystemencoding() 'utf-8' Then I added this code in views.py: loc_info = "fs_encoding: " + str(sys.getfilesystemencoding()) return django.http.HttpResponse(loc_info) And I got: fs_encoding: ascii I want to get the value "UTF8" as the result of the function sys.getfilesystemencoding() in Django -
router.register(), AttributeError: module 'rest_framework.views' has no attribute
I don't know what I am doing wrong. I have been battling with this error for hours. I have opened all the suggestions I saw and implemented what they suggested but still, the error is pending router.register(r'^hmos/$', views.HMOList), AttributeError: module 'rest_framework.views' has no attribute 'HMOList' This is "core/urls.py" from django.conf.urls import url from .views import * from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from rest_framework_jwt.views import obtain_jwt_token,refresh_jwt_token from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('hmos', views.HMOList) urlpatterns = format_suffix_patterns(urlpatterns) This is "core/views.py" from django.shortcuts import render_to_response import json from rest_framework.parsers import MultiPartParser, FileUploadParser, FormParser from django.db.models import Q from rest_framework import permissions from django.contrib.auth import authenticate, login,logout from rest_framework import generics, status, views from rest_framework.permissions import IsAuthenticated from .models import * from .serializers import * from rest_framework.response import Response from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework.permissions import IsAuthenticated from .utils import generate_responder_serial from rest_framework.parsers import MultiPartParser, FileUploadParser, FormParser from django.conf import settings import os from django.db.models import Q #from rest_framework.authentication import (BaseJSONWebTokenAuthentication) from rest_framework import viewsets def jwt_response_payload_handler(token, user=None, request=None): return { 'token': token, 'user': SystemUserSerializer(user).data } def create(self, request, *args, **kwargs): new_data = {'name': request.data['name'].strip(), 'address': request.data['address'], 'state': request.data['state'], 'mobile1': request.data['mobile1'], 'mobile2': request.data['mobile2'], } if HMO.objects.filter(name = request.data['name'].strip()): raise …