I've created View which filters data by search query given in textbox. As well as I used Paginator to show data divided into pages.
My problem is, when I filter data with Q object then and try to paginate by clicking the next button, all data is refreshed.
When I search text by Q object the URL becomes http://127.0.0.1:8000/mael/parties/?q=keyword
And from clicking the next button the URL becomes http://127.0.0.1:8000/mael/parties/?page=2
When I manually change URL http://127.0.0.1:8000/mael/parties/?q=keyword&page=2, then it works. But I don't know how to do this in code.
Is it possible to use Q object search and pagination together?
My View
from mael.models import PartyTotalBillsView
from django.views.generic import ListView
from django.db.models import Q
from django.http import HttpResponseRedirect
class PartyListView(ListView):
paginate_by = 2
model = PartyTotalBillsView
def parties(request):
# Show all records or searched query record
search_text = request.GET.get('q','')
try:
if search_text:
queryset = (Q(party_name__icontains=search_text))
party_list = PartyTotalBillsView.objects.filter(queryset).order_by('party_name')
else:
# Show all data if empty keyword is entered
party_list = PartyTotalBillsView.objects.order_by('party_name')
except PartyTotalBillsView.DoesNotExist:
party_list = None
paginator = Paginator(party_list, 2) # Show 2 rows per page: for Test
page_number = request.GET.get('page')
party_list = paginator.get_page(page_number)
return render(request, 'mael/parties.html', {'party_list': party_list})
Template file
<form id="search-form" method="get" action="/mael/parties/">
<input id="search-text" type="text" name="q" placeholder="Enter search keyword">
<input class="btn-search-party" type="submit" value="Search" />
</form>
<br/>
<table class="show-data">
<thead>
<tr>
<th>ID</th>
<th>Party Name</th>
<th>Total Bill Amount</th>
<th>Phone</th>
<th>Address</th>
<th></th>
</tr>
</thead>
{% if party_list %}
<tbody>
{% for party in party_list %}
<tr>
<td class="party-id">{{ party.party_id }}</td>
<td class="party-name">{{ party.party_name }}</td>
<td>{{ party.total_bills }}</td>
<td class="party-phone">{{ party.party_phone }}</td>
<td class="party-address">{{ party.party_address }}</td>
<td>
<button class="btn-modify" data-partyid="{{party.party_id}}" type="buttton">
Modify
</button>
</td>
</tr>
{% endfor %}
</tbody>
{% endif %}
</table>
<div class="pagination">
<span class="step-links">
{% if party_list.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ party_list.number }} of {{ party_list.paginator.num_pages }}
</span>
{% if party_list.has_next %}
next
last »
{% endif %}
</span>
</div>
Please do not use two views. A ListView can perform filtering as well:
class PartyListView(ListView):
paginate_by = 2
model = PartyTotalBillsView
template_name = 'mael/parties.html'
context_object_name = 'party_list'
def querystring(self):
qs = self.request.GET.copy()
qs.pop(self.page_kwarg, None)
return qs.urlencode()
def get_queryset(self):
qs = super().get_queryset()
if 'q' in self.request.GET:
qs = qs.filter(party_name__icontains=self.request.GET['q'])
return qs.order_by('party_name')
In the links for the previous and next pages, you then append the querystring of the view:
<span class="step-links">
{% if party_list.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}
</span>
{% if party_list.has_next %}
next
last »
{% endif %}
</span>
Pagination & CBV
If you are using django generic ListView with paginate_by attribute, you don't need to build paginator instance. Either you use CBV (Class Based View) or Function Views but not both.
For HTML display create a _django_pager.html page to include in your list pages.
{% comment %}
https://getbootstrap.com/docs/4.1/components/pagination/
{% endcomment %}
{% if is_paginated %}
<ul class="pagination">
{% if page_obj.has_previous %}
<li class="page-item"><a class="page-link" href="?{% url_replace page=page_obj.previous_page_number %}">«</a></li>
{% else %}
<li class="page-item disabled">«</li>
{% endif %}
{% for i in page_obj.paginator.page_range %}
{% if page_obj.number == i %}
<li class="page-item active">{{ i }}<span class="sr-only">(current)</span></li>
{% else %}
<li class="page-item"><a class="page-link" href="?{% url_replace page=i %}">{{ i }}</a></li>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<li class="page-item"><a class="page-link" href="?{% url_replace page=page_obj.next_page_number %}">»</a></li>
{% else %}
<li class="page-item disabled">»</li>
{% endif %}
</ul>
{% endif %}
Filtering
Q object is powerfull for building complex query but you have to specify DB field under which Q object applies.
Instead of hardcoding the form in HTML I recommand to use a Form Class. So in forms.py create a PartySearchForm
class PartySearchForm(forms.Form):
"""
Search in party
"""
search_text = forms.CharField(max_length=100,
required=False,
widget=forms.TextInput(attrs={
"class": "form-control",
"placeholder": "Search"
})
)
Option 1: filter queryset in view
class PartyListView(ListView):
model = PartyTotalBillsView
form = PartySearchForm
paginate_by = 100
def build_where(self):
where = Q(pk__gt=0)
if self.request.GET.get("search_text"):
search_list = self.request.GET.get("search_text", None).split()
for search_item in search_list:
where &= (
Q(party_name__icontains=search_item)
)
return where
def get_queryset(self):
qs = self.model.objects.all()
qswhere = qs.filter(self.build_where())
# first param must be request.GET or None (essential for the first load and initial values)
# https://www.peterbe.com/plog/initial-values-bound-django-form-rendered
self.form = PartySearchForm(self.request.GET or None)
return qswhere
In the build_where function you can add as many search field as you want. You can search on other DB field than party_name by adding the fields to the where variable.
where &= (
Q(party_name__icontains=search_item)
| Q(party_location__icontains=search_item)
)
You can also add other search fields than search_text in your form and add Q search on the where variable.
if self.request.GET.get("my_new_field"):
where &= Q(supplier=self.request.GET.get("my_new_field", ""))
Key point here is the get_queryset method where the displayed queryset is defined, ie: fetched, filtered and sorted (which could also be a method). .order_by('party_name') is not useful if you add a class Meta in models.py
class Meta:
verbose_name = "Let's go party"
ordering = ['party_name']
One other way to do would be to pass the queryset to the form and perform the search
Option 2: filter queryset in form
Looks even cleaner with the search logic in the SearchForm only!
PartyListView.get_queryset become
def get_queryset(self):
qs1 = self.model.objects.all()
self.form = PartySearchForm(self.request.GET, queryset=qs1)
qs = self.form.get_queryset(self.request.GET)
return qs
PartySearchForm become
class PartySearchForm(forms.Form):
"""
Search in party
"""
search_text = forms.CharField(max_length=100,
required=False,
widget=forms.TextInput(attrs={
"class": "form-control",
"placeholder": "Search"
})
)
def __init__(self, *args, **kwargs):
"""
Takes an option named argument ``queryset`` as the base queryset used in
the ``get_queryset`` method.
"""
self.queryset = kwargs.pop("queryset", None)
super().__init__(*args, **kwargs)
def get_queryset(self, request):
where = Q(pk__gt=0)
# is_valid() check is important to get access to cleaned_data
if not self.is_valid():
return self.queryset
search_text = self.cleaned_data.get("search_text").strip()
if search_text:
search_list = search_text.split()
for search_item in search_list:
where &= (
Q(party_name__icontains=search_item)
)
qs = self.queryset.filter(where)
return qs.distinct()
Eventually, if you are using Postgres DB and want to go deeper with Text Search you can implement Django full text search. Pros & cons can be gained by reading this.
Related
I want to call a function - from a model or from a Listview that will change Order.isDone status - TRUE or FALSE after clicking the button in template.
Model.py:
class Order(models.Model):
isDone = models.BooleanField(default=False, verbose_name='Zrealizowane')
views.py:
class OrderListView (ListView):
model = Order
template_name = 'orders/orders_list.html'
ordering = ['-orderDate']
urls.py:
urlpatterns = [
path('', views.home, name='page-home'),
path('orders_list/', OrderListView.as_view(), name='page-orders-list'),
path('completed_orders_list/', OrderCompletedListView.as_view(), name='page-completed-orders-list'),
path('orders/order_create/', OrderCreateView.as_view(), name='page-order-create'),
path('orders/<int:pk>/delete/', OrderDeleteView.as_view(), name='page-order-delete'),
]
template:
<tbody>
{% for order in object_list %}
{% if order.isDone == False %}
<tr>
<td>
<button type="button" class="btn btn-secondary" data-toggle="modal" data-target="#exampleModalCenter">Szczegóły</button>
<form action="{% url 'page-orders-list' order.id %}" method="post">
{% csrf_token %}
<button class="btn btn-info btn-sm">Finish order</button>
<form>
<a class="btn btn-danger adminButton" href="{% url 'page-order-delete' order.id %}">Usuń</a>
</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
What is the easiest way to do this ?
I suggest using another view for this. You can use the get method in the view to change the status of the order. The in your HTML you would only need to use a link instead of a form.
So something like this:
views.py
class OrderFinishView(RedirectView):
success_url = None # After finishing the order, where do you want to redirect the user?
def get(self, request, *args, **kwargs):
order_id = self.kwargs['pk_order'] # pk_order must be in your URL
order = get_object_or_404(Order, pk=order_id)
order.is_done = True
order.save()
return super().get(request, *args, **kwargs)
urls.py
urlpatterns = [
path('', views.home, name='page-home'),
path('orders_list/', OrderListView.as_view(), name='page-orders-list'),
path('completed_orders_list/', OrderCompletedListView.as_view(), name='page-completed-orders-list'),
path('orders/order_create/', OrderCreateView.as_view(), name='page-order-create'),
path('orders/<int:pk>/delete/', OrderDeleteView.as_view(), name='page-order-delete'),
path('orders/<int:pk_order>/finish', OrderFinishView.as_view(), name='page-order-finish'),
]
template
<tbody>
{% for order in object_list %}
{% if order.isDone == False %}
<tr>
<td>
<a href={% url 'page-order-finish' order.id %}>Finish</a>
</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
Another idea is to use an UpdateView to update your order with a PartialOrderForm which would only contain the is_done field.
I used the #vinkomlacic's solution, but i changed the return of get function:
def get(self, request, *args, **kwargs):
order_id = self.kwargs['pk_order'] # pk_order must be in your URL
order = get_object_or_404(Order, pk=order_id)
order.isDone = True
order.save()
return redirect(self.success_url)
Seems to be working properly now after setting success_url in class
I would like to update my list after adding some inputs through a form but i cannot see my updated list. I see the existing items in my list ,but when i add a new item it does not appear on the list. I can manually add it using the admin pannel and view it in the list(a whole different path),but not with the form i created to take input and update the list. I was able to query my database and input from the form is not getting written to the database, that's why its not displaying any changes.Below is my code
models.py
class BlogPost(models.Model):
notes = models.CharField(max_length = 1000000000000000000000000000)
date = models.DateTimeField(auto_now_add=True)
done = models.BooleanField(default=False)
def __str__(self):
return self.notes
form.py
from blog.models import BlogPost
class BlogForm(forms.ModelForm):
class Meta:
model = BlogPost
fields = ['notes', 'done',]
views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse,HttpResponseRedirect,HttpRequest
from blog.models import BlogPost
from blog.form import BlogForm
def home(request):
context = {
'welcome_text': 'Welcome to the home page. View some more stuff soon'
}
return render(request,'home.html', context)
def blogpost(request):
if request.method == "POST":
form = BlogForm(request.POST)
if form.is_valid():
if form.save():
message.success(request, "the task was added")
return redirect('blogpost')
else:
all_blogs = BlogPost.objects.all
return render(request, 'blog.html',{'the_blogs': all_blogs } )
blog.html
{%extends 'base.html' %}
{% block title%}
<title> Blog </title>
{% endblock title%}
{%block content %}
<div class="container">
<br>
{%for message in messages%}
{{message}}
{% endfor %}
<form method = 'POST'>
{% csrf_token %}
<div class="form-group">
<input type="text" class="form-control" name = 'blog' placeholder = 'new blog' >
</div>
<button type="submit" class="btn btn-primary">Add Blog</button>
</form>
<br>
<table class="table table-hover table-dark">
<thead>
<tr>
<th scope="col">Blog </th>
<th scope="col">Done</th>
<th scope="col">Date</th>
<th scope="col">Edit</th>
<th scope="col">Delete</th>
</tr>
</thead>
<tbody>
{% for item in the_blogs %}
{% if item.done %}
<tr class="table-success">
<td >{{item.notes}}</td>
<td >Not-Completed</td>
<td>{{item.date}}</td>
<td>edit</td>
<td>delete</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
</div>
{%endblock content%}
if you need more information regarding this, here is a link to my GitHub repository with more code.
https://github.com/wfidelis/Django-App
You have to correct the code indentation and the get call part, pass the form to context object and call it with double curly brackets on templates, also add an action attribute to the template.
def blogpost(request):
all_blogs = BlogPost.objects.all()
if request.method == "POST":
form = BlogForm(request.POST)
if form.is_valid():
if form.save():
message.success(request, "the task was added")
return redirect('blogpost')
else:
form = BlogForm()
return render(request, 'blog.html',{'form': form, 'the_blogs': all_blogs } )
<form method='POST' action="">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary">Add Blog</button>
<form/>
When you add a blog, don't redirect, try rendering the page with the new list the same as how you did it here:
all_blogs = BlogPost.objects.all
return render(request, 'blog.html',{'the_blogs': all_blogs } )
or try returning new object created as JSON format to the front-end (as a response of the POST request) and front-end will add it to the HTML with jQuery or JS
My application has two models, Recipe and RecipeIngredient, related by foreign key. Each Recipe may have many different RecipeIngredients (and different number of associated ingredients for each recipe). So using a dynamic formset to assign ingredients to a recipe seems to be the best approach.
I have a simple form that has a user enter a quantity and select a unit and ingredient from a dropdown. As a standalone form it works fine.
Unfortunately, I cannot get any formset incorporating it to submit.
I have searched many of the different formset Q&As here on StackOverflow but cannot see where the problem is. When I click 'submit', the form blinks and refreshes in place, with the entered values still in the form. No objects are created. No errors report to the console nor to the browser. The related code:
The models:
class RecipeBase(models.Model):
id = models.UUIDField(primary_key=True,default=uuid.uuid4,null=False)
name = models.CharField(max_length=128,null=False)
creation_date = models.DateField("Record creation date",auto_now_add=True)
creation_user = models.CharField("Record creation user",max_length=150)
lastupdated_date = models.DateField(auto_now=True)
lastupdated_user = models.CharField(max_length=150)
category = models.ForeignKey(RecipeCategory,on_delete=models.CASCADE,related_name='recipes')
subcategory = models.ForeignKey(RecipeSubcategory,on_delete=models.CASCADE,related_name='recipes')
def __str__(self):
return str(self.name)
class RecipeIngredient(models.Model):
id = models.UUIDField(primary_key=True,default=uuid.uuid4,null=False)
quantity = models.DecimalField(max_digits=8,decimal_places=3,null=False)
referenced_unit = models.ForeignKey(UnitDetail,on_delete=models.CASCADE)
referenced_ingredient = models.ForeignKey(Ingredient,on_delete=models.CASCADE)
parent_recipe = models.ForeignKey(RecipeBase,on_delete=models.CASCADE,related_name='ingredients')
def __str__(self):
return str(self.id)[:8]
The call to enter ingredients:
<a class='btn btn-success' href="{% url 'recipes:addingredient' pk=recipe_details.pk %}">Add Ingredients</a>
Calls the view:
class AddIngredientView(CreateView):
form_class = AddIngredientForm
model = RecipeIngredient
template_name = 'addingredientmultiple2.html'
success_url = "recipes:listrecipes"
def get_context_data(self, **kwargs):
parent_recipe_id = RecipeBase.objects.get(id=self.kwargs['pk'])
data = super(AddIngredientView, self).get_context_data(**kwargs)
if self.request.POST:
data['ingredients'] = AddIngredientFormset(self.request.POST)
data['parent_recipe_id'] = parent_recipe_id
else:
data['ingredients'] = AddIngredientFormset()
data['fixture'] = parent_recipe_id
return data
def form_valid(self, form, **kwargs):
user = self.request.user
fixture = RecipeBase.objects.get(id=self.kwargs['pk'])
context = self.get_context_data()
formset = AddIngredientFormset(self.request.POST)
if formset.is_valid():
ingredients = formset.save()
for recipeingredient in ingredients:
#recipeingredient.creation_user = str(request.user)
#recipeingredient.lastupdated_user = str(request.user)
recipeingredient.parent_recipe_id = parent_recipe_id
#recipeingredient.user = user
recipeingredient.save()
return super(AddIngredientView, self).form_valid(form)
Using form and formset:
class AddIngredientForm(forms.ModelForm):
quantity = forms.DecimalField(widget=forms.NumberInput(attrs={'data-placeholder': 0.00,'size': '8','label_tag': ''}))
referenced_unit = forms.ModelChoiceField(queryset=UnitDetail.objects.all())
referenced_ingredient = forms.ModelChoiceField(queryset=Ingredient.objects.all())
class Meta():
model = RecipeIngredient
fields = ('quantity','referenced_unit','referenced_ingredient',)
AddIngredientFormset = inlineformset_factory(RecipeBase,RecipeIngredient,form=AddIngredientForm,extra=1,can_delete=True)
And template:
{{ ingredients.media.css }}
<div class="container">
<h2>Add ingredients to {{ referring_recipe_name }}</h2>
<h4>{{ referring_recipe_id }}</h4>
</div>
<div class="col-md-4">
<form class="form-horizontal" enctype="multipart/form-data" method="post">{% csrf_token %}
<table class="table">
{{ ingredients.management_form }}
{% for form in ingredients.forms %}
{% if forloop.first %}
<thead>
<tr>
{% for field in form.visible_fields %}
<th>{{ field.label|capfirst }}</th>
{% endfor %}
</tr>
</thead>
{% endif %}
<tr class="formset_row">
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<input class='btn btn-success' type="submit" value="Save"/> back to the list
</form>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'formset/jquery.formset.js' %}"></script>
<script type="text/javascript">
$('.formset_row').formset({
addText: 'ADD INGREDIENT',
deleteText: 'REMOVE',
prefix: 'ingredients'
});
</script>
{{ ingredients.media.js }}
I am driving to render a context scale that is not rendering in my HTML and I can manage to see the error. I do not get any error in the inspect/console and neither in the Atom terminal.
I am developing a survey app using a scale from 0-100% (using JavaScript)
but for some reason it is not rendering;
here is my code:
views.py
class SurveyDetail(View):
def get(self, request, *args, **kwargs):
survey = get_object_or_404(Survey, is_published=True, id=kwargs['id'])
if survey.template is not None and len(survey.template) > 4:
template_name = survey.template
else:
if survey.display_by_question:
template_name = 'survey/survey.html'
else:
template_name = 'survey/one_page_survey.html'
if survey.need_logged_user and not request.user.is_authenticated():
return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
categories = Category.objects.filter(survey=survey).order_by('order')
form = ResponseForm(survey=survey, user=request.user,
step=kwargs.get('step', 0))
#try:
get_scale = form.get_multiple_scale()
#except:
# get_scale = None
context = {
'response_form': form,
'survey': survey,
'categories': categories,
'scales': get_scale
}
return render(request, template_name, context)
form.py:
class ResponseForm(models.ModelForm):
WIDGETS = {
Question.TEXT: forms.Textarea,
Question.SHORT_TEXT: forms.TextInput,
Question.RADIO: forms.RadioSelect,
Question.SELECT: forms.Select,
Question.SELECT_IMAGE: ImageSelectWidget,
Question.SELECT_MULTIPLE: forms.CheckboxSelectMultiple,
Question.SCALE: forms.TextInput,
}
class Meta(object):
model = Response
fields = ()
def __init__(self, *args, **kwargs):
""" Expects a survey object to be passed in initially """
self.survey = kwargs.pop('survey')
self.user = kwargs.pop('user')
try:
self.step = int(kwargs.pop('step'))
except KeyError:
self.step = None
super(ResponseForm, self).__init__(*args, **kwargs)
self.uuid = uuid.uuid4().hex
self.steps_count = len(self.survey.questions.all())
# add a field for each survey question, corresponding to the question
# type as appropriate.
data = kwargs.get('data')
for i, question in enumerate(self.survey.questions.all()):
is_current_step = i != self.step and self.step is not None
if self.survey.display_by_question and is_current_step:
continue
else:
try:
self.scales = question.get_multiple_scales()
except:
self.scales = None
self.add_question(question, data)
def get_multiple_scale(self):
mscale = []
for items in self.scales:
index, question = items
tag = "<p class='tagged'>{}</p>".format(question)
mscale.append(tag)
return mscale
HTML:
{% load bootstrap %}
{% load static %}
{% load i18n %}
{% load survey_extras %}
<table class="table">
<!--<thead>
<tr>
<th> Question </th>
<th> Answers </th>
</tr>
</thead> -->
<tbody>
{% for form in response_form %}
{% if form.field.widget.attrs.category == category.name or not form.field.widget.attrs.category %}
<tr class="{% if form.errors%} danger {% endif %}">
<td>
<div class="question-title">
<h4>{{ form.label|safe }}</h4>
</div>
{% if form.field.required %}
<span class="glyphicon glyphicon-asterisk" style="color:red"> </span>
{% endif %}
<span class="help-inline" style="color:red">
<strong> {% for error in form.errors %}{{ error }}{% endfor %} </strong>
</span> <br>
<div class="answers">
{% for field in form %}
<ul>
{{ field }}
</ul>
{% endfor%}
{% if "hidden" in form.field.widget.attrs %}
<br>
{% for scale in scales %}
{{ scale|safe }}
<div id="rate" class="scale">
</div>
<div class="scale-title">
<div class="container">
<div class="row">
<div class="col scaleleft">
0%
</div>
<div class="col scaleright">
100%
</div>
</div>
</div>
</div>
<br>
{% endfor %}
{% endif %}
</div>
</td>
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
You've got a catch-all except clause in the get method. That is a very very very bad idea; you are catching and hiding any error that happens in the get_multiple_scale method. Probably, something is going wrong there, but your code makes it impossible to tell what.
Remove that try/except.
You have a similar one in your form's init method; there it makes even less sense, as you end up assigning None to self.scales which is the very thing that you're iterating over in get_multiple_scales. There is a very odd circular definition here, which you certainly shouldn't have.
My view:
class HospitalAppointmentView(ListView):
model = DoctorAppointment
template_name = "doctor_appointment_list.html"
paginate_by = 5
def get(self, request, pk, username, hdpk, **kwargs):
self.pk = pk
self.username = username
self.hdpk = hdpk
return super(HospitalAppointmentView, self).get(request, pk, username, hdpk, **kwargs)
def get_context_data(self, **kwargs):
context = super(HospitalAppointmentView, self).get_context_data(**kwargs)
context['appointments'] = DoctorAppointment.objects.filter(hospital__id=self.pk, doctor__id=self.hdpk).order_by("-appointment_date")
context['today'] = today
return context
And my template:
{% for appointment in appointments %}
<table>
<tr>
<td>{{appointment.appointment_date}}</td>
<td>{{appointment.first_name}} {{appointment.middle_name}} {{appointment.last_name}}</td>
<td>{{appointment.user}}</td>
</tr>
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if page_obj.has_previous %}
previous
{% endif %}
<span class="current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
next
{% endif %}
</span>
When I do this it displays the page no but dont paginate the data.. It shows all the list. It should be showing only 5 value but showing all the value.
Thanks in advance..
Appointments should be a Pagination object. Currently you are sending a queryset.
Check https://docs.djangoproject.com/en/dev/topics/pagination/ for examples.
Instead of adding the appointments in get_context_data, you should override get_queryset.
class HospitalAppointmentView(ListView):
...
def get_queryset(self, **kwargs):
return DoctorAppointment.objects.filter(
hospital__id=self.pk,
doctor__id=self.hdpk).order_by("-appointment_date")
Also, change the template variable you access to object_list:
{% for appointment in object_list %}