query set lost when page changes in Django - django

I created a search system for my objects called Property and it filters and search through my objects well in first page but when I change pagination or ordering or changing page all filters gone and it sends all objects to template. is there anyway to fix this?
for example this is my first url after search:
/properties/search?location=&category=flat&look_for=FR
after switching to page 2 I get:
/properties/search?page=2
and the result of my search dissappeard.
my pagination in template:
{% if is_paginated %}
{% if page_obj.has_previous %}
<li>
<a href="?page=1" aria-label="First">
<span aria-hidden="true">First</span>
</a>
</li>
<li>
<a href="?page={{ page_obj.previous_page_number }}" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
{% endif %}
{% for num in page_obj.paginator.page_range %}
{% if page_obj.number == num %}
<li class="active">{{num}}</li>
{% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3'%}
<li>{{num}}</li>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<li>
<a href="?page={{ page_obj.next_page_number }}" aria-label="Next">
<span aria-hidden="true">»</span></a>
<li>
<a href="?page={{ page_obj.paginator.num_pages }}" aria-label="Last">
<span aria-hidden="true">Last</span></a>
{% endif %}
{%endif%}
views.py
class SearchView(ListView):
model = Property
template_name = 'property/properties-list.html'
context_object_name = 'properties'
ordering = '-pub_date'
paginate_by = 8
def get_context_data(self, *args, **kwargs):
context = super(SearchView, self).get_context_data(*args, **kwargs)
"""somthing"""
return context
def get_paginate_by(self, queryset):
if self.request.GET.get("paginate_by") == "":
return self.paginate_by
return self.request.GET.get("paginate_by", self.paginate_by)
def get_ordering(self):
ordering = super(SearchView, self).get_ordering()
if self.request.GET.get('sort_by') == "Name":
return ('-title')
elif self.request.GET.get('sort_by') == "Price":
return ('-price')
elif self.request.GET.get('sort_by') == "Date":
return ('-pub_date')
else:
return self.ordering
def get_queryset(self):
location = self.request.GET.get('location')
category = self.request.GET.get('category')
look_for = self.request.GET.get('look_for')
if location or category or look_for:
if look_for == '' and category == '':
queryset = Property.objects.filter(Q(city__icontains = location))
elif look_for == '':
queryset = Property.objects.filter(Q(city__icontains = location) & Q(category__slug = category))
elif category == '':
queryset = Property.objects.filter(Q(city__icontains = location) & Q(property_status = look_for))
else:
queryset = Property.objects.filter(Q(city__icontains = location) & Q(category__slug = category) & Q(property_status = look_for))
else:
queryset = Property.objects.all()
return queryset
url.py
path("properties/search", views.SearchView.as_view(), name = "Search")
Obviously I'm new to Django, if you have any recommendation to improve my code, I would be happy to hear it.

<a href="?page={{ page_obj.next_page_number }}" aria-label="Next">
Remember that HTTP is stateless. It doesn't automatically keep track of sorting or filtering options. Here you only include page in the query parameters, so this is the only option that is known when the user clicks the "next" button. One solution to maintain filtering or sort order is to include the appropriate query parameters in the href of all <a> tags.

Related

Use Q object and Paginator together in Django

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.

django access answers to math tasks in different view

I want to write a website that gives elementary math tasks to its visitors, quite similar to this: http://jsfiddle.net/r4QTQ/
In contrast to the JS example my idea is for the visitor to finish all tasks first, then press a button "check answers" and have all answers marked with a smiley if answer is right or the correct result if visitor's answer is wrong. To this - if I'm right - it's necessary to redirect the visitor's answers and the task-list to a different view. Also I want to use Django templates and CBviews.
I have this view for setting up the math tasks - view.py:
class Plus_im_10erPageView(TemplateView):
form_class = AnswerForm
template_name = 'plus_im_10er.html'
success_html = 'plus_im_10er_check.html'
def tasks(self):
# make a list of math tasks here
return task_list
def get_context_data(self, **kwargs):
context = super(Plus_im_10erPageView, self).get_context_data(**kwargs)
task_list = self.tasks()
context['tasks'] = task_list
self.context = context
return context
def post(self, request):
form = AnswerForm(request.POST)
if form.is_valid():
answers = form.cleaned_data
print(answers)
return render(request, self.success_html, {'answers': answers}
The AnswerForm is a collection of 10 CharFields like this - forms.py:
class AnswerForm(forms.Form):
answer_1 = forms.CharField(label='answer', required=False)
answer_2 = forms.CharField(label='answer', ...
...
Next is the template - plus_im_10er.html:
{% extends 'base.html' %}
{% block content %}
<ul>
<form method="POST">{% csrf_token %}
{% for task in tasks %}
<li>{{ task.0 }} + {{ task.1 }} =
<input type="text" size=2 name="answer_list"
onkeypress="return event.charCode >= 48 && event.charCode <=57">{{ answer }}
</input>
</li>
{% endfor %}
</br>
</br>
<input type="button" onclick="location.href='/plus_im_10er_check/';"
value="Check answers">
</input>
</ul>
{% endblock content %}
This works so far.
What I cannot figure out is how to continue. My idea is to write a second view called Plus_im_10er_checkPageView and a second template called plus_im_10er_check.html but whatever I tried didn't get me anywhere. I spare you my attempts. How would you tackle this?
This is a working solution. It's not pretty, so I would appreciate ideas to refacture it.
Starting with view.py:
class Plus_im_10erPageView(TemplateView):
template_name = 'plus_im_10er.html'
success_html = 'plus_im_10er_check.html'
no_of_tasks = 3
#classmethod
def generate_plus10_tasks(self):
"""
Generate tasks containing two addends with a sum less or equal 10.
"""
task_list = []
for _ in range(self.no_of_tasks):
while True:
x = random.randint(0, 9)
y = random.randint(0, 9)
result = x + y
if result <= 10:
task_list.append((x, y, result))
break
self.task_list = task_list
return task_list
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs) # noqa
context['task_list'] = self.generate_plus10_tasks()
self.context = context
return context
def post(self, request):
form = AnswerForm(request.POST)
answered_tasks = []
if form.is_valid():
answers = form.cleaned_data
total_correct_answers = 0
# helper to get the form_field name
index = 1
for task in self.task_list:
if index > self.no_of_tasks:
break
answer = int(answers[f'answer_{index}'])
x, y, correct_result = task
if answer == correct_result:
total_correct_answers += 1
answered_tasks.append((x, y, correct_result, answer,
total_correct_answers)) # noqa
index += 1
return render(request,
self.success_html,
{'answered_tasks': answered_tasks}
)
The forms:
from django import forms
class AnswerForm(forms.Form):
answer_1 = forms.CharField(label='answer', required=False)
answer_2 = forms.CharField(label='answer', required=False)
answer_3 = forms.CharField(label='answer', required=False)
answer_4 = forms.CharField(label='answer', required=False)
answer_5 = forms.CharField(label='answer', required=False)
answer_6 = forms.CharField(label='answer', required=False)
answer_7 = forms.CharField(label='answer', required=False)
answer_8 = forms.CharField(label='answer', required=False)
answer_9 = forms.CharField(label='answer', required=False)
answer_10 = forms.CharField(label='answer', required=False)
plus_im_10er.html
<!-- templates/plus_im_10er.html -->
{% extends 'base.html' %}
{% block content %}
<h2>Plus rechnen im 10er-Raum</h2>
<ul>
<form method="POST">{% csrf_token %}
{% for task in task_list %}
<li><label for="id_answer">{{ task.0 }} + {{ task.1 }} = </label>
<input id="id_answer" type="text" size=2 name="answer_{{ forloop.counter }}"
onkeypress="return event.charCode >= 48 && event.charCode <=57">{{ form }}
</input>
</li>
{% endfor %}
</ul>
</br></br>
<form action="/plus_im_10er_check/" method="GET">
<input type="submit" value="Antworten prüfen">
</form>
{% endblock content %}
plus_im_10er_check.html
<!-- templates/plus_im_10er_check.html -->
{% extends 'base.html' %}
{% block content %}
<h2>Plus rechnen im 10er-Raum</h2>
<h3>Antworten prüfen</h3>
<ul>
<div>
{% for task in answered_tasks %}
{% if task.2 == task.3 %}
<li>{{ task.0 }} + {{ task.1 }} = {{ task.3 }} &#128515</li>
{% else %}
<li>{{ task.0 }} + {{ task.1 }} &#8800 {{ task.3 }}</li>
{% endif %}
{% endfor %}
</br>
Du hast {{ answered_tasks.2.4 }} &#128515 von 3.
</div>
</br></br>
<button type="button">Neue Aufgaben</button>
</ul>
{% endblock content %}
Ande the result looks like this:

Reverse for 'sales' with no arguments not found. 1 pattern(s) tried: ['sales/(?P<pk>\\d+)/$']

I have seen a lot of relatable questions and answers, I just haven't understood even after tweaking my code why it doesn't seem to respond. I am new to django, I am hoping someone can point me in the right direction.
Views.py
#login_required
def add_user_sales(request , pk):
current_user = request.user
context = {}
context["data"] = MadeSale.objects.get(id=pk)
profiles = UserProfile.get_profile()
for profile in profiles:
if profile.profile_name.id == current_user.id:
if request.method == 'POST':
form = SalesForm(request.POST)
if form.is_valid():
upload = form.save(commit=False)
upload.posted_by = current_user
upload.profile = profile
upload.save()
messages.success(request, f'Hi, Your data has successfully been updated' )
return redirect('addProduct')
else:
form = SalesForm()
return render(request,'addProduct.html',{"user":current_user,"form":form}, context)
linked url
<nav class="navbar" style="margin-left: auto;">
<ul class="ul" style="margin-left: auto;">
<li class="li">Home</li>
<li class="li">Sales</li> ***(This line is the culprit)***
<li class="li">Total</li>
<li class="li">Margin</li>
<!-- For DevelopmentPurposes -->
<li class="li">Admin Dashboard</li>
<li class="li">Total</li>
</ul>
</nav>
my url
url(r'sales/(?P<pk>\d+)/$', views.add_user_sales, name='sales'),
There's a missing space in your url templatetag 
{% url 'sales'add_user_sales.pk %}
needs to be
{% url 'sales' add_user_sales.pk %}

context not rendering in django App

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.

Django Paginator Error

I'm been trying to implement django paginator into my whiteboard app so I can split the pictures into different pages.
The problem occurs when I attempt to move across different pages.I limited each page to 1 objects and uploaded few pictures to test if the pagination works between pages but when I try to move across different pages using the pagination method, it doesn't respond.
http://img854.imageshack.us/img854/3303/94627386.jpg
I'm been researching and testing for solutions to this problems through the django pagination docs and I think problem lay at the pagination module method at my template.
My views.py
def Boat(request ,animal_id):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('world:LoginRequest'))
picture = Picture.objects.filter(board=animal_id)
paginator = Paginator(picture,1)
page = request.GET.get('page')
try:
picture = paginator.page(page)
except PageNotAnInteger:
picture = paginator.page(1)
picture = paginator.page(paginator.num_pages)
return render(request,'boat.html',{'picture':picture })
My boat.html
{% if picture.object_list %}
<ul>
{% for pet in picture.object_list %}
{% if pet.image %}
<br>
<img src= "{{ pet.image.url }}" </a>
<br>
</a>
</li>
{% endif %}
<br>
View Comment Like<br/>
{% for c in picture %}
{% ifequal c.picture.id pet.id %}
<br>{{ c.body }}</li>
<br>{{ c.created}}</li>
<br>{{ c.user}}</li>
{% endifequal %}
% endfor %}
{% endfor %}
</ul>
{% endif %}
Add Pictures to your board<br/>
{% if number %}
{{number}}
{% endif %}
Return back to Profile<br/>
<br><br><br><br><br>
<div class="pagination">
<span class="step-links">
{% if picture.has_previous %}
previous
{% endif %}
<span class="current">
Page {{ picture.number }} of {{ picture.paginator.num_pages }}.
</span>
{% if picture.has_next %}
next
{% endif %}
</span>
</div>
Parts of my module
class Picture(models.Model):
user = models.ForeignKey(User)
board = models.ForeignKey(Board,blank=False,null=False,related_name='board')
image = models.FileField(upload_to="images/",blank=True)
description = models.TextField()
is_primary = models.BooleanField(default=False)
def __unicode__(self):
return self.description
def Boat(request ,animal_id):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('world:LoginRequest'))
picture = Picture.objects.filter(board=animal_id)
paginator = Paginator(picture,1)
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
try:
picture = paginator.page(page)
except (EmptyPage, InvalidPage):
picture = paginator.page(paginator.num_pages)
picture = paginator.page(paginator.num_pages)
return render(request,'boat.html',{'picture':picture })
#this is view
#this is views files
#login_required(login_url='/login')
# class Base_page_list2(ListView):
def Base_page_list(request,*args, **kwargs):
# tiket = Tiket.objects.all()
# lastest_tiket =Tiket.objects.order_by('-id').all()[:8]
tiket_list = Tiket.objects.all()
paginator = Paginator(tiket_list,2)
page = request.GET.get('page')
page_obj = paginator.get_page(page)
context ={
'tiket':None,
'page_obj':page_obj,
}
context['tiket']=['page_obj']
if request.user.is_superuser:
context['tiket']= Tiket.objects.all()
elif not request.user.is_hrm:
raise Http404('شما نمی توانید به این صحفه دسترسی داشته باشید')
elif request.user.is_mis :
context['tiket']= Tiket.objects.filter(status_tag='s')
elif request.user.is_mali:
context['tiket']=Tiket.objects.filter(status_tag='m')
elif request.user.is_mosh:
context['tiket']=Tiket.objects.filter(status_tag='c')
elif request.user.is_modir:
context['tiket']=Tiket.objects.filter(status_tag='b')
elif request.user.is_kz:
context['tiket']=Tiket.objects.filter(status_tag='k')
elif request.user.is_pa:
context['tiket']=Tiket.objects.filter(status_tag='p')
else:
context['page_obj']['tiket']=Tiket.objects.filter(author=request.user)
return render(request,'hrm_account/base.html',context)
`enter code here`error
File "/home/ali/Desktop/testsharen2/sharen/sharen_hrm/views.py", line 128, in Base_page_list
context['page_obj']['tiket']=Tiket.objects.filter(author=request.user)
TypeError: 'Page' object does not support item assignment