Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - expected type pk, received str [Many to many]
I have a webapp where we can create communities with django as a backend, but when i try to send a POST to create a community, I get: community_configuration: ["Incorrect type. Expected pk value, received str."] My POST: { title: knkn kn .k jbjnmn, logo: [object File], is_active: true, description: test, welcome_message: Welcome message, org_id: 114, community_configuration: About us,Community news,FAQs,Supporters,Resources, } Here are my serializers: class MicroConfigurationSerializer(serializers.ModelSerializer): class Meta: model = MicroConfiguration fields = [ 'name', ] def to_representation(self, instance): return instance.name class CommunityConfigurationSerializer(serializers.ModelSerializer): micro_configurations = MicroConfigurationSerializer(many=True, read_only=True) class Meta: model = CommunityConfiguration fields = '__all__' class CommunitySerializer(serializers.ModelSerializer): logo = serializers.SerializerMethodField() organisation = serializers.SerializerMethodField() community_configuration = CommunityConfigurationSerializer() class Meta: model = Community fields = ( ... etcetc ... ) Heres my model: class MicroConfiguration(core_models.BaseModel): name = models.CharField(max_length=32, unique=True) permissions = models.ManyToManyField(Permission) def __str__(self): return self.name class CommunityConfiguration(core_models.BaseModel): name = models.CharField(max_length=32) micro_configurations = models.ManyToManyField(MicroConfiguration) permission_group = models.ForeignKey( Group, on_delete=models.SET_NULL, null=True ) def __str__(self): return self.name class Community(core_models.BaseModel): accounts = models.ManyToManyField( settings.AUTH_USER_MODEL, through='associates.AccountCommunity', through_fields=('community', 'account') ) goals = models.ManyToManyField(Goal, through='associates.CommunityGoal') type = models.ManyToManyField(CommunityType, through='CommunityAttribute') communities = models.ManyToManyField( 'self', through='associates.CommunityCommunity', symmetrical=False, ) crossposts = models.ManyToManyField( Action, through='activities.CommunityCrosspost', through_fields=('community', 'action'), related_name='communities', ) title = models.CharField(max_length=64) logo = models.ImageField(null=True, blank=True) intro_media = models.ForeignKey( 'associates.MediaStore', null=True, … -
django - prefetch a specific item of a one-to-many relationship
Let's say I have the following simple models. One BlogPost can have multiple BlogPostImages. The BlogPostImages have a field which specifies the order of the images. The image with order=1 is defined as the preview image My goal: For a given queryset of BlogPosts (with various filters applied) I want to prefetch the corresponding preview images (i.e. order=1) from django.db import models class BlogPost(models.Model): name = models.CharField(max_length=50) class BlogPostImage(models.Model): image = models.ImageField() order = models.IntegerField() blogpost = models.ForeignKey( BlogPost, related_name="images", on_delete=models.CASCADE, ) First attempt: Prefetch all images results = BlogPost.objects.filter(...).prefetch_related("images").all() for result in results: # 1.1 Triggers query for each blogpost preview_image = result.images.filter(order=1) # 1.2 Prefetch works, no extra query, but seems inefficient to needlessly iterate over all images for image in result.images.all(): if image.order == 1: preview_image = image Second attempt: Prefetch only the preview image sq = (BlogPostImage.objects .filter(blogpost=models.OuterRef('pk'), order=1) .values("image") ) results = (BlogPost.objects.filter(...) .annotate(_preview_image=models.Subquery(sq, output_field=models.CharField())) ) for result in results: # 2.1 No extra query, but only the image name preview_image = result._preview_image How can I prefetch the preview image and let the database do the work? -
I need help in the cmd django [duplicate]
so i was working in a to do list website using Django .. i saw this tutorial in YouTube so for the setup he used command prompt for setup i already downloaded Django Downloads (they choose desktop but i wanna downloads >Downloads>django-admin start project todo_list and when i press enter it says 'Django admin' is not recognized as an internal or external command -
Django and NGINX: How to serve protected media files to internal viewer?
currently I protect my media files against unauthorized access like described e.g. here with the following configuration: Media files are located in /home/mysite/dproject/media/ In the nginx configuration the location to the media files is set like this: ... location /protected/ { internal; alias ../mysite/dproject/media/; } ... In urls.py I redirect requests to /media/ to an access denied view: urlpatterns = [ ... re_path(r'^media/', login_required(PermissiondeniedView.as_view()), name='directmediaaccessdenied') ] In settings.py the paths MEDIA_URL and MEDIA_ROOT are set: MEDIA_ROOT = str(PROJ_DIR('media')) MEDIA_URL = '/media/' To serve files for download, I use the following code in my views: response = HttpResponse() path = os.path.normcase( '/protected/' + filepath ) del response['Content-Type'] response['Content-Disposition'] = 'attachment; filename="%s"' % path response['X-Accel-Redirect'] = path return response So far everything works as expected, but I am not able to provide the data to embedded PDF or 3D viewers. For example I use a viewer to show 3D files (source taken from here). The path to the file is passed with a hash parameter, so a valid URL to the view with the embedded viewer looks like this: https://mysite.mydomain.com/3Dview/#model=/media/path/to/file.ext With the configuration described above, the viewer fails to load the file. The viewer works when I change the nginx config to: … -
how can i set the id of product to their own group?
Problem The problem I'm facing is that i have a same products with different descriptions, so i had to group them in a dropdown respectively. Now when i change the value in the dropdown of the product, it changes the values in only the first product retrieved. The code and the screenshot of the issues are attached below. Code <script> $(document).on("change", '.tranactionID', function (event) { event.preventDefault(); $('#id_price').text($(this).children(":selected").attr("price")); $('#id_sale_price').text($(this).children(":selected").attr("sale_price")); let id = $('#ItemID').find(":selected").attr('transID'); console.log('Id : ',id) let Url = `{% url 'cart:cart_add' 0 %}`.replace(0,id); $('#transactionIDValue').attr('action', Url); let formAction = $('#transactionIDValue').attr('action') let formAction2 = $('#transactionIDValue').prop('action') console.log('form action relative url : ',formAction) console.log('form action full url : ',formAction2) }); </script> {% regroup transaction by productID as ProductList %} {% for productID in ProductList %} <div class="col-sm-3" id="productID" > <div class="product"> <a href="{% url 'main:product-detail' productID.grouper.id %}" class="img-prod"><img class="img-fluid" src={{productID.grouper.product_image.url}} alt="" height="200px"> <span class="status" id="discount">%</span> <div class="overlay"></div> </a> <div class="text py-3 pb-4 px-3 text-center"> <h3><a href="#">{{productID.grouper}}</a></h3> <div class="d-flex"> <div class="pricing"> <p class="price"><span class="mr-2 price-dc" id='id_price'>Rs. </span><span class="price-sale" id='id_sale_price'>Rs. </span></p> </div> </div> <select class="tranactionID" id="ItemID" style="width: 250px;"> <option value="none" selected disabled hidden> Select an Option </option> {% for val in productID.list %} <option transID={{val.id}} price={{val.Price}} sale_price={{val.get_sale}} class="price_value" >{{val.AUID}} - {{val.Description}}</option> {% endfor %} </select> <!-- … -
Getting authentication error even after login in Django rest framework authentication?
my models.py from django.db import models from django.contrib.auth.models import AbstractUser class User_model(AbstractUser): user_type = models.CharField(max_length=2, choices=(("MN", "Mentor"), ("NM", "NormalUser"))) my serializers.py from rest_framework import serializers from rest_framework_jwt.settings import api_settings from django.contrib.auth.models import User from .models import User_model class UserSerializer(serializers.ModelSerializer): class Meta: model = User_model fields = ('username',) class UserSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class Meta: model = User_model fields = ('token', 'username', 'password') views.py from django.shortcuts import render Create your views here. from django.http import HttpResponseRedirect from django.contrib.auth.models import User from rest_framework import permissions, status from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.views import APIView from .serializers import UserSerializer, UserSerializerWithToken from rest_framework import mixins from rest_framework.generics import GenericAPIView @api_view(['GET']) def current_user(request): """ Determine the current user by their token, and return their data """ serializer = UserSerializer(request.user) return Response(serializer.data) class UserList(mixins.CreateModelMixin, GenericAPIView): """ Create a new user. It's called 'UserList' because normally we'd have a get method here too, for retrieving a list of all User objects. """ permission_classes = … -
Can one override the boolean icons in the django admin while using django suit?
Is there any way I can override the default behaviour of django's icon display? Am using django suit, and for it to work with s3 bucket I had to disable admin default statics. But now on the boolean part of the tables, it is returning an image placeholder with the alt text which is True or False. I just wanted to completely remove that icon and it stays with just True and False. Hope my question was clear -
Can't reach AWS EC2 hosted website with Django app
In EC2 Console everything is working correctly, instance is launching properly and in the console there were no errors but I can't open the website and get ERR_CONNECTION_TIMED_OUT error. A week ago I was able to connect to the website but now I created a new instance and it didn't work. I'm using Django with Docker and Nginx proxy. The issue might be connected with EC2 because as I said previously I've launched an instance and it worked properly. Here's the output: app_1 | Waiting for database... app_1 | Database unavailable, waiting 1 second... app_1 | Database available! app_1 | app_1 | 128 static files copied to '/vol/web/static'. app_1 | Operations to perform: app_1 | Apply all migrations: admin, auth, contenttypes, core, sessions app_1 | Running migrations: app_1 | Applying contenttypes.0001_initial... OK app_1 | Applying auth.0001_initial... OK app_1 | Applying admin.0001_initial... OK app_1 | Applying admin.0002_logentry_remove_auto_add... OK app_1 | Applying admin.0003_logentry_add_action_flag_choices... OK app_1 | Applying contenttypes.0002_remove_content_type_name... OK app_1 | Applying auth.0002_alter_permission_name_max_length... OK app_1 | Applying auth.0003_alter_user_email_max_length... OK app_1 | Applying auth.0004_alter_user_username_opts... OK app_1 | Applying auth.0005_alter_user_last_login_null... OK app_1 | Applying auth.0006_require_contenttypes_0002... OK app_1 | Applying auth.0007_alter_validators_add_error_messages... OK app_1 | Applying auth.0008_alter_user_username_max_length... OK app_1 | Applying auth.0009_alter_user_last_name_max_length... OK app_1 | Applying … -
How to combine 'blocktanslate' with 'humanize' tag in templates?
blocktranslate allows me to display a localized plural, whereas humanize allows me to display a grouped-by-hundred number. Each of them works when used independently but I'd like to have both in the same time. I've tried: (words_number is the integer sent by the view) {% load humanize %} {% blocktranslate count counter=words_number %} 1 word {% plural %} {{ counter|intcomma }} words {% endblocktranslate %} But it displays: words (empty space where the number should be) -
DJANGO Data update problem. No Error Code
I want to update the data I have determined in the database by pulling it with post. However, it is not updated. views.py def bilgilerim_guncel(request): if(request.method=='POST'): name_surname= request.POST['name_surname'] mobile_number= request.POST['mobile_number'] age= request.POST['age'] length= request.POST['length'] weight= request.POST['weight'] foot= request.POST['foot'] position= request.POST['position'] players.objects.filter(user_id=user_id).update(name_surname=name_surname,mobile_number=mobile_number,age=age,foot=foot,length=length,position=position,weight=weight) return render(request, 'profil/bilgilerim.html') players_models.py class players(models.Model): name_surname=models.CharField(max_length=18,null=False,blank=False) mobile_number=models.IntegerField(null=False,blank=False) player_status=models.IntegerField(null=True,blank=True,default=0) team_id=models.IntegerField(null=True,blank=True,default=0) photo=models.ImageField(null=True,blank=True,default='resim-yok.jpg') awards=models.IntegerField(null=True,blank=True) dogecoin=models.IntegerField(null=True,blank=True) age=models.IntegerField(null=False,blank=False) foot=models.CharField(max_length=10,null=False,blank=False) length=models.CharField(max_length=4,null=False,blank=False) weight=models.IntegerField(null=False,blank=False) red_card=models.IntegerField(null=True,blank=True,default=0) position=models.CharField(max_length=2,null=False,blank=False) form_points=models.CharField(max_length=3,null=True,blank=True) user=models.ForeignKey(User,on_delete=models.CASCADE) -
Vs code break point does not not stop at Python-Django API TestCase
Normally, debugging is just working fine with Container. I am spinning up my container at port 8000 and attaching the debugging port which is 3000 to it. But, when I hit my rest_api, although it stops from Swagger when it comes to being hit by TestCase debugger does not stop. I could not figure out the reason. -
How to modify and set rules for fields values in django models?
I need to modify the field values of a Django model just like in the following myfunction but when I tried something like this I got nothing changed also i tride __init__ instead of myfunction and I tride save() but nothing worked. class AllDataStrecture(models.Model): name = models.CharField(max_length=30,blank=True,null=True) codename = models.CharField(max_length=30, blank=True, null=True) content_type =models.OneToOneField(ContentType,on_delete=models.DO_NOTHING,null=True) def create_values(self): #also here I am trying to create values for in Permission.objects.all(): self.name = i.name self.content_type = i.content_type self.codename = i.codename def myfunction(self): if 'Can view' in self.name: self.name = self.name.replace('Can view','') if 'Can change' in self.name: self.delete() my Goal is to create a model for an automation app, in which user can select a model name and say if this model name changed then do this .... what I need here is to use Permission instead of models.Model and override it in which I delete the word Can view, or Can change and keep only the value change modelanem -
How to exclude request with {format} drf-yasg?
everyone. I'm writing docs for my api on drf with using drf-yasing. And each of my requests has a copy with {format}. How i can delete that? screenshot my problem For example my easy view: @swagger_auto_schema(method='GET', manual_parameters=[params_id]) @api_view(['GET']) def get_service_history(request): service = Service.objects.get(id=request.GET['id']) ser = ServiceHistorySerializer(service.service_history.all(), many=True) return Response(ser.data) Url: path('deleted_service/', views.deleted_service) ps sorry for my english :) -
return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such column: blog_category.parent_id
enter image description here enter image description herem4I.jpg -
Deploying Django + Vuejs in containers (AWS Elastic Beanstalk)
I'm developing an app with Django and Vuejs and the time has come to test deployment related things. My app will be deployed several times (1 instance per future customer) so I'd like to use containers for faster deployments and removal of virtual machine maintenances. The thing is : I do not now how to build the vuejs part in production. The Django backend is supposed to serve the bundle assets and, while I see on the AWS documentation that I can migrate, collect static files,... a Django application when the container starts, I do not know when/where I'm supposed to build the vuejs part in order to let Django collect the built things. Can someone help me on this ? When/where/how should I build the vuejs part ? Thanks in advance for your help. If more information is needed I will edit this post. -
Django how to get all the column names from the given sql table (model.py)
I am trying to fetch all the columns from the given SQL table in Django (model.py). I found most of the tutorials discussing getting a specific column using its column name. In my case, I can expect unknown columns in the future and I want to see them in the Django dashboard. Is there any possible way to get all the column names from the given table without giving any column names inside the model.py (Django)? -
Loading Flask app on ubuntu webserver without port number
I am new in web development and trying to load my website on ubuntu web server for the first time. The website is developed with Flask at backend. I loaded the website on local server and it's loading well on 127.0.0.1:5000/. I purchased a droplet on digitalocean.com and uploaded it on ubuntu webserver. It is loading well on 157.245.243.108:5000/. I purchased domain name from godaddy.com. The problem is that website is loading well with ip address (157.245.243.108) along with 5000 port. The godaddy DNS does not accept port value. It only asks for ip address. When I upload ip address only (without port) it only loads apache2 server page. The question is: How to load website to IP address only without port number? I am willing to share my code if required. -
Dynamic dropdown base on other input fields in django form
This is my model: class Location(BaseModel): value = models.CharField(max_length=255) class Category(BaseModel): location = models.ForeignKey( Location, on_delete=models.CASCADE, related_name="categories" ) name = models.CharField(max_length=255) class Food(BaseModel): category = models.ForeignKey( Category, on_delete=models.CASCADE, related_name="foods" ) name = models.CharField(max_length=255) Now in my food creation form, I have to select first a Location from a dropdown and then the next dropdown will be the categories under the selected Location. Can this be done in forms.py? This is my forms.py now. class FoodForm(NoFormTagMixin, forms.ModelForm): location = forms.ModelChoiceField( queryset=Location.objects.all(), required=True ) class Meta: model = Food fields = ( "name", "location", "category", ) -
What's the best way to approach relation does not exist error?
I'm getting a ProgrammingError relation does not exist for my site. I recently made changes to Postgres. I'm not even sure what would be the best thing to share to help someone understand the issue. Please let me know if you are familiar with this issue. I have seen a lot of problems with this on Stack Overflow. -
How to submit the same form multiple times all at once with the same submit button
I am still exploring and learning python and django, and I'm also working on some projects as well. I am currently building a student management system, but I failed to continue since I can't make my duplicate form accept marks input of multiple students. Here's my code! In my forms.py class AdvancedMathsForm(forms.ModelForm): class Meta: model = ResultsALevel fields = ('student_name', 'advanced_maths_1', 'advanced_maths_2',) Then here's my models.py class ResultsALevel(models.Model): objects = models.Manager() student_name = models.ForeignKey(AdvancedStudents, on_delete=models.CASCADE, related_name='a_level_student') title = models.OneToOneField(ExamTitle, on_delete=models.CASCADE, null=True) accountancy = models.CharField(max_length=4, default=None, blank=True, null=True) advanced_maths_1 = models.CharField(max_length=4, default=None, blank=True, null=True) advanced_maths_2 = models.CharField(max_length=4, default=None, blank=True, null=True) Here's my views.py class MarksEntryView(LoginRequiredMixin): def form_5_entry_maths_view(self, request): student_first_name = request.POST.get('first_name') student_middle_name = request.POST.get('middle_name') student_last_name = request.POST.get('last_name') maths_1_marks = request.POST.get('maths_paper_1') maths_2_marks = request.POST.get('maths_paper_2') print(f"{student_first_name}, {maths_1_marks}, {maths_2_marks}") for student_first in student_first_name: print(student_first) current_teacher = User.objects.get(email=request.user.email) logged_school = current_teacher.school_number students_involved = User.objects.get(school_number=logged_school).teacher.all() data_taken = ResultsALevel(student_name=None, advanced_maths_1=maths_1_marks, advanced_maths_2=maths_2_marks) data_taken.save() context = {'students': students_involved} return render(request, 'analyzer/marks_entry/marks_entry_page.html', context) And here's my html file ''' {% extends 'analyzer/layouts/base.html' %} {% block title %} Page User {% endblock %} {% block stylesheets %}{% endblock stylesheets %} {% block content %} {% load static %} <div class="row"> <div class="col-md-12"> <div class="card "> <div class="card-header"> <h4 class="card-title">Form 5 Students</h4> … -
Django Listing in Page Issue, "Data Not Appearing"
I ran into the problem that no results were listed when pulling a processed data into my SQlite class database. However, I did not encounter an error code. Related pages will be a page where each member will see their profile page and information. I want the data to be pulled according to the column I defined named user_id other than id. views.py def bilgilerim(request,id): bilgilerim_cek=players.objects.get(user_id=id) context={ 'bilgiler': bilgilerim_cek, 'bilgitum': players.objects.filter(user_id=id), } return render(request,'profil/bilgilerim.html', context) bilgilerim.html {% for bilgilerim_x in players %} {{ bilgilerim_x }} <div class="TopInfoStatistic w-100"> <p class="text-start w-75 float-start "><img class="m-0 p-0" src="../img/teams/{{ bilgilerim_x.team_id }}.png" alt="Generic placeholder image" style="width: 15px; height: 15px;"><strong class="text-dark">Dumlupınar S.K</strong></p> <p class="text-end w-25 float-end align-middle">{{ bilgilerim_x.dogecoin }}<img class="align-content-center" src="../img/icon/dogecoin.svg" style="width: 14px; height: 14px;"></p> </div> <div class="row w-100 InfoStatisticScore m-0 mb-3"> <div class="w-25 float-start m-0 p-0 pe-3" data-bs-toggle="modal" data-bs-target="#profilphoto"> <img class="m-0 p-0 border rounded-3 border-warning" src="{{bilgilerim_x.photo}}" alt="Generic placeholder image" style="width: 90px; height: 90px;"> </div> <div class="w-75 m-0 p-0"> <p class="w-100 m-0 p-0 ps-3" style="font-size: 20px; font-weight: 500;" data-bs-toggle="modal" data-bs-target="#namesurname">{{bilgilerim_x.name_surname }}</p> <p class="w-100 m-0 p-0 ps-3" style="font-size: 16px; font-weight: 500;" data-bs-toggle="modal" data-bs-target="#mobilenumber"> {{ bilgilerim_x.mobile_number}}</p> <p class="w-100 m-0 p-0 ps-3" style="font-size: 14px;" data-bs-toggle="modal" data-bs-target="#ageheightweight">Yaş: {{ bilgilerim_x.age }} - Boy: {{ bilgilerim_x.length }} - Kilo: {{ bilgilerim_x.weight … -
Bypass validator for title in model in UpdateView - Django
Heads up: this is pretty complicated to wrap your head around - in took me 30 minutes just to write this question Hi everyone, I am created a replica of stackoverflow. I am using a CreateView to allow them to create questions. CreateView: class CreateQuestionView(LoginRequiredMixin, CreateView): model = Question template_name = 'questions/questions-part/ask-a-question.html' fields = ['title', 'content', 'tags'] As you can see, it is using the Question model. Question: class Question(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=120, validators=[is_unique_title]) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) num_of_ans = models.IntegerField(default=0) num_of_votes = models.IntegerField(default=0) tags = models.CharField(max_length=30) I have also put a validator in place for the title, so that you can't use a already-used title. def is_unique_title(value): titles = [i.title for i in Question.objects.all()] if value in titles: raise ValidationError(gettext_lazy('%(value)s is already taken'), params={'value': value},) I have put an UpdateView to update the post. class UpdateQuestionView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Question template_name = 'questions/questions-part/question-update.html' fields = ['title', 'content', 'tags'] context_object_name = 'question' success_url = reverse_lazy('list-questions') def test_func(self): post = get_object_or_404(Question, id=self.kwargs['pk']) if post.author == self.request.user: return True return False Now, my problem is this. When I update a question, and I don't change the title, django thinks that I am using a title … -
How to fix "Facebook has detected MySite isn't using a secure connection to transfer information" in social-auth-app-django?
I have no idea why I'm getting this error, I'm all ears to hear from you. Facebook has detected MySite isn't using a secure connection to transfer information -
View the scheduled tasks of celery in Django
I am scheduling some tasks with apply_async() providing the countdown for the task. Once the tasks executes I can view the state and logs with django-celery-results's task_results model. Now, I know all the scheduled tasks are added to the message queue from where I should be able to retrieve the scheduled tasks that haven't executed yet. But is there any other way to view them with state/logs etc. Or will I need to create a model similar to task_results andimplement the feature myself. -
Django Index Error: List Index out of Range using try catch
How do I throw in a try catch exception if there is no data within field student? I haven't put any data inside student for debugging purposes and I just want it to say "No Data found" or "You have no books issued" Here is my views.py: def viewissuedbookbystudent(request): student=models.StudentExtra.objects.filter(user_id=request.user.id) issuedbook=models.IssuedBook.objects.filter(enrollment=student[0].enrollment) li1=[] li2=[] for ib in issuedbook: books=models.Book.objects.filter(isbn=ib.isbn) for book in books: t=(request.user,student[0].enrollment,student[0].branch,book.name,book.author) li1.append(t) issdate=str(ib.issuedate.day)+'-'+str(ib.issuedate.month)+'-'+str(ib.issuedate.year) expdate=str(ib.expirydate.day)+'-'+str(ib.expirydate.month)+'-'+str(ib.expirydate.year) #fine calculation days=(date.today()-ib.issuedate) print(date.today()) d=days.days fine=0 if d>15: day=d-15 fine=day*10 t=(issdate,expdate,fine) li2.append(t) context={'li1':li1,'li2':li2} return render(request,'library/viewissuedbookbystudent.html',context) I get this error every time I run it and I know it's because of no data within student field: IndexError at /viewissuedbookbystudent list index out of range Request Method: GET Request URL: http://127.0.0.1:8000/viewissuedbookbystudent Django Version: 3.2.4 Exception Type: IndexError Exception Value: list index out of range Exception Location: C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py, line 318, in __getitem__ Python Executable: C:\Users\Admin\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.4 Python Path: ['E:\\C drive\\Users\\Admin\\PycharmProjects\\librarymanagement-master', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\Admin\\AppData\\Roaming\\Python\\Python39\\site-packages', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages' Can I fix it using a try catch? If yes, how?