Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
convert html form data to pdf in Django
How can I export my html form to pdf and show it in pdf form on button click My form: <form> {% for a in test %} <div class="form-group col-md-4"> <label>{{a}}</label> <div class="input-group mb-3"> <input aria-label="" value="{{ a|get_at_index:forloop.counter0 }}" readonly> <div class="input-group-append"> <span class="input-group-text">gm</span> </div> </div> </div> {% endfor %} ...... </form> I don't want to convert whole html to pdf, just the form. How can I export the form after getting data to pdf and show it on button click ? Is it possible to get pdf in form of table i.e. row and column ? -
How to log database queries in Django during exception?
I would like to log the last query to the database when an exception occurs. Obviously DEBUG = False. The below code does not work, connection.queries returns []. try: MyModel2.objects.all() MyModel2.objects.all() Boom except: from django.db import connection logger.exception("SQL: %s", connection.queries) Output: "SQL: []" -
Django admin auto field with prefix
I have a auto field that creates a ticket number. however just the number alone looks very un professional. how would I add "#0000" in front of the auto field and every time the number goes above 1 or two digits the "0" needs to be filled . Hope this makes sense . Ticket_Number = models.AutoField(primary_key=True,) -
How to store HttpResponse which returns a pdf file inside the Django application folder internally ,
def file_pdf_to_merge(id): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = file_name(id) pdf=SimpleDocTemplate(response) flow_obj=flow_obj_for_display(id) pdf.build(flow_obj) return response Code works perfectly find it returns pdf file which can be downloaded in browser upon clicking a button , I want to store the file locally in the application within same view how can I do it. -
django-xero==0.0.3
Is there any version of django-xero that is compatible with Django 3+.l am getting this error. django-xero 0.0.3 requires Django<3.0,>=2.2.3, but you'll have django 3.1.3 which is incompatible -
django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK
Why do I have the following problem when running tests? Tried everything already, nothing seems to work django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Everything is working, but the testing. -
Django Dynamic Url Error in href attribute
My Error is here Hi i wanna show profile page with articles/profile/int:author_id When i add profile page with href attribute but other links doesn't work on navbar. by the way if i remove articles:profile article.author_id on navbar.html. All links works. can u help me thank you for attention. views.py def profile(request,author_id): article = get_object_or_404(Article,author_id = author_id) context = { "article":article, } form = ArticleForm(request.POST or None,request.FILES or None) if form.is_valid(): article = form.save(commit=False) article.author = request.user article.save() messages.success(request,"Dosya Yüklendi") return redirect("article:dashboard") return render(request,"profile.html",{"article":article,'form':form}) navbar.html YB Blog <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="{% url 'about' %}">Hakkımızda</a> </li> <li class="nav-item active"> <a class="nav-link" href="{% url 'article:articles' %}">Makaleler</a> </li> </ul> <ul class="navbar-nav ml-auto"> {% if request.user.is_authenticated %} <li class="nav-item active"> <a class="nav-link" href="{% url 'article:dashboard' %}">Makale Ekle</a> </li> <li class="nav-item active"> <a class="nav-link" href="{% url 'article:profile' article.author_id %}">Makale Ekle</a> </li> <li class="nav-item active"> <a class="nav-link" href="{% url 'user:logout' %}">Çıkış Yap</a> {% else %} <li class="nav-item active"> <a class="nav-link" href="{% url 'user:login' %}">Giriş Yap</a> </li> {% endif %} <li class="nav-item active"> <a class="nav-link" href="{% url 'user:register' %}">Kayıt Ol</a> </li> </ul> </div> </nav> urls.py from django.contrib import admin from django.urls import path from . import views app_name = … -
django regroup template on table
i have following setup in my project, in models.py/ class ShareMemberSaving(models.Model): MONTHS = ( ('बैशाख','बैशाख'), ('जेष्ठ','जेष्ठ'), ('असार','असार'), ('साउन','साउन'), ('भदौ','भदौ'), ('असोज','असोज'), ('कार्तिक','कार्तिक'), ('मङ्सिर','मङ्सिर'), ('पौष','पौष'), ('माघ','माघ'), ('फाल्गुन','फाल्गुन'), ('चैत्र','चैत्र') ) YEAR_CHOICES = [] for r in range(2073,3000): YEAR_CHOICES.append((r,r)) name = models.ForeignKey(ShareMember,on_delete=models.DO_NOTHING) year = models.IntegerField(('year'), choices=YEAR_CHOICES) month = models.CharField(max_length=50,choices=MONTHS) amount = models.IntegerField(default=0) class Meta: unique_together = [('name','year','month')] in views.py def shareMember(request,pk): member = get_object_or_404(ShareMember,id = pk) saving = member.sharemembersaving_set.all() context = { 'member':member, 'saving':saving, } return render(request,'sahakarihome/sharemember.html',context) **in template ** <table> <thead> <tr> <th>आर्थिक बर्ष</th> <th>बैशाख</th> <th>जेष्ठ</th> <th>असार</th> <th>साउन</th> <th>भाद्र</th> <th>असोज</th> <th>कार्तीक</th> <th>मङ्सिर</th> <th>पौष</th> <th>माघ</th> <th>फाल्गुन</th> <th>चैत्र</th> <th>जम्मा</th> <th>जम्मा ब्याज</th> <th>चक्रे ब्याज</th> <th>0.50%</th> <th>कैफियत</th> </tr> </thead> {% regroup saving|dictsort:"year" by year as year_list %} <tbody> {% for year in year_list %} <tr> <td>{{year.grouper}}</td> {% for item in year.list %} <td>{{ item.amount }}</td> {% endfor %} <td>8650</td> </tr> {% endfor %} </tbody> </table> the problem is i want to render my data according to month choice in the table and showing error if user attempts to enter amount by escaping any month ,also i want to fix the table columns after the months choices for eg total after all 12 months .how can i solve this? -
Celery waking up in 5.00 seconds
Why Celery beat is always waking up in 5s while I don't have any enabled task? Is there a way to remove/change this period from 5s to 10m for example? Logs: web_1 | [2021-03-03 09:43:11,936: INFO/Beat] DatabaseScheduler: Schedule changed. web_1 | [2021-03-03 09:43:11,936: DEBUG/Beat] Writing entries... web_1 | [2021-03-03 09:43:11,969: DEBUG/Beat] DatabaseScheduler: Fetching database schedule web_1 | [2021-03-03 09:43:11,974: DEBUG/Beat] Current schedule: web_1 | web_1 | [2021-03-03 09:43:12,013: DEBUG/Beat] beat: Waking up in 5.00 seconds. web_1 | [2021-03-03 09:43:17,025: DEBUG/Beat] beat: Waking up in 5.00 seconds. web_1 | [2021-03-03 09:43:22,033: DEBUG/Beat] beat: Waking up in 5.00 seconds. web_1 | [2021-03-03 09:43:27,044: DEBUG/Beat] beat: Waking up in 5.00 seconds. web_1 | [2021-03-03 09:43:32,059: DEBUG/Beat] beat: Waking up in 5.00 seconds. web_1 | [2021-03-03 09:43:37,068: DEBUG/Beat] beat: Waking up in 5.00 seconds. web_1 | [2021-03-03 09:43:42,080: DEBUG/Beat] beat: Waking up in 5.00 seconds. web_1 | [2021-03-03 09:43:47,095: DEBUG/Beat] beat: Waking up in 5.00 seconds. web_1 | [2021-03-03 09:43:52,108: DEBUG/Beat] beat: Waking up in 5.00 seconds. web_1 | [2021-03-03 09:43:57,121: DEBUG/Beat] beat: Waking up in 5.00 seconds. web_1 | [2021-03-03 09:44:02,131: DEBUG/Beat] beat: Waking up in 5.00 seconds. web_1 | [2021-03-03 09:44:07,140: DEBUG/Beat] beat: Waking up in 5.00 seconds. web_1 | [2021-03-03 09:44:12,147: … -
Add contours to a 3D Time-Series Image in Plotly
I have a requirement to add contours for each slice of a 3D Time-series image in Plotly. I tried something similar to below, which shows the image slices in a time series similar to this, however it doesn't show any contours study_uid = request.POST.get('study_uid') img = get_image(study_uid, workspace_path) cntrs = get_contours(study_uid, workspace_path) # create the plotly time series from the 3D Image figure = go.Figure(pex.imshow(ret_img, animation_frame=0, binary_string=True, labels=dict(animation_frame="slice"))) # TRYING TO ADD THE CONTOURS TO THE TIME SERIES IMAGE HERE figure.add_trace(go.Contour(z=contours, showscale=False, contours=dict(coloring='lines'), line_width=2)) figure.update_layout(autosize=True, width=725, height=725) div = opy.plot(figure, auto_open=False, output_type='div', auto_play=False) Here the img and cntrs have the same structure; as in a 3D-image array. Basically each slice of the 3D image can have a different respective contour which is available in the cntrs. What would be the best approach to go about this? Thanks in advance! -
Unit Tests for Token Authentication in Django
I am using Pytest and Factory_boy to create unit tests for my APIs. These API are to be accessed by third-party clients using the generated token from a model named apikey I have used Token Authentication for them to be authenticated and have access to the API. For the Unit Tests, I was still not successful in doing it. factory.py class ApiKeyFactory(DjangoModelFactory): name = factory.LazyFunction(fake.name) key = factory.LazyFunction(fake.name) // I dont know yet how to generate an api-key-like string through lazy function, thats why I just used name for the mean time class Meta: model = models.apikey conftest.py @pytest.fixture def apikey(): return [ ApikeyFactory(), ApikeyFactory(), ApikeyFactory(), ] test.py @pytest.mark.django_db class TestFoodListCreateAPIView: """ Food List API """ url_name = "web:food-list-create" def test_list(self, api_client, apikey, food): """ Should return 200 success """ token = apikey.first() api_client.credentials(HTTP_AUTHORIZATION="Token " + token.key) url = reverse(self.url) response = api_client.get(url_name) assert response.status_code == 200 auth.py class ApiKeyAuthentication(TokenAuthentication): keyword = "Token" def authenticate_credentials(self, key): try: token = Apikey.objects.get(key=key) except ProjectToken.DoesNotExist: raise exceptions.AuthenticationFailed("Invalid Token.") user = User.objects.get(id="1") return (user, token) and my API is just like this class FoodListCreateAPIView(ListCreateAPIView): serializer_class = serializers.FoodSerializer permission_classes = [IsAuthenticated] def get_queryset(self): return models.Food.allitems(self.request.auth.id) Authentication and APIs are already working. I just can't make … -
Django form, reduce nesting in view file code
I have a creative question. There is a render form code from views.py: def post_view(request, template_name='newpost.html'): if request.method != 'POST': form = NewPost() else: form = NewPost(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('index') return render(request, template_name, {'form': form}) Please tell me. How to shorten this code to make it flatter. Thank! -
User select columns when upload xls file in Django
I am trying to create an app, in which user will upload an xls file and then he can show columns by his selection, without saving the data. My function in views.py is below: def Upload_insitu(request): if request.method == 'POST': form = InsituForm(request.POST, request.FILES) if form.is_valid(): insitu_obj = form.instance area = insitu_obj.area insitu = insitu_obj.insitu xl = pd.read_excel(insitu, engine='openpyxl') cols = xl.columns.tolist() data = [] for i in range(len(cols)): data.append(xl.iloc[:,i].to_list()) return render(request,"upload_insitu.html", {'form': form, 'area': area, 'cols': cols, 'data': data}) else: form = InsituForm() return render(request,"upload_insitu.html", {'form': form}) and my html file is below: <body> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{form.area}} {{form.insitu}} <button type="submit">Upload</button> </form> {% if area %} <p>{{area}}</p> <select name="table" method="GET" action="/"> {% for name in cols %} <option value="{{ name }}">{{ name }}</option> {% endfor %} </select> <button type="submit">select</button> {% endif %} </body> As you can see I have created a select box for the columns of the xls file, but I can not get the data of the selected column. -
How to add foreign key in table using existing column without losing data in django with sqlite3?
I want to alter some tables that have IntegerField type into a foreign key without losing any data. so, How can I do that in both sqlite3 and Django when I do makemigrations command? this is models looks like: class Sentences(models.Model): actor_id = models.IntegerField(blank=True, null=True) film_id = models.IntegerField(blank=True, null=True) class Tokens(models.Model): word_id = models.IntegerField(blank=True, null=True) sentence_id = models.IntegerField(blank=True, null=True) class Actors(models.Model): ... class Words(models.Model): ... class Films(models.Model): ... every _id has IntegerField in the first place is referred to the actual id from another table but instead, I want to modify it to become ForeignKey instead of IntegerField how I do that modification? -
I can't run a small script due to Foundation not being recognised
I am a new python programmer and was testing out pyttsx3, I am trying to use nsss. However when I run the following code import pyttsx3 engine=pyttsx3.init('nsss') engine.say ("Top of the morning") # angine=pyttsx3.init() # angine.say("Why hello there") # angine.runAndWait() It says error Foundation module not found, so I installed it with pip install foundation. This installs foundation and django version 1.10.8 which to my understanding is not compatible with python v 3.9. But when I install Django version 3.1.7, that version is not compatible with Foundation. The error logs are below C:\Users\Ahmed_Abdelmuniem\AppData\Local\Programs\Python\Python39\python.exe "C:/Users/Ahmed_Abdelmuniem/PycharmProjects/AI Engine/main.py" Traceback (most recent call last): File "C:\Users\Ahmed_Abdelmuniem\AppData\Local\Programs\Python\Python39\lib\site-packages\pyttsx3\__init__.py", line 20, in init eng = _activeEngines[driverName] File "C:\Users\Ahmed_Abdelmuniem\AppData\Local\Programs\Python\Python39\lib\weakref.py", line 134, in __getitem__ o = self.data[key]() KeyError: 'nsss' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Ahmed_Abdelmuniem\PycharmProjects\AI Engine\main.py", line 3, in <module> engine=pyttsx3.init('nsss') File "C:\Users\Ahmed_Abdelmuniem\AppData\Local\Programs\Python\Python39\lib\site-packages\pyttsx3\__init__.py", line 22, in init eng = Engine(driverName, debug) File "C:\Users\Ahmed_Abdelmuniem\AppData\Local\Programs\Python\Python39\lib\site-packages\pyttsx3\engine.py", line 30, in __init__ self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug) File "C:\Users\Ahmed_Abdelmuniem\AppData\Local\Programs\Python\Python39\lib\site-packages\pyttsx3\driver.py", line 50, in __init__ self._module = importlib.import_module(name) File "C:\Users\Ahmed_Abdelmuniem\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line … -
I am having an Error in Django Search Views
I am trying to create a serach functionality in django. I just wrote the view but i was getting an error with that. I have tried debugging the codes but I don't seems to know where the error is. Error Log File "C:\Users\Habib\Documents\django\FIVERR\Alex_SMS\SMS\core\urls.py", line 2, in <module> from . import views File "C:\Users\Habib\Documents\django\FIVERR\Alex_SMS\SMS\core\views.py", line 37 return render(request, "core/search.html", context) ^ SyntaxError: invalid syntax views.py def search(request): if request.method == 'GET': product_name = request.GET.get('search') try: product = Product.objects.filter(name__icontains=product_name) context = {"product": product} return render(request, "core/search.html", context) else: result = "Sorry there is no product with that name" return render(request, "core/search.html", {"result":result}) -
i want to create form for emojis in django by which user can insert emojis acc to their mood
i want to create a form in which user can only use emojis to fill the field how can i do that models.py class Status(models.Model): user = models.OneToOneField(User ,on_delete=models.CASCADE,) status = models.CharField(max_length=1, default='😀', editable=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_status(sender, instance, created, *args, **kwargs): if created: Status.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_status(sender, instance, **kwargs): instance.status.save() views.py def profile(request, username): if request.method == 'POST': profile_form = Profile_PicForm(request.POST, request.FILES, instance=request.user.profile_pic) banner_form = BannerForm(request.POST, request.FILES, instance=request.user.banner) status_form = StatusForm(request.POST, instance=request.user.status) if profile_form.is_valid(): profile_form.save() return redirect('/@<slug:username>/') else: messages.error(request, 'Please Check The File.') if banner_form.is_valid(): banner_form.save() return redirect('/@<slug:username>/') else: messages.error(request, 'Please Check The File.') if status_form.is_valid(): status_form.save() return redirect('/@<slug:username>/') else: messages.error(request, 'Please Use Emojis Only.') else: profile_form = Profile_PicForm(instance=request.user.profile_pic) banner_form = BannerForm(instance=request.user.banner) status_form = StatusForm(instance=request.user.status) return render(request, 'profile.html', {'profile_form': Profile_PicForm, 'banner_form': BannerForm, 'status_form': StatusForm}) do i user choicefield in place of CharField or is there any other ways to do it something in JavaScript -
How to take specific user logs in Django?
I want to record some user activities in my system. Actually what I want looks very similar to admin logs. I can successfully save admin's logs using a code I found on the internet. There are some important operations in the system. These are; User blocking (is_active = False) DOA table changes (These are called as approvals | doa table in admin logs.) Role change (These are called as register | rank change in admin logs.) Creating a new user (These are called as register | user in admin logs.) All of these operations are doing by users whose role is "Lead". This is a code for admin logs: admin.py @admin.register(LogEntry) class LogEntryAdmin(admin.ModelAdmin): date_hierarchy = 'action_time' list_filter = [ 'user', 'content_type', 'action_flag' ] search_fields = [ 'object_repr', 'change_message' ] list_display = [ 'action_time', 'user', 'content_type', 'object_link', 'action_flag', ] def has_add_permission(self, request): return False def has_change_permission(self, request, obj=None): return False def has_delete_permission(self, request, obj=None): return False def has_view_permission(self, request, obj=None): return request.user.is_superuser def object_link(self, obj): if obj.action_flag == DELETION: link = escape(obj.object_repr) else: ct = obj.content_type link = '<a href="%s">%s</a>' % ( reverse('admin:%s_%s_change' % (ct.app_label, ct.model), args=[obj.object_id]), escape(obj.object_repr), ) return mark_safe(link) object_link.admin_order_field = "object_repr" object_link.short_description = "object" And it is look … -
How to fix cors error if its coming in only one api and not others
I am getting cors error in one of the api in django rest framework. Is there any solution? -
Translate messages in Django
Using django 3.1.7 and Python 3.9, I'm trying to translate messages like this: views.py from django.utils.translation import ugettext as _ messages.success(request, _("File successfully uploaded")) template.html {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> <span style="list-style-type:none;"> {% trans message %} </span> </div> {% endfor %} {% endif %} I, of course, have .po and .mo files build. Translations are working fine in other context. But in that particular case, I got this error message: AttributeError 'Message' object has no attribute 'replace' I am not quite sure to understand... -
Django Rest framework getting all foreign key data in parent object
I have a family model like below class Family(models.Model): name = models.CharField(max_length=255) address = models.CharField(max_length=500, blank=False) monthly_contribution = models.FloatField(default=0) enabled = models.BooleanField(default=True) def __str__(self): return self.name + f' ({self.address})' I have a Parishioner model like below class Parishioner(models.Model): def _age(self): return date.today().year - self.dob.year """Parishioner model""" id = models.CharField(primary_key=True, max_length=1000, default=get_next_parishoner_id) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) dob = models.DateField() age = property(_age) GENDER_CHOICES = [("Male", "Male"), ("Female", "Female"), ("Other", "Other")] gender = models.CharField(max_length=10, choices=GENDER_CHOICES) address = models.CharField(max_length=1000) fathers_name = models.CharField(max_length=500) mothers_name = models.CharField(max_length=500) baptism_certificate = models.ImageField(null=True, upload_to=upload_image) marriage_certificate = models.ImageField(null=True, upload_to=upload_image) family = models.ForeignKey(Family, null=True, on_delete=models.PROTECT) role = models.CharField(null=True, max_length=255) def __str__(self): return self.first_name + " " + self.last_name This is my Family viewset class FamilyViewSet(viewsets.ModelViewSet): queryset = Family.objects.all() serializer_class = FamilySerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) This is my Parishioner viewset class ParishionerViewSet(viewsets.ModelViewSet): queryset = Parishioner.objects.all() serializer_class = serializers.ParishionerSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) This is my Family serializer class FamilySerializer(serializers.ModelSerializer): members = ParishionerSerializer(read_only=True, many=True) class Meta: model = Family fields = ('id', 'name', 'address', 'monthly_contribution','members', 'enabled') read_only_fields = ('id','members',) This is my Parishioner serializer class ParishionerSerializer(serializers.ModelSerializer): class Meta: model = Parishioner fields = ('id','first_name', 'last_name', 'dob', 'age', 'gender', 'address', 'fathers_name', 'mothers_name', 'baptism_certificate', 'marriage_certificate', 'family', 'role') … -
How to filter Django ManyToManyField based upon exact queryset?
How do we filter django model instances based upon the exact values in the ManyToManyField. Consider the following example: Say, we have two models: class Author(models.Model): name=models.CharField(max_length=200) class Book(models.Model): authors=models.ManyToManyField(Author) I want to filter all the books, which only have a given author of given ids. If I am looking to filter the queryset say by author ids 1, 2, 3. I tried doing this: Book.objects.filter(authors__id__in=[1,2,3]) This doesn't work, since it gives me the list of books that have authors with these ids along with other authors. How to filter books such that the authors are only in these ids -
Is having a nested serializer with multipart/form-data request isn't suported by DRF?
I want to POST a request using form data that has a nested object and a file and I can't find a solution to my problem. Does anyone have an idea if it's even possible or I have to write something custom? -
How to fetch latest entry in a related table while making sure the query is optimized
I have two models in consideration. RV_Offers and RV_Details. Each offer can have multiple details i.e. I have a foreignkey relationship field in RV_Details table. Here is my view: rv_offers_queryset = RV_Offers.objects.all().select_related('vendor').prefetch_related('details') details_queryset = RV_Details.objects.all().select_related('rv_offer') title = Subquery(details_queryset.filter( rv_offer=OuterRef("id"), ).order_by("-created_at").values("original_title")[:1]) offers_queryset = rv_offers_queryset.annotate( title=title).filter(django_query) offers = RVOffersSerializer(offers_queryset, many=True).data return Response({'result': offers}, status=HTTP_200_OK) As can be seen, I am passing the offers queryset to the serializer. Now, here is my serializer: class RVOffersSerializer(serializers.ModelSerializer): details = serializers.SerializerMethodField() vendor = VendorSerializer() def get_details(self, obj): queryset = RV_Details.objects.all().select_related('rv_offer') queryset = queryset.filter(rv_offer=obj.id).latest('created_at') return RVDetailsSerializer(queryset).data class Meta: model = RV_Offers fields = '__all__' If you look at the get_details method, I am trying to fetch the latest detail that belongs to an offer. My problem is, even though I am using select_related to optimize the query, the results are still extremely slow, In fact, I am using django debug toolbar to inspect the query and apparently select_related seems to have no effect. What am I doing wrong or how else can I approach this problem? -
Dictionary not passing to the template django
I'm trying to read a cookie and pass the data into the template but it returns a string /cart on the template. view.py def cart(request): # exception no cookie named 'cart' try: cart = json.loads(request.COOKIES['cart']) except: cart = {} context = { 'data': [], 'cart': cart, } for item in cart: product_detail = ProductImage.objects.select_related( 'product' ).filter(product=item[0], place='Main Product Image') context['data'].append(product_detail) return render(request, 'store/cart.html', context) I've checked whether the cart variable contains data and it does contain a dictionary. Following is the context variable, {'data': [<QuerySet [<ProductImage: Product 1-22>]>], 'cart': {'1': {'unit_price': '980.00', 'quantity': 3}}} when I tried to print the cart in the template using {{ cart }} it returns /cart but the data key contains all the data. So hoping to know what's going on here thanks in advance.