Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does Django automatically retrieve the parent object when a retrieved child object references that object?
In the Spring framework when an object A has a ManyToOne relation to object B: public class objectA{ private Long id; @ManyToOne private objectB objectB; } Then that objectB is only fetched when the getter method for objectB is called somewhere i nthe code. In that case an extra SQL query is made to fetch objectB of that particular objectA instance. You can change that behaviour by changing the fetch strategy to EAGER, in that case objectB is also fetched during the initial query to fetch objectA. My question is: What is the default fetch style that Django uses? Does Django always fetch any referenced parent objects or childobjects eagerly? Or does it differ per relation? Thank you -
Django: TypeError: an integer is required (got type str)
here i am getting the error, File "C:\Users\DEEDEVTR01\Desktop\python\pyenv\lib\site-packages\MySQLdb\__init__.py", line 84, in Connect return Connection(*args, **kwargs) File "C:\Users\DEEDEVTR01\Desktop\python\pyenv\lib\site-packages\MySQLdb\connections.py", line 179, in init super(Connection, self).init(*args, **kwargs2) TypeError: an integer is required (got type str) views.py from rest_framework import views from rest_framework.views import APIView import MySQLdb from testpro.settings import connection cur, conn = connection() class Product_ListAPIView(APIView): def get(self,request,format=None): cur,conn = connection() query = ''' SELECT * FROM products''' try: with conn.cursor(MySQLdb.cursors.DictCursor) as cursor: cursor.execute(query) result = cursor.fetchall() data = list(result) return Response({"data":result},status=status.HTTP_200_OK) except Exception as e: print(e) -
How to add markers and send the locations to postgres/postgis database in django-leaflet
I added a django-leaflet map to display place markers. I couldn't display the markers as click events and send these to postgres/postgis database. I used django-leaflet forms to input the data. I wonder how I could display the place markers as well as send these to the backend along with other model fields. {% load static %} {% include 'base.html' %} {% load leaflet_tags %} <style> .leaflet-container { /* all maps */ width: 1400px; height: 800px; align-content: right; } </style> <html> <head> {% leaflet_js plugins="forms" %} {% leaflet_css plugins="forms" %} </head> <body> {% leaflet_map "map" callback="window.map_init_basic" %} <h2>Edit Apartment ID {{ Apartment.apt_id }}</h2> <h2>Edit Apartment Location {{ Apartment.location }}</h2> <form action="POST"> {{ form }} <input type="submit"/> </form> </body> </html> <script type="text/javascript"> window.addEventListener("map:init", function (e) { var detail = e.detail; L.marker([38.7578, 8.9806]).addTo(detail.map); }, false); </script> -
How do I extract all distint values for a specific key inside JSONField in Django running on Postgres?
Summary: For a dropdown I need to compute the distinct values for a specific key stored inside a JSONField in a table in Postgres database. Worst case scenario: The table contains 1-10 million entries. Background: I'm developing a setup in which I have multiple deployments (one for each customer). Each deployment contains a backend and multiple clients. Logs are posted continuously from clients to the backend. These logs will contain a field log_meta, which includes a key named origin, that describes from where the log-entry came. From customer to customer the value of origin may vary, and I don't want to enforce a restricted set of values for origin, but in general they denote the environment in which the client is running; "DEV" and "PRODUCTION" are potential values for origin. In practice, there might be only 1-2 distinct values for origin in a single deployment. The number of logs can be expected to be in the range of 1-10 millions. from jsonfield import JSONField from django.db import models class Log(models.Model) # Other fields log_json = JSONField(default=list) log_meta: JSONField(default=dict) # Will contain a key named origin In an "administrator frontend" I want to support that the administrator can filter (via a … -
AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from view, but received `<class 'NoneType'>`
I have the following model - class Userdetails(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, blank=True, null=True) userno = models.CharField(max_length=200, blank=True, null=True And following View - @api_view(['GET', 'POST']) def useroptions(request): # to create new user if request.method == 'GET': names = Userdetails.objects.values("name","userno","id") return Response(names) elif request.method == 'POST': count = Userdetails.objects.count() serializer = userdetailsSerializer(data=request.data) usernos = Userdetails.objects.values("userno") names = Userdetails.objects.values("name") list_of_names = [] for ele in names: list_of_names.append(ele["name"]) list_of_usernos = [] for ele in usernos: list_of_usernos.append(ele["userno"]) This gives me this error on CMD - Internal Server Error: /view/pardel/2/multiuser Traceback (most recent call last): File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/rest_framework/views.py", line 507, in dispatch self.response = self.finalize_response(request, response, *args, **kwargs) File "/home/hostbooks/django1/myproject/lib/python3.6/site-packages/rest_framework/views.py", line 422, in finalize_response % type(response) AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` [13/Feb/2020 08:09:14] "POST /view/pardel/2/multiuser HTTP/1.1" 500 17234 I am not getting the reason for this error and Please me to sort … -
Django ManytoManyField Display User Profile
i got stuck when trying to display User Name as Manytomanyfield in django template, but always display with ]>. how can i display it without queryset bla bla bla... just User 1 (First Name or Last Name or Full Name) class Refferal(models.Model): ref = models.ManyToManyField(Profile, related_name='ref') profile = models.ForeignKey(Profile, on_delete=models.PROTECT) def __str__(self): return str(self.ref) {% for tree in tree %} <section> <span class="diagram-icon"></span> <span class=diagram-label>{{ tree.ref.all }}</span> </section> {% endfor %} -
Django 'docker' is not recognized as an internal or external command,
when i type this docker run -p 6379:6379 -d redis:2.8 in pycharm terminal I receive this error did i miss something? -
Configuring HTTPS redirect fails
I am hosting a Django application on digitalocean. I follow this tutorial to finish its SSL certification. Following that tutorial I don't know where to add this line of code: return 301 https://$server_name$request_uri; I tried adding it in /etc/nginx/sites-enabled/leptitox_pro server { listen 80; server_name 68.183.203.33 yahkut.com www.yahkut.com; return 301 https://$server_name$request_uri; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/leptitoxadmin/pyapps/Leptitox; } location /media/ { root /home/leptitoxadmin/pyapps/Leptitox; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } when it didn't work I added it in /etc/nginx/sites-available/leptitox_pro server { listen 80; server_name 68.183.203.33 yahkut.com www.yahkut.com; return 301 https://$server_name$request_uri; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/leptitoxadmin/pyapps/Leptitox; } location /media/ { root /home/leptitoxadmin/pyapps/Leptitox; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } it didn't work there as well, so I added below the server block of code in /etc/nginx/nginx.conf: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { server { # new listen 80; # new server_name yahkut.com; # new return 301 https://$server_name$request_uri; # new } ## # Basic Settings ## sendfile on; tcp_nopush on; } I then restarted ngnix and run nginx … -
custom search filter in django modelviewset not showing anything
I'm trying to do a searchfilter on modelviewset and I think the way to do this is to create a custom search filter. Not sure whats missing but its not working. Its not returning anything. This is what I have so far: my custom search filter on another file: class CustomSearchFilter(SearchFilter): def get_search_fields(self, view, request): if request.query_params.get('courseCode'): return ['courseCode'] return super(CustomSearchFilter, self).get_search_fields(view, request) my model view set: class CourseViewSet(viewsets.ModelViewSet): authentication_class = (TokenAuthentication, ) permissions_class = (IsAuthenticated, ) def list(self, request): if self.request.user.is_professor: user = self.request.user paginator = LargeResultsSetPagination() search = CustomSearchFilter() course = Course.objects.filter(course_professor=user) prof = User.objects.filter(is_professor=True) result_page = paginator.paginate_queryset(course, request) paginator_count = paginator.get_paginated_response(course) course_serializer = CourseSerializer(result_page, many=True) prof_serializer = UserSerializer(prof, many=True) search_queryset = search.get_search_fields(course,request) search_ser = CourseSerializer(search_queryset, many=True) response = {'message': 'Sucess!', 'prof': prof_serializer.data, 'course': course_serializer.data, 'page': paginator_count.data, 'search': search_ser.data } return Response(response, status=status.HTTP_200_OK) -
upload image from angular 7 to Django
my UI is angular 7 and backend Django. i wanna upload my image in FileField at django backend: this is my api code: class UploadImage(APIView): parser_classes = (FileUploadParser,) renderer_classes = [JPEGRenderer] def put(self, request, filename, format=None): try: _u = request.user users = UserProfiles.objects.filter(user=_u) for g in users: g.picture = request.data['file'] g.save() return response.Response({'status': 0, 'msg': 'upload successfully!'}, status=HTTP_200_OK) except Exception as e: print(e) return response.Response({}, status=HTTP_400_BAD_REQUEST) and this is my JPEGRenderer : from rest_framework.renderers import BaseRenderer class JPEGRenderer(BaseRenderer): media_type = 'image/jpeg' format = 'jpg' charset = None render_style = 'binary' def render(self, data, media_type=None, renderer_context=None): return data when i sent my image to backend i take 406 acceptable http error my request: Request URL:api/user/upload_img/IMG_20181207_160953.jpg Request method:PUT Remote address:127.0.0.1:8000 Status code: 406 Version:HTTP/1.1 Referrer Policy:no-referrer-when-downgrade request headers: Host: localhost:8000 User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0 Accept: application/json Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Referer: http://localhost:4200/ Authorization: Bearer eyJ0eXAiOiJFp Content-type: image/jpeg enctype: multipart/form-data Content-Length: 255159 Origin: http://localhost:4200 Connection: keep-alive Pragma: no-cache Cache-Control: no-cache and my image is in request payload -
I am not able to reset password
TimeoutError at /passwordreset/ [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond Request Method: POST Request URL: http://127.0.0.1:8000/passwordreset/ Django Version: 3.0.2 Exception Type: TimeoutError Exception Value: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond Exception Location: C:\Users\saikr\AppData\Local\Programs\Python\Python38\lib\socket.py in create_connection, line 796 Python Executable: C:\Users\saikr\AppData\Local\Programs\Python\Python38\python.exe Python Version: 3.8.1 Python Path: ['C:\New_Django\Realtime', 'C:\Users\saikr\AppData\Local\Programs\Python\Python38\python38.zip', 'C:\Users\saikr\AppData\Local\Programs\Python\Python38\DLLs', 'C:\Users\saikr\AppData\Local\Programs\Python\Python38\lib', 'C:\Users\saikr\AppData\Local\Programs\Python\Python38', 'C:\Users\saikr\AppData\Local\Programs\Python\Python38\lib\site-packages', 'C:\Users\saikr\AppData\Local\Programs\Python\Python38\lib\site-packages\win32', 'C:\Users\saikr\AppData\Local\Programs\Python\Python38\lib\site-packages\win32\lib', 'C:\Users\saikr\AppData\Local\Programs\Python\Python38\lib\site-packages\Pythonwin'] Server time: Thu, 13 Feb 2020 07:29:38 +0000 -
How to throw back serializer.errors in Django?
How do I throw the serializer.errors if I have a wrong input in some field? Do I have to code some "logic", or I just have to "write" some configurations. #models.py class Product(models.Model): name = models.CharField() amount = models.IntegerField() description = models.TextField() #serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' def create(self, validated_data): ... def update(self, instance, validated_data): ... #views.py class ProductViewSet(viewsets.ModelViewSet): serializer_class = ProductSerializer def partial_update(self, request, pk=None): ... def get_queryset(self): ... For example I want to POST: { "name": "Banana", "amount": "ABCD", "description": "" } Instead of getting an error in the server: ValueError: invalid literal for int() with base 10: 'ABCD' I want a response like this: {"amount": ["A valid integer is required."], "description": ["This field may not be blank."]} -
Django server and prestodb connection and data pagination
I have a simple infrastructure that is using django server for APIs and PrestoDb as query engine. Everything is working fine for me but I have few limitations depending on prestodb: Prestodb doesn't support pagination, How can I manage huge amount of data? loading it into memory is costly. I am opening and closing connection to presto again and again for each query, What is the best way to use only one or two connections only and use them all over the application? What is the proper way to show errors to users instead of raw presto exceptions? What kind of caching mechanism should be used for common data? I am using celery for background jobs, is there any other for running background jobs that are not load on python server? What are best practices for django? Any helpful link? -
Using with and if simultaneous in django template
my view : I have used templated_context_processor for my convinience def list_subtest(request): return {'subtest':Subtest.objects.all(),'test':Test.objects.all()} my models :Here I have test and subtest models. For example Blood falls in test category and hemoglobin falls in subtest category class Test(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Subtest(models.Model): name = models.CharField(max_length=100) test = models.ForeignKey(Test,on_delete=models.CASCADE,related_name='subtest',blank=True, null=True) unit = models.CharField(max_length=10) reference_value = models.IntegerField() selected = models.BooleanField(default=False) def __str__(self): return self.name my template : I want to show the test and the subtest that falls under the same test . <ul class="nav-list"> <li> <a href="#">Test</a> <form class="hero-menu"> {% for test in test %} <div class="category-block"> <ul class="dropdown-list"> <li> <a href="#"><h4 data-modal-target="menu-test-popup"> {{test.name|title}} </h4></a> </li> {% for subtest in subtest %} {% with subtest.test as name %} {% if name %} <li> <div class="checkbox-group"> <input type="checkbox" id="aUniqueName" name= value="example"/> <label for="aUniqueName"> {{subtest.name}} </label> </div> </li> {% endif %} {% endwith %} {% endfor %} -
django project how to integrate with tcp/udp request
i want to collect and store data from one tracking device, That device using TCP UDP protocol, I don't know how to integrate my project with tracking device, am using Django frame work, any one know the solution please let me know. -
Disqus Commenting - show latest 10 comment first
how to load latest 10 comment first in disqus? i have already read this docs https://django-disqus.readthedocs.io/en/latest/templatetags.html , but i didn't got any helpful. any help, would be appreciated. thanks! -
Django tutorial part 5. Indexview testing doesn't get message "No polls are available."
I tried to run the testing on django tutorial part 5. But I couldn't pass. The test class is like below class QuestionIndexViewTests(TestCase): def test_no_questions(self): """ If no questions exists, an appropriate message is displayed """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_future_question(self): """ Questions with a pub_date in the future aren't displayed on the index page. """ create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_question_list'], []) def test_past_question(self): """ Questions with pub_date in the past are displayed on the index page """ create_question(question_text="Past question.", days=-30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_future_question_and_past_question(self): """ Even if both past and future questions exist, only past questions are displayed """ create_question(question_text="Past question.", days=-30) create_question(question_text="Future question.", days=30) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question.>'] ) def test_two_past_questions(self): """ The questions index page may display multiple questions. """ create_question(question_text="Past question 1.", days=-30) create_question(question_text="Past question 2.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) Errors occured in functions test_future_question and test_future_question_and_past_question. I able passed the test when I commented out the statements 'self.assertContains(response, "No polls are available.")' It seems like I need … -
Djnago manage.py makemigrations killed always
(venv) /project/Backend$ python manage.py makemigrations Killed (venv) /project/Backend$ python manage.py runserver Watching for file changes with StatReloader Performing system checks... -
How access all information provided by DEBUG=TRUE on production server without accessing it to users
I have a project which is in development stage. Now I am building authorization app where I want to put logic 1 - user registered on site after registration he by default isn't verified. 2 - backend send email verified letter to user provided email while registering. 3 - letter contain link with domain.uid. 4 - user clicking on link in letter which will redirect him and if all above steps is good his account verified. All above logic I have created but faced with problem link which send to user's email domain.uid contain domain which in development server equal == localhost because of it while I am debugging it click on link it's give me 404 error. I decided that my problem can be solved by providing really registered domain. I bought domain linked it to my hosting and deployed my project with gunicorn, nginx on production server. Now I am faced with another I read that DEBUG=TRUE on production server can be cached with Google and provide vulnerabilities . And now my question how I can access DEBUG=TRUE information from my production server with closing this information to users??? Or I should doing by another way?? Please guide … -
Django multivalue for a field
I want to have a table schema as below. table 1: User userid, tech, other here tech is a foreign key to Tech table object Table 2: Tech techid, techanme, scenes Here, I want multiple values to be assigned to the scenes. How can I do this using django models. (Please see I used manytomanyfields, but there I could not get back the scenes for the techname as required) -
how do i generate custom 404/500 error page in django app on entring or requesting a wrong url which is not exist in the project
i have tried the code bellow to generate custom error/404/500 page but its not working at all, actually i want to raise this error when user tries to enter wrong url,then a custom error page with 404/500 would be displayed to the user. views.py from django.shortcuts import render from django.shortcuts import render from django.conf import settings def error_404(request,exception): context = {} context = {"project name":settings.PROJECT_NAME} return render(request,'error_404.html',context) def error_500(request): context = {} context = {"project name":settings.PROJECT_NAME} return render(request,'error_500.html',context) app urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path from django.conf.urls import handler404, handler500, include from .import views import testapp from testapp import views as common_views urlpatterns = [ path('error_404',views.error_404,'error_404'), path('error_500',views.error_500,'error_500'), ] project/urls.py from django.contrib import admin from django.urls import path from django.conf.urls import handler404, handler500, include from testapp import urls import testapp from testapp import views as common_views urlpatterns = [ path('admin/', admin.site.urls), path('', include(testapp.urls)), ] handler404 = common_views.error_404 handler500 = common_views.error_500 -
Ordering by geospatial data and moving up specific records based on a field - ElasticSearch DSL DRF
The situation I'm currently trying to solve is a case where GeoSpatialOrderingFilterBackend is used from ElasticSearch DSL - DRF, which orders the documents based on a location (lat, long), this in return gives out a elasticsearch_dsl.search.Search queryset - ordered as it should; although I have a case where some are featured and therefore would like to move them to the top of the queryset. Scenario (as is): Record 1, Location X, Featured False Record 3 Location Y, Featured False Record 2, Location Z, Featured True Expected: Record 1, Location Z, Featured True Record 2, Location X, Featured False Record 3, Location Y, Featured False Sorting afterwards (as shown below) on the queryset puts the featured up at the top; although scrambles the whole geospatial/location ordering. result = super().filter_queryset(request, queryset, view).sort('-featured') I'm looking for a way to put the featured records up at the top; but maintain the order of the records. -
During AJAX call of POST method converted to GET method when using with Django i18n pattern
I have used Django i18n pattern in my project to convert my website text between english and german. I have handled all post methods with common code written in webbase.js file. After implementation of Django i18n code in my project, my website started to behave strangely and converted my all POST mehtod with GET. I have already tried with solutions explained online like below. sol-1 : Append slash after url. sol-2 : AJAX call I have tried with both type: "POST" ad method: "POST". But even after updating code as per solution, still I am not able to solve my issue. My code is as below. webbase.js app.post = function(url, postData, hasMsg, callback, dataType, msgId, processData, contentType) { try { msgId = msgId || "appMsg" var ajaxParam = { dataType: dataType || "json", type: "POST", headers: { "X-CSRFToken": app.getStorage("csrftoken") }, url:url, data: postData, beforeSend: function() { ajaxCalls++; $('#loading-image').show(); }, complete: function() { ajaxCalls--; if(ajaxCalls == 0) { $('#loading-image').hide(); } }, success: function(data) { if (hasMsg) { if (data.code == 0) { app.showMessage(msgId, app.MsgType.Error, data.msg, 10); return; } app.showMessage(msgId, app.MsgType.Success, data.msg, 10); } if(callback) { callback(data); } }, error: function(data) { app.showMessage(msgId, app.MsgType.Error, "Error occurred", 10); console.log(data); } } if(typeof processData … -
How to redirect to the same page after successful POST request?
Here I have a newsletter form inside every pages so I placed it inside base.html and I wrote views like this. What I want is if the user process the request from home page it should redirect to the homepage and if the user send request from services page it should redirect to the services page and so on. With request.path_info this is returning to the /newsletter/ path but I don't want that.I want to redirect to that template from where the request has been sent. base.html <form action="{% url 'newsletter' %}" method="POST" class="form-inline"> {% csrf_token %} <input type="text" placeholder="Email Address" name="email" class="form-control"> <button class="btn btn-primary btn--subcribe" type="submit">Subcribe</button> {% if form.email.errors %}<b class="text text-danger"> </form> I tried with request.path_info like this def newsletter(request): form = NewsletterForm() if request.method == "POST": form = NewsletterForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Thank you for your subscription.') return redirect(request.path_info) return render(request, 'base.html', {'form': form}) -
get data from form.cleaned_data in a dictionary
I have a django form which sends data as: {'transaction_date': datetime.date(2020, 2, 13), 'dispatch_date': datetime.date(2020, 2, 13), 'send_from_warehouse': <Warehouse: test_warehouse>, 'sales_order': <MaterialRequest: 6>, 'parent_company': <Client: client>, 'product1': '132', 'product1_quantity': 273, 'product2': '231', 'product2_quantity': 273, 'product3': '213', 'product3_quantity': 325, 'product4': '216', 'product4_quantity': 325, 'product5': '564', 'product5_quantity': 260, 'product6': None, 'product6_quantity': None, 'product7': None, 'product7_quantity': None, 'product8': None, 'product8_quantity': None, 'model': 'Sell', 'driver_name': '0', 'dri ver_number': '0', 'lr_number': 0, 'vehicle_number': '0', 'freight_charges': 0, 'vehicle_type': 'Part Load', 'transport_by': <Vendor: BlaBla>, 'expected_delivery': datetime.date(2020, 2, 13), 'remarks': None} How can I get the dictionary of product with their quantity ? Expected output is: {'132': 273, '231': 273, '213': 325, '216': 325, '564': 260} What I am doing right now is this: products = [] quantity = [] products.append(form.cleaned_data["product1"]) products.append(form.cleaned_data["product2"]) products.append(form.cleaned_data["product3"]) products.append(form.cleaned_data["product4"]) products.append(form.cleaned_data["product5"]) products.append(form.cleaned_data["product6"]) products.append(form.cleaned_data["product7"]) products.append(form.cleaned_data["product8"]) for i in products: if i == None: products.remove(i) quantity.append(form.cleaned_data["product1_quantity"]) quantity.append(form.cleaned_data["product2_quantity"]) quantity.append(form.cleaned_data["product3_quantity"]) quantity.append(form.cleaned_data["product4_quantity"]) quantity.append(form.cleaned_data["product5_quantity"]) quantity.append(form.cleaned_data["product6_quantity"]) quantity.append(form.cleaned_data["product7_quantity"]) quantity.append(form.cleaned_data["product8_quantity"]) for i in quantity: if i == None: quantity.remove(i) prod_quant = dict(zip(products,quantity)) print("prod_quant is ", prod_quant) which outputs as: prod_quant is {'132': 273, '231': 273, '213': 325, '216': 325, '564': 260, None: None} Also why is "None" not removed from both the lists?