Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
multiple aspect filter in abay sdk
response = api.execute('findItemsAdvanced', {'keywords':'Macbook', }, 'aspectFilter':[{'aspectName': 'Series','aspectValueName': 'MacBook Air'}, {'aspectName': 'Processor', 'aspectValueName': 'AMD A10'}] }) Now i am working in ebaysdk . i am facing the problem with multiple aspect filter. Is there any solution for multiple aspect filter.if aspect filter is single it is working fine but multiple are not -
DRF: testing POST method using Client()
I have a class that accepts the dictionary list - data = [{}, {}] . If I send data via Postman, everything will work but the problem with testing POST class method. The error is FAIL: test_vendor_from_csv_create (vendors.tests.VendorCsvCreateTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/y700/projects/solution/apps/vendors/tests.py", line 128, in test_vendor_from_csv_create self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 404 != 200 views.py class CsvToDatabase(APIView): def post(self, request, format=None): r_data = request.data for data in r_data: if data['nda'] == '': data['nda'] = None ... #some logic serializer = VendorsCsvSerializer(data=data) try: serializer.is_valid(raise_exception=True) serializer.save() except ValidationError: return Response({"errors": (serializer.errors,)}, status=status.HTTP_400_BAD_REQUEST) else: return Response(request.data, status=status.HTTP_200_OK) test.py class VendorCsvCreateTest(APITestCase): #API def test_vendor_from_csv_create(self): url = reverse('csv_vendor_create') response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) I assume the problem is format='json'. If this is the case, how do I transfer the data in the right format? If the reason is different, can you give me a solution, please! -
Redirect to item page after deleteView in class based views
I have an invoice page with each invoice (factuur) has items in it (relation invoice-items with ForeignKey). When I delete one of the items with the class based deleteView I want to redirect back to the specific invoice id with the remaining items in it. urls.py: path('factuur/<factuur_id>', views.facturen_detail_view, name='facturen_detail_view'), path('delete/<int:pk>', views.FactuurItemDeleteView.as_view(), name='delete_factuurItem'), views.py: class FactuurItemDeleteView(BSModalDeleteView): model = FactuurItems template_name = 'delete_fitem.html' success_message = 'Succes: factuur item is verwijderd.' success_url = reverse_lazy('facturen_detail_view') So what I want is redirect it to /factuur/factuur_id after deletion (where I was at the moment of clicking the delete button). But how do I redirect as I need to know invoice id (factuur_id) in the first place. I don't know how to do this with the class based views method. When success_url is as above then it tries to redirect to the factuur_id with the deleted item_id what is not the wanted situation. -
page not found error while passing paarmeter through url in view django
I am new to python django. I am facing an issue while passing parameter to view through URL in django. code: views.py from django.shortcuts import render from django.http import HttpResponse def hello(request): text = "HEllo" return HttpResponse(text) def viewArticle(request, articleId): text = "HEllo : %d"%articleId return HttpResponse(text) urls.py from django.conf.urls import url from django.urls import path,include from myapp import views urlpatterns = [ path('hello/',views.hello,name='hello'), path('article/(\d +)/',views.viewArticle,name='article'), ] image: -
Django Base Validator
i need to make a regex for my django project. I've made a Custom Validator that must implement a regex. I need to implement a regex that check the format of this different input: nnnn-nn/yyyy or nnnn/yyyy in the first input the number after - must 1 or 2 long -
Django Error during template rendering: maximum recursion depth exceeded while calling a Python object
I don't understand where I stucked -
How to make stripe Charge amount dynamic in Django
I am new to Django, I am trying to build a hostel reservation with stripe payments.I have a room model and Reservation as follows. class Reservation(models.Model): student = models.OneToOneField(User,on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete = models.CASCADE) start_date = models.DateTimeField(auto_now_add=True) class Room(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=200,null=True,blank=True,unique=True) price = models.IntegerField() hostel = models.ForeignKey(Hostel,on_delete=models.CASCADE,null=True) number_of_beds = models.IntegerField() room_thumbnail = models.ImageField(null=True) resized_thumbnail = ImageSpecField( processors=[ResizeToFill(620, 430)], format='JPEG', options={'quality': 60}) room_type = models.ForeignKey(Category,on_delete=models.CASCADE) room_number = models.IntegerField() is_reserved = models.BooleanField(default=False) description = models.TextField() def get_absolute_url(self): return reverse('room_detail', args =[ str( self. id)]) I also have a room detail view for the rooms and charge view where ai want the charge amount on stripe to be dynamic based on the price of the rooms. Can some help me on how to solve this. <!-- begin snippet: js hide: false console: true babel: false --> def BookingConfirmation(request): if request.method == 'POST': rooms = Room.objects.all() amount = rooms.price charge = stripe.Charge.create( currency='usd', amount = amount, description='A Django charge', source=request.POST['stripeToken'] ) return render(request,'booking-confirm.html',{}) def RoomBookingView(request,pk): publishkey = settings.STRIPE_PUBLISHABLE_KEY if request.method == 'POST': if pk: room_id = Room.objects.get(pk = pk) student_id = request.user room_id.is_reserved = True, reservation = Reservation( room_id = room_id.id, student_id = student_id.id, ) reservation.save() try: room = … -
Using FPDF i want Inline bold text in paragraph in python
from fpdf import FPDF pdf1 = FPDF pdf1.multi_cell(0, 5, 'This is my disclaimer. THESE WORDS NEED TO BE BOLD. These words do not need to be bold.', 0, 0, 'L') pdf1.output("sample.pdf") -
how to fetch data in chunks from db in django and then delete them?
My basic problem statement is that I want to fetch every row but in chunks only 2000 rows at one time from a table having 1 million rows. And after these chunked queries are evaluated i want to delete every row. so just say i have a = Model.objects.filter(id=1<2000) b = Model.objects.filter(id=2000<4000) c = Model.objects.filter(id=4000<6000) .. .. now if i combine all these queryset into one queryset by some means say del = a + b + c +d ...... and i do del.delete() so will it delete all the rows in less time or it will re process queries again to delete them and will take time? -
Django url dispatcher calls the wrong function
the problem that I have is this one: I created a new re_path in my urls.py file, but when I make a request at that url the wrong function is called. # myapp/urls.py from django.urls import path, re_path from . import views as multiplayer_lite_views urlpatterns = [ # other paths re_path(r'vote/(?P<match_id>\w{16})', multiplayer_lite_views.vote, name='multiplayer_lite_vote'), re_path(r'nightvote/(?P<match_id>\w{16})', multiplayer_lite_views.night_vote, name='multiplayer_lite_night_vote'), path('new-match/', multiplayer_lite_views.new_match, name='multiplayer_lite_new_match'), path('', multiplayer_lite_views.home, name='multiplayer_lite_home'), ] what I did was simply duplicate the line re_path(r'vote/... and renamed it to re_path(r'nightvote/... but changing also all the other info, like multiplayer_lite_views.vote to multiplayer_lite_views.night_vote. The problem is that when I go to this url nightvote/ the function vote is called. # myapp/views.py def vote(request, match_id): print('vote function') # do other stuff return return JsonResponse(...) def night_vote(request, match_id): print('nightvote function') # do other stuff return return JsonResponse(...) In the server side what I see is that: ... vote function [18/Mar/2020 10:19:16] "POST /nightvote/gfvkpvhlwlqzosae HTTP/1.1" 200 16 ... PS I have already tried to close Django and reopen, the same with vs code. -
implementing like system in django and postgres
i want to implement a like system for our project,my question is almost about performance,i want to use django with Postgresql DB,in models.py i have a Like model: class Like(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name = "like") place = models.ForeignKey(Places,on_delete=models.CASCADE,related_name = "likedPlace") when a user want to see a post,i should show them if he/she liked the post or not,is postgresql good for this purpose?or any other relational database?if i have 50000 user and each user like 10 post,each time i should iterate 500000 row in worst case. can i use nosql database like cassendra for this purpose? -
How to add additional field in the default admin_User table in Django 3.0.3
I don't have idea to put extra field in default admin user table/ model in django 3.0.3 version . Please give some idea to make extra field like user_roll, user_id, designation etc. -
Django 502 bad gateway with Nginx and Uwsgi
I can normally open up my web in the front several hours after deployment,but later , it occurred 502 bad gateway ,it is so wired, my web uses Django and Nginx and Uwsgi, i do research a lot on google,but failed with nothing Here is my configuration: 1.Nginx configuration # mysite_nginx.conf upstream django { server 127.0.0.1:8004; # for a web port socket (we'll use this first) } server { listen 80; server_name www.example.com # substitute your machine's IP address or FQDN charset utf-8; client_max_body_size 75M; # adjust to taste location /media { alias /home/blender_font_project/django_file/Blender_website/media; } location /static { alias /home/blender_font_project/django_file/Blender_website/static; } location / { uwsgi_pass 127.0.0.1:8003; include /etc/nginx/uwsgi_params; } } 2.uwsgi configuration # mysite_uwsgi.ini file [uwsgi] chdir = /home/blender_font_project/django_file/Blender_website module = djangoTest5.wsgi master = true processes = 10 socket = :8003 vacuum = true harakiri=60 daemonize=/home/blender_font_project/uwsgi_file/real3dfont_logfile BTW , i have set Django to DEBUG Ture and i can access my resource by www.example.com/static/example.jpg,but the web page shows 502 I really dont know why , thanks if you offer any help! -
Why celery is giving Database connection error even though database server has connection pooling active
Currently I am facing some problem regarding my web app. I have a web app built with django along with celery for some background task. The workflow is - client uploads an image and then some processing is done in celery task like some api call and some db update. Then client polls for result and if the task is done the result is given as response. I am using DigitalOcean managed postgresql db and using a connection pool. For celery message queue I am using rabbitmq and redis as backend result server. As most of my task is I/O bound I am using gevent for celery so that I can receive concurrent requests without any problem. My server has 2vcpu, 4GB RAM, 25GB SSD. At first when no connection pooling was activated in DB, we stress tested with around 100 image uploaded at the same time and got "FATAL: remaining connection slots are reserved for non-replication superuser connections". After some research found that this was due to db connection limit crossing, So I used connection pooling. Then there was no problem for django. But strangely celery was giving the same error while updating database. My celery command is (from … -
My postgresql database not showing many to many field column but django admin page does. Why?
I hope you got the question from the title itself. After migrating I can select multiple fields from that many to many field in django admin page but when I click on save it saves in the admin page of django but when I check the postgresql database everything that is not many to many field saves but the table lacks many to many field column. -
How to control request object in logging handler
Hi im making a logging module in django i want to save all of the user activity in class Log model here is Log model class Log(models.Model): user = models.ForeignKey("user") ip_address = models.Charfield() visited_view = models.Charfield() for example, when user(testman) visit PostCreateView Log object will create ("testman", '[user_ip_address]', 'visited_view') here is my settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'db_logger': { 'class': 'myapp.utils.logging.LogHandler', }, }, 'loggers': { 'request': { 'handlers': ['db_logger'], 'level': 'INFO', } }, } db_logger will use My Custom LogHandler from myapp.models import Log class LogHandler(logging.Handler): def emit(self, record): if record.name.split('.')[0]=='request': user = recored.request.user ## This is what i want :) Log.objects.create() and In CreateView insert logging command my_logger = logging.getLogger('db_logger') class PostCreateView(CreateView): def get_context_data(self, request, *args, **kwargs): my_logger.warning('test') but I have big problem now because logging.Handler is python lib not django So i can't control request in LogHandler :( How can i control request object in Handler? thank you :) -
user Checkout and guest checkout: best way to use both in Django
Actually I need suggestion about best practice to handle guest checkout and customer checkout. I have a scenario that 1 order can have multipul products (which is not problem). My order table is like class Orders(models.Model): customer= models.ForeignKey(Customer, on_delete=models.CASCADE) order_number = models.AutoField(primary_key=True) total_amount = models.DecimalField(max_digits=10, decimal_places=2) ordertime = models.DateTimeField(auto_now_add=True) order_status = models.CharField(max_length=50) is_placed = models.BooleanField(default=False) and then it is linked to product table like this class OrderProduct(models.Model): order=models.ForeignKey(Orders, on_delete=models.CASCADE) activity = models.ForeignKey(ActivityOrganizer, on_delete=models.CASCADE) participants=models.IntegerField(default=0) totalPrice=models.DecimalField(max_digits=10, decimal_places=2) checkIn = models.DateField() language = models.CharField(max_length=50, null=False, blank=False) And my Customer Table is class Customer(models.Model): customerProfile = models.OneToOneField(User, on_delete=models.CASCADE) first_name=models.CharField(max_length=50, null=False, blank=False) last_name=models.CharField(max_length=50, null=False, blank=False) email=models.CharField(max_length=50, null=False, blank=False) mobile_number=models.CharField(max_length=50, null=False, blank=False) profile_image=models.ImageField(null=True, upload_to='CustomerProfile') is_customer=models.BooleanField(default=False) city=models.CharField(max_length=50, null=True, blank=True) gender=models.CharField(max_length=50, null=True, blank=True) verification_key = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return str(self.first_name) Now I want to Enable guest checkouts aswell . then Should I use existing tables of order by allowing Foregin key Null ? Or I should make seprate order tables for this ? What will be best way ? -
make a periodic task run by time user given
i have to build the appication by djano to send mail notification to user , but the user want to set a time to send thier email every at that time they want , i read that celery has periodic task to run but must set time already , so how can i make a periodic task with time given by user using celery ?? class UserMail(models.Model): user_mail = models.EmailField() auto_send_mail = models.BooleanField(default=False) time_set = models.TimeField(blank=True,null=True) time set to get a time given by user when they post in the form -
Django 2.2 - change with of related auto_complete field on admin form
I'm trying to change the field width of a related auto_complete field. So that the selected record is shown a bit wider. <span class="select2 select2-container select2-container--admin-autocomplete select2-container--focus" dir="ltr" style="width: 260px;"> // ... ></span> I created my own form and tried fiddling with widget.attrs (inside the init) but it has zero effect. Which itself is no strange, since these are all span elements rendered. class OrderLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.fields['product'].widget.attrs.update({'stytle': 'width: 400px'}) self.fields['product'].widget.attrs.update({'width': 400}) I was also looking which widget is being used, but didn't find it either. Djanog docs do explainThe form.Select is a simple dropdown list, which does not provide auto complete functionality. I also tried changing some css for .select2 class, but seems to gave no effect. -
How to add extra field to django serializer?
I am trying to add an additional field to my serializer but I am getting the following error:- "The field 'provider' was declared on serializer CreateUserSerializer, but has not been included in the 'fields' option." Here is my serializer.py:- class CreateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField() username = serializers.CharField() company = serializers.CharField() provider = serializers.CharField() password = serializers.CharField(write_only=True) company_detail = serializers.SerializerMethodField() branch_detail = serializers.SerializerMethodField() def get_company_detail(self): return {} def get_branch_detail(self): return {} def create(self, validated_data): try: with transaction.atomic(): user = User.objects.create(**validated_data) user_profile = UserProfileModel.objects.create(user=user) user_profile.__dict__.update(**validated_data) user_profile.save() identity = FederatedIdentityModel.objects.create(user=user, oauth_provider=validated_data['provider']) company = CompanyModel.objects.create(user=user, name=validated_data['company']) branch = BranchModel.objects.create(user=user, name=validated_data['company'], company=company) return user except APIException: raise APIException( detail="Failed to register", code=status.HTTP_500_INTERNAL_SERVER_ERROR ) class Meta: model = User fields = ['first_name', 'last_name', 'password', 'email', 'username', 'company_detail', 'branch_detail'] I don't want to add the company and provider fields in the field option as it is not a part of user model. I just want to use them as writable fields so that I can create object for the two models. How can I get rid of the following error? -
Django: ERROR: python setup.py egg_info Check the logs for full command output
I am newbie as developer and have developped a first project in Django I try to deploy my project in a test server (Ubuntu 18.04.1 LTS (GNU/Linux 4.15.0-88-generic x86_64)) prepared by a sys admin in my team Each time I try to install dependancies (pip install -r requirements.txt) it fail with the error below: ERROR: Command errored out with exit status 1: command: /home/test/envs/envTbm/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-1uqfxt7j/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-1uqfxt7j/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-1uqfxt7j/psycopg2/pip-egg-info cwd: /tmp/pip-install-1uqfxt7j/psycopg2/ Complete output (7 lines): running egg_info creating /tmp/pip-install-1uqfxt7j/psycopg2/pip-egg-info/psycopg2.egg-info writing /tmp/pip-install-1uqfxt7j/psycopg2/pip-egg-info/psycopg2.egg-info/PKG-INFO writing dependency_links to /tmp/pip-install-1uqfxt7j/psycopg2/pip-egg-info/psycopg2.egg-info/dependency_links.txt writing top-level names to /tmp/pip-install-1uqfxt7j/psycopg2/pip-egg-info/psycopg2.egg-info/top_level.txt writing manifest file '/tmp/pip-install-1uqfxt7j/psycopg2/pip-egg-info/psycopg2.egg-info/SOURCES.txt' Error: b'You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application.\n' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. I did not understand what could be the problem... -
Django Rest Api Annotate group by Filter showing Error?
This error i am getting while enter http://127.0.0.1:8000/api/student/ this url My Database : posts/models.py ''' from django.db import models class Student(models.Model): lname = models.CharField(max_length=50) fname=models.CharField(max_length=50) def __str__(self): return self.lname ''' posts/serializers.py(webapp) ''' from rest_framework import serializers from . import models class StudentSerializer(serializers.ModelSerializer): class Meta: fields = ('lname','fname',) model = models.Student ''' posts\filters.py(webapp) ''' from django_filters import rest_framework as filters from .models import Student class StudentFilter(FilterSet): total = filters.NumberFilter(name='total') class Meta: model = Student fields = ['lname','fname','total',]#other fields ''' posts\views.py(webapp) ''' from rest_framework import generics from django.db.models import Count from .models import Post,Student,Exam,Sample from .serializers import PostSerializer,StudentSerializer,ExamSerializer,SampleSerializer from django_filters.rest_framework import DjangoFilterBackend #import django_filters.rest_framework from django.db import connection class StudentList(generics.ListAPIView): serializer_class = StudentSerializer def get_queryset(self): return Student.objects.all().values('fname').annotate(total=Count('fname')).order_by('total') ''' posts\urls.py(webapp) ''' from django.urls import path from . import views urlpatterns = [ path('', views.PostList.as_view()), path('<int:pk>/', views.PostDetail.as_view()), path('student/',views.StudentList.as_view()), path('exam/',views.ExamList.as_view()), path('sam/',views.SampleList.as_view()) ] ''' SampleProject(urls.py) ''' from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('posts.urls')), ] ''' I got output in shell but i could't get the same value in browser (api) -
How to open a file in itertools.islice() function in python?
I am tried some script in that i catch pdf file and then convert that file to txt file . I got type of text file as _io.textIoWrapper . Now i call itertools.isslice() with _io.textIoWrapper object . That produce ValueError: I/O operation on closed file. If file format plain io.textIoWrapper didn't give any error. I tried to open textIoWrapper object but that gives expect only str , bytes or None not TextIoWrapper type views.py def save_file(cls, user, file, file_format, project_id,file1): project = get_object_or_404(Project, pk=project_id) parser = cls.select_parser(file_format) if file_format == 'pdf': path = default_storage.save('text_pdf_file.pdf', ContentFile(file.read())) return_file = convert_pdf_txt(path,file_format) print(type(return_file)) # _io.textIoWrapper file = return_file data = parser.parse(file,file_format) storage = project.get_storage(data) storage.save(user) utils.py class PlainTextParser(FileParser): def parse(self, file,file_format): if file_format == 'plain': file = EncodedIO(file) file = io.TextIOWrapper(file, encoding=file.encoding) while True: batch = list(itertools.islice(file, settings.IMPORT_BATCH_SIZE)) if not batch: break yield [{'text': line.strip()} for line in batch] convert.py import os from docx import Document import pdfplumber as pp import io import unidecode import re def remove_accented_chars(text): text = unidecode.unidecode(text) return text def remove_extra_spaces(line): return re.sub(' +|\t+',' ',line) def remove_special_char(line): return re.sub(r"[^a-zA-Z0-9%.@]+",' ', line) def preprocessing(lines,fileExtension): example_text_file = "ex_txt.txt" for line in lines: if fileExtension == "docx": x=str(line.text) elif fileExtension == "pdf": x … -
Django ModelForm. Select a valid choice. That choice is not one of the valid choices
I have a Model and a ModelForm. The ModelForm has a dependent dropdown list implemented with JQuery. Whenever I try to save the ModelForm in my views, I get an error saying that the choice that I have selected is not valid. Does it have to do with the choices/options to the individual_kata_event, individual_kumite_event, team_kata_event & team_kumite_event dropdowns being added after a choice from the gender dropdown has been selected? In models.py, class Athlete(models.Model): name = models.CharField(max_length=100) gender = models.CharField(max_length=100, choices=GENDER_CHOICES) date_of_birth = models.DateField() feet_height = models.PositiveIntegerField(default=0) inch_height = models.PositiveIntegerField(default=0) weight = models.FloatField(default=0.0, help_text='Weight in kg') club = models.CharField(max_length=100, choices={ ('Arrianna Academy' , 'Arrianna Academy'), ('Bangladesh Shitoryu Karate-do Union' , 'Bangladesh Shitoryu Karate-do Union') }) team = models.CharField(max_length=100, choices={ ('Bangladesh Ansar & VDP' , 'Bangladesh Ansar & VDP'), ('Bangladesh Army' , 'Bangladesh Army') }) individual_kata_event = models.CharField(max_length=22, choices=[('', ''), ], default='None') individual_kumite_event = models.CharField(max_length=22, choices=[('', ''), ], default='None') team_kata_event = models.CharField(max_length=22, choices=[('', ''), ], default='None') team_kumite_event = models.CharField(max_length=22, choices=[('', ''), ], default='None') gold = models.PositiveIntegerField(default=0) silver = models.PositiveIntegerField(default=0) bronze = models.PositiveIntegerField(default=0) picture = models.ImageField(upload_to='athlete_images', blank=True) In forms.py, class AthleteForm(forms.ModelForm): class Meta: model = Athlete fields = '__all__' widgets = { 'date_of_birth': forms.DateInput( format=('%m/%d/%Y'), attrs={ 'class': 'form-control', 'placeholder': 'Select a date', … -
convert pandas excel output to json drf django
i have this api. it returns excel header data and i want to dump pandas data to json but its showing error...................................................................... @api_view(['POST', ]) def bulkUploadPolicyMember(request): data = json.loads(request.data['data']) data = decode_data(data) data["uploaded_by"] = request.user.uid data['status'] = 0 data['uploaded_date'] = datetime.datetime.now() data['sheet'] = data['sheet'] if 'sheet' in data and data['sheet'] != '' else None data['docket_id'] = data['docket_id'] if data['docket_id'] != '' else None if data['docket_id'] is None: return CustomeResponse(request=request, comment=DOCKET_REQUIRED, data=json.dumps({}, cls=UUIDEncoder),status=status.HTTP_400_BAD_REQUEST,validate_errors=1, message=DOCKET_REQUIRED) try: doc_obj = InwardDocument.objects.values('insurer_id').get(uid=data['docket_id']) except InwardDocument.DoesNotExist: return CustomeResponse(request=request, comment=DOCKET_REQUIRED, data=json.dumps({}, cls=UUIDEncoder),status=status.HTTP_400_BAD_REQUEST,validate_errors=1, message=DOCKET_REQUIRED) policy_file_path = settings.BULK_POLICY_FILE_UPLOAD+'insurers/'+str(doc_obj['insurer_id']) try: if 'file' in request.FILES and request.FILES['file'] != "": policy_file = request.FILES['file'] # check extension if validateFileExtension(policy_file) is True: if (getFileExtByFileName(policy_file) == 'xlsx' or getFileExtByFileName(policy_file) == 'xls') and data['sheet'] is None: return CustomeResponse(request=request, comment=SHEET_NAME_CHECK, message=SHEET_NAME_CHECK, data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST,validate_errors=1) policy_file_name = file_save_by_source(request, policy_file_path, policy_file) if policy_file_name != "": data['file_name'] = policy_file_name else: return CustomeResponse(request=request, comment=COULD_NOT_UPLOAD_FILE, message=COULD_NOT_UPLOAD_FILE, data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST,validate_errors=1) try: upload_path = settings.MEDIA_URL+policy_file_path+'/'+policy_file_name try: pd_data = pd.read_excel(upload_path).columns except Exception as e: print(e) return CustomeResponse(request=request, comment=BULK_DATA_NOT_FOUND,message=BULK_DATA_NOT_FOUND, data=json.dumps({}, cls=UUIDEncoder),status=status.HTTP_400_BAD_REQUEST,validate_errors=1) except Exception as e: #print(e) return CustomeResponse(request=request, log_data=json.dumps(str(e), cls=UUIDEncoder), message=SOMETHING_WENT_WRONG, data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST, validate_errors=1) else: return CustomeResponse(request=request, comment=ALLOWED_POLICY_FILES, data=json.dumps({}, cls=UUIDEncoder),status=status.HTTP_400_BAD_REQUEST,validate_errors=1, message=ALLOWED_POLICY_FILES) else: print("->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") return CustomeResponse(request=request, comment=POLICY_FILE_REQUIRED, data=json.dumps({}, cls=UUIDEncoder),status=status.HTTP_400_BAD_REQUEST,validate_errors=1, message=POLICY_FILE_REQUIRED) except KeyError: return CustomeResponse(request=request, comment=KEY_MISSING, message=KEY_MISSING, data=json.dumps({}, …