Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Exception Value: no such column: noticia_tb.id
I made a scraping application using scrapy, to scrape the news from a page, I put it to create a sqlite database, and then I made a django api to consume this database and make a link available in json, however when I upload the application from the following error: OperationalError at /news/ no such column: noticia_tb.id So I opened the database file and noticed that the ID was not generated, how do I generate this ID or use it without? follow my moldels.py class NoticiaTb(models.Model): title = models.TextField(blank=True, null=True) subtitulo = models.TextField(blank=True, null=True) url = models.TextField(blank=True, null=True) data = models.TextField(blank=True, null=True) image_url = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'noticia_tb' follow the scrapy project pipeline class ApinoticiaPipeline(object): def __init__(self): self.create_connection() self.create_table() def create_connection(self): self.conn = sqlite3.connect("myapinoticia.db") self.curr = self.conn.cursor() def create_table(self): self.curr.execute("""DROP TABLE IF EXISTS noticia_tb""") self.conn.execute("""create table noticia_tb( title text, subtitulo text, url text, data text, image_url text )""") def process_item(self, item, spider): self.store_db(item) return item def store_db(self, item): self.curr.execute("""insert into noticia_tb values (?,?,?,?,?)""",(str(item['title'][0]),str(item['subtitulo'][0]),str(item['url'][0]),str(item['data'][0]),str(item['image_url'][0]))) self.conn.commit() -
djongo Company with ID “None” doesn’t exist. Perhaps it was deleted?
I couldn't find a solution among similar questions. Using mongosh, the Company objects do exist, but in the admin, they show as object(None) and therefore cannot be edited due to error "Company with ID “None” doesn’t exist. Perhaps it was deleted?". I guess it is about the "id" detection, but can not fix it myself. Question: how to fix the code to make the Company object to be shown correctly, not as None. myproject> db.companies_company.find() [ { _id: ObjectId("6145dd9a8bc9a685b2ae2375"), name: 'company1' }, { _id: ObjectId("6145ddaa8bc9a685b2ae2377"), name: 'company2' } ] models.py: from django.db import models # Create your models here. class Company(models.Model): name = models.CharField(max_length=100, blank=False, null=False, unique=True) admin.py: from django.contrib import admin # Register your models here. from .models import Company @admin.register(Company) class CompanyAdmin(admin.ModelAdmin): pass -
How to download a file from my media root folder to my phone or computer
Anytime i click on the download link of the mp3 files or images, instead of them starting to download but they just start to preview on the browser. I want when i click on the url "http://localhost:8000/s/download_rdr/1/" and the file "http://localhost:8000/s/media/music.mp3" starts downloading but all it does is to start playing in the browser. My views.py class DownloadRdr(TemplateView): def get(self, request, pk, *args, **kwargs): item = Item.objects.get(id=pk) #Return an mp3 return redirect('http://localhost:8000/s/media/music.mp3') -
date field value disappears when changing language Django
i'm using this modelform to save the users info class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = '__all__' widgets = { 'date_of_birth': DateInput(), 'first_name': forms.TextInput(attrs={'placeholder': _('first Name')}), 'address': forms.TextInput(attrs={'placeholder': _('Street')}), } def __init__(self, *args, **kwargs): super(ProfileForm, self).__init__(*args, **kwargs) self.fields['address'].widget.attrs['class'] = 'form-control' self.fields['date_of_birth'].widget.attrs['class'] = 'form-control' self.fields['image'].widget.attrs['class'] = 'form-control p-1' i always use this class which allows me to add a datepicker to the "date of birth" field class DateInput(forms.DateInput): input_type = 'date' it works fine with the English language but when i change the language to french the field stops rendering the value it just keeps showing empty. so in english it looks like this on the same view when i change the language to french it shows like this when i use chrome dev tools i can see that field has a value of the correct date and the console gives a warning message like this 127.0.0.1/:892 The specified value "21/09/2021" does not conform to the required format, "yyyy-MM-dd". I think my problem occurs because the format changes between languages, so is there any way to stop the date format from changing or configure the date input in the form to use one date format on all languages,or any … -
How to handle two SAME form on one page Django views
I pass multiple forms to one template like this, (NOTE THAT address_form and shipping_address_form are same FORM) # views.py class CartListView(generic.ListView): ... def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['companies_json'] = serializers.serialize( "json", Item.objects.all()) address_form = AddressForm() shipping_address_form = AddressForm() order_form = OrderForm() context['address_form'] = address_form context['order_form'] = order_form context['shipping_address_form'] = shipping_address_form return context In my template i have ONE form tag(due to fact that i want only ONE button to submit them) # template.html <form class="form" action="/payment/" method="POST"> {% csrf_token %} {{ address_form }} {{ shipping_address_form }} question is how to handle them in views.py if i do it like below, it selects only LAST form so address_form and shipping_address_form has values from shipping_address_form (FROM TEMPLATE) #views.py def payment_handler(request): if request.method == 'POST': addres_form = AddresForm(request.POST) shipping_addres_form = AddresForm(request.POST) if addres_form.is_valid(): if i print(request.POST) it shows that it has both address_form and shipping_address_form stored in List, how can i select in views.py which one AddresForm shoud check? 'name': ['Test 1', 'test 2'], 'surname': ['frank', 'albertson'] -
How to annotate related object with MAX by some attribute
class Bill number = CharField class Service number = CharField bill = ForeignKey(order, related_name="bill_services") price = IntegerField bills = Bill.objects.prefetch_related('bill_services').annotate(service_number_with_max_price=....) Hello. How can I annotate a service number with max price for each Bill. I want to use it for something like that: {% for bill in bills %} {{ bill.service_number_with_max_price }} {% endfor %} -
Djongo keeps closing and creating new MongoClient DB connections with each request
I'm using djongo to connect my Django REST framework API with my MongoDB cluster, and when logging the requests at DEBUG level, I see that djongo starts every request by closing the existing MongoClient connection, creating a new connection, doing the query, then closing the connection again. 2021-09-18 13:41:34,714 - DEBUG - djongo.base - Existing MongoClient connection closed 2021-09-18 13:41:34,715 - DEBUG - djongo.base - New Database connection 2021-09-18 13:41:34,716 - DEBUG - djongo.sql2mongo.query - sql_command: ... 2021-09-18 13:41:35,340 - DEBUG - djongo.sql2mongo.query - Aggregation query: ... 2021-09-18 13:41:35,343 - DEBUG - djongo.sql2mongo.query - Result: ... 2021-09-18 13:41:35,454 - DEBUG - djongo.base - MongoClient connection closed Why does it close the connection with every request and how can I stop this behavior? It should initiate the DB connection when the web server starts and keep using that connection for all the requests, instead of creating hundreds of connections each second. Relevant codes from djongo/base.py: if self.client_connection is not None: self.client_connection.close() logger.debug('Existing MongoClient connection closed') self.client_connection = Database.connect(db=name, **connection_params) logger.debug('New Database connection') def _close(self): """ Closes the client connection to the database. """ if self.connection: with self.wrap_database_errors: self.connection.client.close() logger.debug('MongoClient connection closed') For the installation and configuration, I've followed the djongo GitHub … -
Django rest framework, returning item status booked or free based on current date/time
I am currently working on a website for my students where it will help them to book some items on the classroom. I am already done with the booking logic and form so no two students are allowed to book the same item at the same time. I would like to create a table for them where it shows the item name and the status of the item based on the current time. So I have a webpage/django view that have a list of all the booking made including the item name, starting date, ending date, and the person who booked the item. So, based on this booking list, I would like to create some logic that will go through this booking list and compare it against the current time/date. In simple words, if the current time/date falls in between the start and end date of a booked item , it should return the value "booked" other wise "free". I am not sure how to achieve this. I brainstormed for days, and search the Internet for some hints but nothing. I would be very thankful if someone helped me. This is my models: class Items(models.Model): ITEMS_CATEGORIES=( ('item-1', 'item-1'), ('item-2', 'item-2'), … -
Proper Celery Monitoring and File-Management with Web-Services
We are working on an Internet and Intranet platform, that serves client-requests over website applications. There are heavy-weight computations on database entries and files. We want to update the state of those computations via push-notification to the client and make changes to files without the risk of race-conditions. The architecture is supposed to run on both, low- scaled one-server environments and high-scaled cluster environments. So far, we are running a Django Webserver with Postgresql, the Python-Library Channels and RabbitMQ as Messagebroker. Once a HTTP-Request from a client arrives in Django, we trigger the task via task.delay() and immediatly return the task_id to the client. The client then opens a websocket to another Django-route and hands over the task_ids he is interested in. Django then polls the state of the task via AsyncResult(task_id).state. Once the state changes, we read the results via AsyncResult(task_id).get and push the task_results to the client. Here a similar sequence diagramm, from another project I found online. Source(18.09.21) Something that is not seen on the diagram, the channels_worker have to fetch the file they are working on from Django. A part of the result is not for the client, but to update the file. Django locks and … -
getting Error running WSGI application NameError: while i deployed my DJango app to pythonanywhere?
Complete error 2021-09-18 10:35:44,065: Error running WSGI application 2021-09-18 10:35:44,068: NameError: name 'get_wsgi_application' is not defined 2021-09-18 10:35:44,068: File "/var/www/dhruv354_pythonanywhere_com_wsgi.py", line 30, in <module> 2021-09-18 10:35:44,068: application = get_wsgi_application() my wsgi.py file import os import sys path = '/home/dhruv354/Django-grocery/' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'ReadingRight.settings' from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise application = DjangoWhiteNoise(get_wsgi_application()) Everything seems fine to me but still it is giving this error, needs help -
How to count total objects in a django model
I am trying to get total number of items in my model which i will be displaying in my base template as a footer. heres my code. VIEW: def showthis(request): count= Item.objects.all().count() context= {'count': count} return render(request, 'waqart/footer.html', context) TEMPLATE: <h1 class="text-4xl md:text-6xl text-gray-700 font-semibold">UX/UI Components {{count}}</h1> -
Django Dynamic Formet form count
I have been working on Django Model Formset, where I have two models 1: Institutional Objectives and 2: Sub Institutional Objectives. I have used the Model formset here. Using the add_more_subobjective button user can multiple sub_institutional_objective forms under one institutional_objective form (I am using Django Dynamic Formset for this, refer here) Problem: When a user adds sub_objective form I want to show him the count of that form, example [As in image: I am getting Subobjective as 1 for all forms image But I want the user to see it like this result_image form.html <form method="post"> {% csrf_token %} <div class="card"> <div class="card-header"> <h4>Add Insititutional Objectives</h4> </div> <div class="form-group" style="margin: 40px;"> {{ form.non_form_errors }} {{ form.as_p }} {{ subobjective.non_form_errors }} <hr> <h4>Sub Objectives</h4> <h6>These are Sub Objectives of this particular IO</h6> {{ subobjective.management_form }} <div class="form-group nested-query-formset"> <h6>Sub Objective {{ count }} </h6> {{ subobjective.as_p }} </div> </div> </div> <div class="mt-3 mb-5"> <button type="submit" class="px-5 btn btn-info">Submit</button> </div> </form> Django Dynamic Fomrset Options: var count = 1; $('.nested-query-formset').formset({ addText: 'Add Another Sub - Objective', deleteText: 'remove', prefix: '{{ subobjective.prefix }}', added: function($row) { count++; console.log(count) }, removed: function($row) { count++; console.log(count) }, }); Any help here is really appreciated. -
How to handle document request in django?
I have three models, Application, Students and University in this, application is connected with both student and university (Students can apply for an university and university can manage these applications). Now i have an scenario in which university will be "Requesting for documents" - by which students will upload documents later. Am just confused how to handle this. How it happens - On application details page there is a button named "Request Document", when university clicks on this - a popup with available documents will be showed, in this they can multiselect the document and submit. And in students side there will be a space where they need to upload all the required documents So now, from the above i have few problems: How to store these on database, as required documents can be varied (can these be stored in a single row with arrays or should i store each row for each documents ? How to show this on students page ? How to validate if the required documents are uploaded ? Please suggest something to do this efficiently ! -
Why bootstrap carousel and django not workig properly?
I am trying to provide bootstrap carousel backend with django.I have written a simple program view which will pass all images to template.But when i run the program i did't get output as expected, all images are rendered adjecent to one other. There was nothing like forward and backward button and all.And i am posting my view and template. Thanks in advance. Hope to here from you soon. View:- def TaggingView(request): queryset = MyImage.objects.filter(is_tagged=False) return render(request, "taggging.html", {'files': queryset}) Template:- <body> <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> {% for file in files %} <div class="carousel-item active"> <img class="d-block w-100" src="{{file.image.url}}" alt="slides"> </div> {% endfor %} </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </body> -
Static files are not loading | Django
Static files are not loading and also does not shows any error. CODE -ADMIN settings.py STATIC_URL = '/static/' STATIC_DIR = os.path.join(BASE_DIR,"static") STATICFILES_DIRS = [ STATIC_DIR, ] STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn') urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('Welcome.urls')), path('auth/', include('Authentication.urls')), path('ad/', include('Ads.urls')), path('user/', include('UserDashboard.urls')), path('admin/', include('AdminDashboard.urls')), ] if settings.DEBUG: urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) APPS template <link href="{% static 'css/user/style.css' %}" rel="stylesheet"> Console Console Dirs Structure Project Directory Structure CODE EXPLANATION Simply added static files in the root dir and tried to import them in template but css files are not loading but media files are successfully loaded like this media <link rel="shortcut icon" type="image/jpg" href="{% static 'img/logo.png' %}" />. In dir structure image we can see img and css folder at same place in static folder. -
Why is the Django API returning an empty array
I am developing a web application using Django but I am not getting the desired results, the Django API is return an empty array ([]). This is the serializer class I am trying to get the places data -> from rest_framework import serializers from . import models class PlaceSerializer(serializers.ModelSerializer): class Meta: model = models.Place fields = ('id', 'name', 'image') These are the views -> from rest_framework import generics from .import models, serializers # Create your views here. class PlaceList(generics.ListCreateAPIView): serializer_class = serializers.PlaceSerializer def get_queryset(self): return models.Place.objects.filter(owner_id=self.request.user.id) # Only the owner can create or make changes on the places def perform_create(self, serializer): serializer.save(owner=self.request.user) -
Store who updated Django Model from admin
I have a use case where data is only inserted and updated from django admin. Now, I have multiple users who have access to django admin page. I want to be able to store who exactly updated or created a record in django admin page. Ideally, I want to add a separate column to an existing model. models.py class Links(models.Model): link = models.URLField(unique=True) created_at = models.DateTimeField(auto_now_add=True) created_by = model.ForeignKey(UserModel) updated_at = models.DateTimeField(auto_now=True) updated_by = model.ForeignKey(UserModel) -
Hello everyone. Has anyone used paystack payment gateway for a subscription django project before?
I tried to create models for user to subscribe within my application but that is not the aim. The aim is to make request to paystack within the backend when ever the frontend want to make subscription. -
serializer.is_valid() returns 500 Internal server error
I am new to Django and have trouble making django-rest-framework API for post, inheriting APIView. I'm using a serializer, that inherits djangos ModelSerializer. I see 500 Internal server error whenever I try validating the serializer. color.js posts image using Django rest framework as follows. function PersonalColorScreen({navigation,route}) { const {image} = route.params; console.log('uri is', image.uri); const [userToken, setUserToken] = React.useState(route.params?.userToken); const requestHeaders = { headers: { "Content-Type": "multipart/form-data" } } // helper function: generate a new file from base64 String //convert base64 image data to file object to pass it onto imagefield of serializer. //otherwise, serializer outputs 500 Internal server error code const dataURLtoFile = (dataurl, filename) => { const arr = dataurl.split(',') const mime = arr[0].match(/:(.*?);/)[1] const bstr = atob(arr[1]) let n = bstr.length const u8arr = new Uint8Array(n) while (n) { u8arr[n - 1] = bstr.charCodeAt(n - 1) n -= 1 // to make eslint happy } return new File([u8arr], filename, { type: mime }) } //random number between 0-9 function getRandomInt(max) { return Math.floor(Math.random() * max); } // generate file from base64 string const file = dataURLtoFile(image.uri, `${getRandomInt(10)}.png`) const formData= new FormData(); formData.append('img',file,file.name); console.log(file.name); //axios post request to send data // axios.post('http://localhost:8000/accounts/personalcolor/', formData,requestHeaders) //multipartparser axios.post('http://localhost:8000/accounts/personalcolor/', formData, requestHeaders) .then(res … -
"Anonymoususer" error after success payment and when go to CallbackURL, Django
my request and verify views: from django.http import HttpResponse, request from django.shortcuts import redirect, get_object_or_404, render from zeep import Client from django.conf import settings from accounts.models import Profile from products.models import Product from pay.models import Order, OrderItem import datetime from django.core.mail import BadHeaderError, send_mail from django.template.loader import render_to_string from pay.views import get_user_pending_order MERCHANT = 'xxx...xxxx' client = Client('https://www.zarinpal.com/pg/services/WebGate/wsdl') amount = "" description = "" # Required email = "" # Optional mobile = "" # Optional CallbackURL = 'https://example.com/payment/verify/' def send_request(request): username = request.user amount = get_user_pending_order(request).get_total() + get_user_pending_order(request).transport.transport_price email = username.email # Optional mobile = username.profile.phone_number # Optional result = client.service.PaymentRequest(MERCHANT, amount, description, email, mobile, CallbackURL) order_to_purchase = get_user_pending_order(request) order_to_purchase.save() if result.Status == 100: return redirect('https://www.zarinpal.com/pg/StartPay/' + str(result.Authority)) else: return HttpResponse('Error code: ' + str(result.Status)) def verify(request): amount = get_user_pending_order(request).get_total() + get_user_pending_order(request).transport.transport_price if request.GET.get('Status') == 'OK': result = client.service.PaymentVerification(MERCHANT, request.GET['Authority'], amount) if result.Status == 100: user = request.user order_to_purchase = get_user_pending_order(request) order_to_purchase.is_ordered = True order_to_purchase.date_ordered=datetime.datetime.now() order_to_purchase.created_on_time=datetime.datetime.now() order_to_purchase.save() order_items = order_to_purchase.items.all() for order_item in order_items: order_item.product.quantity = order_item.product.quantity - 1 order_item.product.save() order_items.update(is_ordered=True, date_ordered=datetime.datetime.now()) subject = 'successful' c = { "refid":str(result.RefID), "ref_code":order_to_purchase.ref_code, "owner":order_to_purchase.owner, } email_template_name = "pay/after_pay_confirm_email.html" email_html = render_to_string(email_template_name, c) email_from = settings.EMAIL_HOST_USER send_mail(subject, email_html, email_from, [user.email], html_message=email_html) ctx = … -
every time i try to upload an image from django admin i get this error : "FOREIGN KEY constraint failed''
everytime i try to upload an for the first time ive set the default value to temporary but then i changed it to None and i still see the default=temporary in django admin I dont know what to do please help <3 and I dont know why the error refers to FOREIGN KEY while i only have 1 model this is my model.py : from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import AbstractUser, AbstractBaseUser, PermissionsMixin, BaseUserManager class customMemberManager(BaseUserManager): def create_user(self, email, mobileNumber, name, familyName, password, nationalCode, image, **other_fields): if not email: raise ValueError('YOU MUST ENTER VALID EMAIL') email = self.normalize_email(email) user = self.model(email=email, mobileNumber=mobileNumber, name=name, image=image, familyName=familyName, password=password, nationalCode=nationalCode, **other_fields) user.set_password(password) user.save() return user def create_superuser(self, email, mobileNumber, name, familyName, image, password, nationalCode, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('superuser must be is_staff set to True') if other_fields.get('is_superuser') is not True: raise ValueError('superuser must be is_superuser set to True') return self.create_user(email, mobileNumber, name, familyName, password, nationalCode, image, **other_fields) class Members(AbstractBaseUser, PermissionsMixin): class Meta: verbose_name_plural = 'Members' name = models.CharField(max_length=50) familyName = models.CharField(max_length=50) email = models.EmailField(max_length=50) nationalCode = models.IntegerField(null=True) mobileNumber = models.IntegerField(null=True, unique=True) image = models.ImageField(upload_to='register_image/', blank=True,default=None) is_staff = models.BooleanField(default=False) is_active … -
Datetimepicker MM/YYYY Format
I'm attempting to implement the datetimepicker with just monthly selection. I've done this, but upon selecting a month, I get an error that indicates 'Enter a valid date.' I'm assuming django doesn't like the format of the date (i.e. MM/YYYY) given the fact that it's looking for something to fit into a DateField. Here is my form. class MonthlyForm(forms.Form): start_month = forms.DateField(required=True) def __init__(self, *args, **kwargs): super(MonthlyForm, self).__init__(*args, **kwargs) self.fields['start_month'].widget = DatePickerInput( options={ "format": "MM/YYYY", # moment date-time format "showClose": False, "showClear": False, "showTodayButton": False, "useCurrent": True, "ignoreReadonly": True, "keepInvalid": True, }, attrs={'autocomplete':'off'} ) Any thoughts on how to get around this would be appreciated. Even if I can somehow bypass the normal form validation for this field would work. I can do the validation inside of def clean. Thanks! -
How to add Series and Episodes in Django Movies website?
I created movies website , now i want to create models where i can select Serial and then add Series and Episodes . Fore example , add Serial Vikings , and then i want to add Season 1 and Episodes 1. What is best idea ? This is my Models class Serial(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") title_english = models.CharField(max_length=100) descritpion = models.TextField(max_length=1000) images = models.ImageField(upload_to="movies") category = models.CharField(choices=CATEGORY_CHOICES, max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES, max_length=30) status = models.CharField(choices=STATUS_CHOICES, max_length=100) year_of_production = models.TextField(max_length=1000) view_count = models.IntegerField(default=0) def get_absolute_url(self): return reverse('post', kwargs={"post_slug_serial": self.slug}) def __str__(self): return self.title i think i need Django Many to many relationship , but how ? Can anyone help me ? what is best way to create this task? -
Django how to link Users to Usermodel
Hello I am pretty new to Django and don't get yet fundamental ideas of Users. I was able to create a registration page to create users which are shown on the admin page in the "Authentication and AUthorization -> Users". Now I want the users to logg in and create their profiles. They should add some additional information like name, bio, picture etc. Every user should be able to add and see its own profile. To do that I created a model: class Profile(models.Model): firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) bio = models.TextField() profile_pic = models.ImageField(upload_to="images/") def __str__(self): return self.firstname + ' | ' + self.lastname In my view and the html I am able to add these informations to the model. But HOW exactly can I relate this "Profile"-Model to the individual user? What do I miss here? -
how to pass the value of list indjango to method
I am trying to do something like this, I have a navigation bar with li items. **index.html** <ul class="submenu dropdown-menu"> <li><a class="dropdown-item" name="mis" href="{% url 'pdfNotes'%}">MIS</a></li> <li><a class="dropdown-item" href="{% url 'pdfNotes'%}">MA</a></li> <li><a class="dropdown-item" href="{% url 'pdfNotes'%}">UXD</a></li> <li><a class="dropdown-item" href="{% url 'pdfNotes'%}">OSS</a></li> </ul> here when I navigate to the first list '' i.e for MIS I have to redirect to pdfNotes.html with the name as 'mis' so that I can use this as a parameter in views.py to filter my data and display only 'MIS' details in pdf notes. same for all other li items. **pdfNotes.html** {% if pdfnote %} <table> <tr> <th># </th> <th>NAME</th> <th>DOWNLOAD FILE</th> </tr> {% with counter=1 %} {% for item in pdfnote %} {% with crs=item.course %} <tr> <td id="id">{{crs}}</td> <td id="id">{{pattn}}</td> <td id="id">{{sem}}</td> <td id="id">{{ forloop.counter}}</td> <td id="name">{{item.name}}</td> <td id="downloadBtn"> <a href="{{item.file.url}}" class="btn-outline-success" download >DOWNLOAD</a> </td> </tr> {% endwith %} {% endfor %} {% endwith %} </table> **model.pdf** class PDF_Notes(models.Model): name=models.CharField("File name",max_length=100) subject=models.CharField("Subject",max_length=50) course=models.CharField("Course",max_length=50) semester=models.CharField("Semister",max_length=50) year=models.CharField("Year",max_length=50) source=models.CharField("Source",max_length=100) file=models.FileField(upload_to="media/PdfNotes") def __str__(self): return self.name **view.py** def pdfNotes(request): pdfNotes_file=PDF_Notes.objects.all() #sub=request.GET[] if(request.GET['mis']): pdfNotes_file=PDF_Notes.objects.all().filter(subject="MIS") n=len(pdfNotes_file) print("hello",pdfNotes_file) params={'pdfnote':pdfNotes_file,'total_items':n} return render(request,'pdfNotes.html',params) how can I do that, please... Thanx!!