Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DRF / JS - React Notifications API
I am working on a browser extension with a Django DRF backend and currently JS frontend ( working to convert it to React ). What I am trying to achieve is when a user clicks a buttons to trigger the Notification API for a set of users. Reading about this I have found some solutions: Websockets - currently the API is WSGI, seen that in order to add ASGI I need to change pretty much the entire foundation of my app or can I just hook up a different module that can talk to WSGI side? Sorry not very confident that I understand how this actually some clarification would be awesome. Also if for example you have 100 users with their channels open to the server how would that impact performace? The Super Hacky way - have an ajax/axios request that runs every 2 min or so and checks for DB changes, if true create the notification object. Again if you have 100 users pining the server constantly I assume performance will take a big hit Cron Job - would something like this work? Could also have a signal, post_save do something but I am not sure how I can … -
How to convert x-www-form-urlencoded to json with Python (Django)
From api i recive x-www-form-urlencoded data. data = 'leads%5Bstatus%5D%5B0%5D%5Bid%5D=29078079' when i try to convert it with urllib.parse.parse_qs or urllib.parse.unquote i got a dict like { "leads[status][0][id]": [ "29078079" ] } how can i convert it to normal json or dict ? like this { "leads": [ "id": "29078079" ] } -
Django Rest Framework Error: Unsupported Media Type: 415
Clicking on the like buttons is throwing the following error: Failed to load resource: the server responded with a status of 415 (Unsupported Media Type) The code is supposed to submit the like action, retrieve the like counts and return the new serialized data. After doing some debugging on chrome, it looks like there is something wrong in the request header as when I inserted a print statement as the first line to the view function, it was never printed on the console, which indicates the error happens before the code makes it to the backend. But, I have set all the required headers, to the best of my knowledge. Searching online did not help either. So, here I am. Here is the Vanilla JavaScript code: function handleLikeButtons(){ let likeButtonsEls = document.querySelectorAll("[id^='likeBtn-']") likeButtonsEls.forEach( (likeBtn) => { likeBtn.addEventListener( 'click', event => { event.preventDefault(); // Submit the like const method = "POST" const url = likeBtn.getAttribute("data-like-endpoint") const headerOptions = "json" const commentId = likeBtn.getAttribute("data-comment-id") const data = JSON.stringify({"id": commentId, "action": "like"}) // createXHRRequest(method, url, data, updateLikeCount, commentId, headerOptions) createXHRRequest(method, url, data, null, commentId, headerOptions) }) }) } function createXHRRequest(method, url, data=null, callbackFn, extraData = null, headerOptions = null){ const xhr = new … -
Incorrect dispatching of url
When I use the configuration below of urls.py, I can see all the API response correctly. path('blog-tags/', include([ path('', BlogTagAPIView.as_view(), name='blogtags'), path('<slug:slug_tag>/', BlogTagDetailsAPIView.as_view(), name='details-blogtag'), ])), path('blog/', include([ path('', BlogCategoryAPIView.as_view(), name="categories"), path('<slug:slug_category>/', BlogCategoryDetailsAPIView.as_view(), name="details-blogcategory"), path('<slug:slug_category>/<slug:slug_post>/', BlogPostDetailsAPIView.as_view(), name="details-blogpost"), ])), But if I use this configuration: path('blog/', include([ path('', BlogCategoryAPIView.as_view(), name="categories"), path('<slug:slug_category>/', BlogCategoryDetailsAPIView.as_view(), name="details-blogcategory"), path('<slug:slug_category>/<slug:slug_post>/', BlogPostDetailsAPIView.as_view(), name="details-blogpost"), path('tags/', include([ path('', BlogTagAPIView.as_view(), name='blogtags'), path('<slug:slug_tag>/', BlogTagDetailsAPIView.as_view(), name='details-blogtag'), ])), ])), I can't see the response from BlogTagAPIView and BlogTagDetailsAPIView and instead I see this message: HTTP 404 Not Found Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Not found." } Why happen this? -
Why response is None testing view using RequestFactory()?
I am trying to test my view using RequestFactory(). However, calling this view in the test responded as None: View def add_to_basket(request): cart = Cart(request) if request.POST.get('action') == 'post': # GETS game DATA FROM AJAX REQUEST game_id = request.POST.get('gameId') game_qty = int(request.POST.get('gameQty')) # check if game exists try: game = Game.objects.get(pk=game_id) except Game.DoesNotExist: return JsonResponse({'message': 'Game not found'}) Test setUp def setUp(self) -> None: # request factory self.factory = RequestFactory() self.middleware = SessionMiddleware() Test itself def test_add_to_basket(self): # set sessions middleware request = self.factory.get(reverse('order:add-to-cart')) self.middleware.process_request(request) request.session.save() # request.user = self.test_user response = add_to_basket(request) print(response.status_code) print(response.content) Printing response outputs None - though apart test, view is working as expected. What could cause this? -
How to download a archive using django response?
I want to download the archive after i created. The code is bellow: def downloadArchive(room, catalog): test = RoomTest.objects.get(idRoom=room) zip_name = room.name + "_" + token_urlsafe(5) + '.zip' zip_path = 'media/zipFiles/' + zip_name if test.OLD_Archive != '' and os.path.exists(test.OLD_Archive): # remove old file. os.remove(test.OLD_Archive) with ZipFile(zip_path, 'w') as zipObj: for student in catalog: zipObj.write('media/' + str(student.file), student.studentFullName() + os.path.splitext('media/' + str(student.file))[1]) test.OLD_Archive = zip_path test.save() response = HttpResponse(zipObj) response['Content-Type'] = 'application/x-zip-compressed' response['Content-Disposition'] = 'attachment; filename=' + zip_name return response Every time i try to download, got error "The archive is either in unknown format or damaged". I think the route is broken. Any ideas how can i check the response route? Btw: if i download the archive manually (after archive), it's working fine. -
Redirect in django to diferents objects
Well I've a trick question (for me at least). I want to redirect to 'clients_update' if client doesn't have adresse field complete or redirect to 'client_info' if field adresse is complete. In booth cases the redirect will be done after boolean field 'valide' in class ContactValidation change to 'True'. models.py class Contact(models.Model): id = models.BigAutoField(primary_key=True) RECLAMATION = 'Reclamation' RDV = 'Marcation de Rdv' MOTIF = [ (RECLAMATION, 'Reclamation'), (RDV, 'Marcation de Rdv') ] motif_contact = models.CharField( max_length=40, choices=MOTIF, default=RDV, ) categorie = models.CharField(default=None, max_length=40) type_client = models.CharField(default=None, max_length=40) date_debut = models.DateTimeField(default=None) date_fin = models.DateTimeField(default=None) description_contact = models.TextField(max_length=1000) intervenants = models.ForeignKey(User, on_delete=models.CASCADE) client_contact = models.ForeignKey(Clients, on_delete=models.CASCADE, default=None) class Meta: verbose_name = 'contact' def __str__(self): return self.motif_contact class ContactValidation(models.Model): contact_validation = models.OneToOneField(Contact, on_delete=models.CASCADE, default=False, primary_key=True, parent_link=True) valide = models.BooleanField(default=False, null=True) def creation_contact (sender, instance, created, **kwargs): if created: ContactValidation.objects.create(contact_validation = instance) signals.post_save.connect(creation_contact, sender=Contact, weak=False, dispatch_uid='models.creation_contact') views.py def validation_contact(request): validation = Contact.objects.all() confirmer = ContactValidation.objects.all() context = { 'validation' : validation, 'confirmer': confirmer } return render(request, 'validation_attente.html', context) @login_required(login_url='login') def validation_confirmation(request, pk): form_validation = ContactValidationForm() contact_validation = get_object_or_404(Contact, pk=pk) if request.method == 'POST': form_validation = ContactValidationForm(request.POST or None) if form_validation.is_valid(): newconfirmation = form_validation.save(commit=False) newconfirmation.contact_validation = contact_validation newconfirmation.save() return redirect('client_update', pk=pk) else: form_validation = … -
How can i upload multiple files with base64 in Django Rest Framework?
I started learning DRF and I'm trying to clone Twitter on VueJs to improve myself. On the VueJs side, I use FileReader for file upload and send the base64 code of the uploaded images to DRF when the form is submitted. On the DRF side, I convert these base64 codes to ContentFile, but at the end I get the errors I mentioned below. {'files': [{'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got ContentFile.', code='invalid')]}, {'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got ContentFile.', code='invalid')]}]} Internal Server Error: /api/add-tweet/ Traceback (most recent call last): File "C:\Users\adilc\Desktop\twitter-vue-django\twitter\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\adilc\Desktop\twitter-vue-django\twitter\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "C:\Users\adilc\Desktop\twitter-vue-django\twitter\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\adilc\Desktop\twitter-vue-django\twitter\lib\site-packages\rest_framework\response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "C:\Users\adilc\Desktop\twitter-vue-django\twitter\lib\site-packages\rest_framework\renderers.py", line 100, in render ret = json.dumps( File "C:\Users\adilc\Desktop\twitter-vue-django\twitter\lib\site-packages\rest_framework\utils\json.py", line 25, in dumps return json.dumps(*args, **kwargs) File "C:\Users\adilc\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 234, in dumps return cls( File "C:\Users\adilc\AppData\Local\Programs\Python\Python38\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Users\adilc\AppData\Local\Programs\Python\Python38\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "C:\Users\adilc\Desktop\twitter-vue-django\twitter\lib\site-packages\rest_framework\utils\encoders.py", line 50, in default return obj.decode() UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte How can I … -
Deploying self-hosted Django dynamic website
So here's the thing: I have a Django app and I want to self host it (LAMP). Superficially, the dynamic website receives images, a OCR process is made and the results are returned to the client. The app could be accessed on average by 5 people at the time (to start with). The memory use could amount to 500 MB per client but it is erased afterwards (I'm not storing data whatsoever after the client has received the website output). So here is one of my doubts: I have some Compaq towers without using (processor: AMD Athlon X2 Dual-Core 7550. Memory: 2GB. Hard-Drive: 250 GB). Are there any restrictions towards installing Apache web server and deploying a dynamic website in desktop machines (besides the speed given by processors such as the Intel Xeon Platinum)? For example, could this tower receive requests from 5 different clients at the same time or this can't be done by a desktop processor? Or should I expect the tower overheating and the dynamic website being really slow? ---- I'm thinking about recycling and saving some money at the cost of a slower website (not extremely low I hope). Any recommendations about what Linux distribution to … -
Django 3 - null value in column "x" of relation
I'm struggling with the django rest project. I want to have some data in my database visible only for current logged in user. I did it by using my serializer and filtering - it's working. The next step is to add data to the database. My purpose is to add data only by admin user, so I have added my custom permission class: permission_classes = (IsAdminOrReadOnly,). Admin also has to have the possibility to specify used owned the data. It's working when I'm using django admin panel. And finally I want to post the data e.g: { "unix": 0, "user": "example@email.com" } Based on the email - I want to specify the user and assign posted data to the user. I have some idea how to resolve this but right now I'm struggling with the error: django.db.utils.IntegrityError: null value in column "user_id" of relation "rest_userstats" violates not-null constraint But did not find the solution yet I did prepare some model class: models.py class UserStats(models.Model): user = models.ForeignKey(get_user_model(), related_name='statistics', on_delete=models.CASCADE, null=True) user_email = models.EmailField() unix = models.IntegerField() serializers.py class UserStatsSerializer(serializers.ModelSerializer): class Meta: model = UserStats fields = ( 'unix', 'user_email', ) views.py class UserStatsViewSet(viewsets.ModelViewSet): serializer_class = UserStatsSerializer queryset = UserStats.objects.all() permission_classes … -
Django Make user to superuser on the frontend
I want to allow an admin/superuser to set already created users to be also a superuser. How would I go about this? I am new to Django. There is a separate user editing page and I want to add a button that would by clicking it change the is_superuser to True. -
Django object on creation isn't stored in the database and the ID is returned as null
I creating a basic notes application where user can perform CRUD operation. Following are my models, views and URLs. from django.db import models from accounts.models import User from django.utils import timezone class Notes(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): if not self.id: self.created_on = timezone.now() self.last_updated = timezone.now() def __str__(self): return self.title Views.py from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework import viewsets, status from rest_framework.response import Response from . import serializers, models class NotesViewSet(viewsets.ModelViewSet): queryset = models.Notes.objects.all() serializer_class = serializers.NotesSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def list(self, request): notes = models.Notes.objects.all().filter(user=request.user) serializer = serializers.NotesSerializer(notes, many=True) return Response(serializer.data) def create(self, request): serializer = serializers.NotesSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) def retrieve(self, request, pk=None): note = models.Notes.objects.filter(id=pk) serializer = serializers.NotesSerializer(instance=note) return Response(serializer.data) def update(self, request, pk=None): note = models.Notes.objects.get(id=pk) serializer = serializers.NotesSerializer( instance=note, data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_202_ACCEPTED) def destroy(self, request, pk=None): note = models.Notes.objects.get(id=pk) note.delete() return Response({"message": "Note deleted"}, status=status.HTTP_202_ACCEPTED) urls.py from django.urls import path from .views import NotesViewSet app_name = 'notes' urlpatterns = [ path('get', NotesViewSet.as_view({ 'get': 'list', }), name='get'), path('create', NotesViewSet.as_view({ 'post': 'create', }), name='create'), path('get/<str:pk>', NotesViewSet.as_view({ 'get': 'retrieve', … -
Error: 'The archive is either in unknown format or damaged' - Django
I got 'The archive is either in unknown format or damaged' error when i download a file and open it. Image: I download the zip from a response provide from browser. Any idea how can i solve this? -
Django Webpack Loader: "Assets" KeyError?
I recently upgraded a Django app to current Django and Python versions, and updated my pip packages as well. Now I'm getting this error: Django Version: 3.2.3 Exception Type: KeyError Exception Value: 'assets' Exception Location: /my/env1/lib/python3.8/site-packages/webpack_loader/loader.py, line 90, in get_bundle Looking at the Exception Location, I see: ...and looking at assets, confirms it has no key named assets: How do I fix this? -
Can a Django model's choices be mapped to classes that are not models?
I've got a bunch of MealIngredient models which have a foreign key of UnitChoice like so: class MealIngredient(models.Model): ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) meal = models.ForeignKey(Meal, on_delete=models.CASCADE) unit = models.ForeignKey(IngredientUnit, on_delete=models.CASCADE, null=True) quantity = models.FloatField(validators=[MinValueValidator(0.0)], default=1) class IngredientUnit(models.Model): UNIT_CHOICES = [ ('Imperial', ( (Volume.pinch, 'pinch'), (Volume.teaspoon, 'teaspoon'), (Volume.tablespoon, 'tablespoon'), (Volume.fluidOunce, 'fluid ounce'), (Volume.cup, 'cup'), (Volume.pint, 'pint'), (Volume.quart, 'quart'), (Volume.gallon, 'gallon'), (Mass.ounce, 'ounce'), (Mass.pound, 'pound'), ) ), ('Metric', ( (Volume.milliliter, 'milliliter'), (Volume.centiliter, 'centiliter'), (Volume.deciliter, 'deciliter'), (Volume.liter, 'liter'), (Volume.decaliter, 'decaliter'), (Volume.hectoliter, 'hectoliter'), (Volume.kiloliter, 'kiloliter'), (Mass.gram, 'gram'), (Mass.kilogram, 'kilogram'), ) ), ('individual', 'individual') ] unit_choice = models.CharField(choices=UNIT_CHOICES, default='individual', max_length=20) I've imported 'sugarcube' which lets you define units, conversions, etc. My issue is that the classes imported from sugarcube (Volume, Mass, etc.) are not models, and as such I'm getting: ValueError: Cannot serialize: pinch There are some values Django cannot serialize into migration files. Is there a way to make this work? Can I make sugarcube's classes serializable? -
Know which field is raising exception in django save
I am calling a save() method of a django model, and I get the following error: Validation Error(["El valor '' debe ser un número decimal"]) ("The value '' must be a decimal number"), but it doesn't say which field is the wrong one. How can I know which field is raising the exception? -
How to get the difference value from table - django?
I am new to Django and came up with a problem. I have a table like TABLE Id Title Type Value 1 A 1 10 2 B 1 20 3 C 2 5 Now from the above table how can I get a value where I sum the value of a similar type and subtract the value from the different type (A+B-C =25). Also, I have a value of two types only. How can I write the query to get the result. -
python Django how show category data on CART Page?
Hi i am new i want to show after customer select a category product then related category other items show bellow on CART page. following are my model. Model.py class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() image = models.ImageField() Cart Page Screen Shoot -
Django custom groups and permission
djangorestframework==3.12.4 django==3.2.2 My requirements - need to add few more fields to Group Model and Permission Model like - created_by, is_active. need to have an API to create Group, only for authorized users. Also, all users cannot see all permission. Idea is- Say there is one user type called Author of organization XYZ then it can create groups and assign certain groups and permission to the users of its own organization. What I tried - Creating custom group model, custom permission model, but it has reference to pemrissionMixin this way I need to rewrite the whole logic of mixin too. Any Idea, how can I effectively achieve the above requirements? -
I've managed to create a file insert input on django but I would like to put the input action on a div instead
right now i managed to insert files using the input ("escolher arquivo") thing but I would like to put the action on the div like in the picture. Is there a way to do that on django? -
How to Update Domain (DomainMixin)in client in django-tenant programmatically
How to Update Domain (DomainMixin)in client in django-tenant programmatically class Client(TenantMixin): type = models.CharField(max_length=100, choices=get_tenant_type_choices()) name = models.CharField(max_length=100) description = models.TextField(max_length=200) created_on = models.DateField(auto_now_add=True) auto_create_schema = True def __str__(self): return self.schema_name class Domain(DomainMixin): pass After creation of tenant How To update Domain again.No existing command there? -
Filter Products by Distribution Center Quantity Channel advisor REST API
I am working on a django project in which I am fetching products from Channel Advisor platform using the file export feature. I am using the filter '$filter=ProfileID eq and TotalQuantity gt 0'. https://developer.channeladvisor.com/working-with-products/product-exports I would like to query the product based on the value present in 'Qty Avail Warehouse' field present in catalogs listing page instead of 'TotalQuantity'. Or filter by distribution center quantity eg: those products having stock greater than 0 in 'Phoenix' distribution center. Thank you. -
Django Rest Framework - Multiple data commit to db
I am building a shift management system, wherein i want to mark the user's availability during the shifts, the user can update his availability status later. To achieve this i am trying to split the shifts in case of overlapping availability. I am unable to achieve multiple data commit to db. I need to understand how to insert multiple data's. basically i need to know how to insert the old fetched details* to this details field and other fields to the Shift_Availability_Model details = ShiftDetailModelSerializer(many=True, read_only=True) views.py class SplitShiftAvailabilityViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = Shift_Availability.objects.all() serializer_class = MultipleShiftModelSerializer filter_backends = (SearchFilter, OrderingFilter, DjangoFilterBackend) filter_fields = [ "group_ref" ]``` serializer.py class MultipleShiftModelSerializer(serializers.ModelSerializer): """Shift model serializer""" details = ShiftDetailModelSerializer(many=True, read_only=True) force = serializers.BooleanField(required=False) # employee = EmployeeModelSerializer() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.context["employee"] = None self.context['travel_method'] = None def internal_validate(self, data, field): self.context[field] = data if data == None: return data elif data.id: return data.id return data def validate_employee(self, data): return self.internal_validate(data, "employee") def validate_travel_method(self, data): return self.internal_validate(data, "travel_method") class Meta: """Meta class.""" model = Shift_Availability fields = '__all__' @transaction.atomic def create(self, data): force = data.pop('force') old_shift_data = OverlapingShiftReturn().return_overlapping( data['employee'], data['start_date'], data['end_date'], force ) # print('old_shift_data = ', old_shift_data) ShiftValidator().overlappingValidation( data['employee'], … -
Django Selenium test works in local Docker container but not on Jenkins server
When I run the Docker image locally in interactive mode and then do the test manually it works. But when I push to GitHub, Jenkins pulls and runs the tests and then times out when trying to initiate the Firefox browser. I tried with different Docker base images. I tried with giving executable_path to local file, and also without(while adding system path). I am new to Docker and Jenkins and I'm not sure what I'm doing wrong. Thanks in advance for any help. dockerfile: FROM ubuntu:bionic COPY BS_PM2021_TEAM_27/requirements.txt requirements.txt RUN apt-get update RUN su - RUN apt-get install sudo -y RUN sudo apt-get install -y xvfb RUN sudo apt-get install -y firefox RUN sudo apt-get install -y wget RUN wget https://github.com/mozilla/geckodriver/releases/download/v0.24.0/geckodriver-v0.24.0-linux64.tar.gz RUN tar -xvzf geckodriver* RUN chmod +x geckodriver RUN sudo mv geckodriver /usr/local/bin/ RUN export GECKODRIVER=$PATH:/user/local/bin/geckodriver RUN sudo apt-get install -y python3.8 RUN sudo apt-get install -y python3-pip RUN pip3 install -r requirements.txt RUN Xvfb & RUN export DISPLAY=localhost:0.0 WORKDIR . COPY . . requirements.txt: asgiref==3.3.4 Django==3.2.3 EasyProcess==0.3 filter-profanity==1.0.9 pytz==2021.1 PyVirtualDisplay==2.2 selenium==3.141.0 sqlparse==0.4.1 urllib3==1.26.5 Jenkinsfile: pipeline { environment { OUTPUT1 = "foo" OUTPUT2 = 'bar' } agent { dockerfile true } triggers { githubPush() } stages { stage('Build') { … -
How to edit fields without using forms in django
Sorry if my codes are inefficient or if the question is dumb but I have a product named car and I used this code to add a car into the database. I didn't use forms because of the checkboxes i used. views.py for adding a car def add_car(request): if request.method == 'POST' and request.FILES: user_id = request.POST['user_id'] brand = request.POST['brand'] status_of_car = request.POST['status_of_car'] city = request.POST['city'] ilce = request.POST['ilce'] e_mail = request.POST['e_mail'] phone_number = request.POST['phone_number'] car_title = request.POST['car_title'] description = request.POST['description'] price = request.POST['price'] serial = request.POST['serial'] color = request.POST['color'] model = request.POST['model'] year = request.POST['year'] condition = request.POST['condition'] body_style = request.POST['body_style'] engine = request.POST['engine'] transmission = request.POST['transmission'] interior = request.POST['interior'] kilometers = request.POST['kilometers'] passengers = request.POST['passengers'] power_of_engine = request.POST['power_of_engine'] fuel_type = request.POST['fuel_type'] no_of_owners = request.POST['no_of_owners'] car_photo = request.FILES.get('car_photo') car_photo_1 = request.FILES.get('car_photo_1') car_photo_2 = request.FILES.get('car_photo_2') car_photo_3 = request.FILES.get('car_photo_3') car_photo_4 = request.FILES.get('car_photo_4') car_photo_6 = request.FILES.get('car_photo_6') car_photo_5 = request.FILES.get('car_photo_5') car_photo_7 = request.FILES.get('car_photo_7') car_photo_8 = request.FILES.get('car_photo_8') car_photo_9 = request.FILES.get('car_photo_9') car_photo_10 = request.FILES.get('car_photo_10') car_photo_11 = request.FILES.get('car_photo_11') car_photo_12 = request.FILES.get('car_photo_12') car_photo_13 = request.FILES.get('car_photo_13') car_photo_14 = request.FILES.get('car_photo_14') feature_1 = request.POST.get('feature_1') feature_2 = request.POST.get('feature_2') feature_3 = request.POST.get('feature_3') feature_4 = request.POST.get('feature_4') feature_5 = request.POST.get('feature_5') feature_6 = request.POST.get('feature_6') feature_7 = request.POST.get('feature_7') feature_8 = request.POST.get('feature_8') feature_9 = request.POST.get('feature_9') feature_10 = …