Django Check boxes and progress bar - python-2.7

I'm new to Django a few week or two in to learning.
Django Ver 1.11
Python Ver 2.7
I'm making a Todo app in Django and I'm done with the application, but I want to add some extra features to it.
1. Sub tasks Checkbox that update the progress bar on the main page
2. and after the progress bar has reached 100% the status changes to done of the task.
I've made the login, registration, logout, adding new tasks and deleting the ones that are complete to my app so far.
here is the code
Models.
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
class To_DO_Fun(models.Model):
Task_Name = models.CharField(max_length=20, default='')
Task_Text = models.TextField(max_length=45, default='')
Task_Done = models.BooleanField(default=False)
owner = models.ForeignKey(User)
def __str__(self):
return self.Task_Name + ' is ' + str(self.Task_Done) + ' by ' + str(self.owner)
forms
from .models import To_DO_Fun
from django import forms
class Form_todo(forms.ModelForm):
class Meta:
model = To_DO_Fun
fields = ['Task_Name','Task_Done']
class Form_Task(forms.ModelForm):
class Meta:
model = To_DO_Fun
exclude = ['Task_Name','Task_Done', 'owner']
fields = ['Task_Text']
views
from __future__ import unicode_literals
from django.shortcuts import render, redirect
from .models import To_DO_Fun #Class Name
from .forms import Form_todo, Form_Task #Form Name
from django.contrib import messages
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import JsonResponse
def HomeFun(request): #To view contents of the home page
return render(request, "ToDo_Files/HomePage.html")
#login_required(login_url='Login-Page')
def Display_Page(request):
if request.user.is_superuser:
all_items = To_DO_Fun.objects.all()
else:
all_items = To_DO_Fun.objects.filter(owner = request.user)
context = {'all_items':all_items}
if request.method == "POST":
obj_todo = To_DO_Fun()
obj_todo.Task_Name = request.POST.get('Task_Name')
obj_todo.owner_id = request.POST.get('owner_id')
obj_todo.save()
context = {'all_items': all_items}
messages.success(request, ("Good Luck."))
return render(request,'ToDo_Files/Display_Page.html',context )
else:
return render(request , 'ToDo_Files/Display_Page.html', context)
return render(request,'ToDo_Files/Display_Page.html',context )
#login_required(login_url='Login-Page')
def remove(request, To_DO_Fun_id):
if request.user.is_superuser:
item = To_DO_Fun.objects.get(pk=To_DO_Fun_id)
item.delete()
messages.success(request, ('Task Deleted.'))
return redirect('Display-Page')
else:
return redirect('Logout-Page')
#login_required(login_url='Login-Page')
def data(request, To_DO_Fun_id):
if request.method == "POST":
item_all = To_DO_Fun.objects.get(pk=To_DO_Fun_id)
form = Form_Task(request.POST, instance= item_all)
if form.is_valid():
form.save()
messages.success(request, ("Task Updated."))
return redirect('Display-Page')
else:
item_all = To_DO_Fun.objects.get(pk=To_DO_Fun_id)
return render(request, 'ToDo_Files/details.html', {'item_all' : item_all})
return redirect('Display-Page')
#login_required(login_url='Login-Page')
def Done_status(request, To_DO_Fun_id):
item = To_DO_Fun.objects.get(pk=To_DO_Fun_id)
item.Task_Done = True
item.save()
messages.success(request, ("Congratulations."))
return redirect('Display-Page')
#login_required
def Pen_status(request, To_DO_Fun_id):
item = To_DO_Fun.objects.get(pk=To_DO_Fun_id)
item.Task_Done = False
item.save()
return redirect('Display-Page')
# def change_status(request, To_DO_Fun_id):
# Task_Done = request.GET.get('active', False)
# To_DO_Fun_id = request.GET.get('To_DO_Fun_id', False)
# # first you get your Job model
# task = To_DO_Fun.objects.get(pk=To_DO_Fun_id)
# try:
# task.Task_Done = Task_Done
# task.save()
# return JsonResponse({"Success": True})
# except Exception as e:
# return JsonResponse({"success": False})
# return JsonResponse('Display-Page')
def Reg_Fun(request):
if request.method == "POST":
UserReg_Form = UserCreationForm(request.POST)
if UserReg_Form.is_valid():
UserReg_Form.save()
return redirect('Login-Page')
else:
messages.error(request, ('USERNAME TAKEN'))
return redirect('Reg-Page')
else:
UserReg_Form = UserCreationForm(request.POST)
return render(request, "ToDo_Files/reg.html", {'UserReg_Form':UserReg_Form})
return redirect('Login-Page')
html for main page
{% extends 'ToDo_Files/base.html' %}
{% block asd %}
<title>Task</title>
{% if messages %}
<br>
{% for msg in messages%}
<div class="alert alert-info alert-dismissable" role="alert">
<button class="close" data-dismiss="alert">
<h4>☀</h4>
</button>
{{ msg }}
</div>
{% endfor %}
{% endif %}
<br>
<center><h5>WORK HARD <br> <i>{{ user.username }}</i></h5>
{% if all_items %}
<div>
<br>
{% if request.user.is_superuser %}
<table class="table table-bordered">
<thead class="thead-dark">
<tr>
<th><center><font color='#218838'>Task Name </font></center></th>
<th><center><font color='#218838'>Task Completion </font></center></th>
<th><center><font color='#218838'>Task Details </font></center></th>
<th><center><font color='#218838'>Task Author </font></center></th>
<th><center><font color='#218838'>Task Done </font></center></th>
</tr>
</thead>
{% for some in all_items %}
{% if some.Task_Done %}
<tr class="table-Success">
<td><center> <strong>{{ some.Task_Name }} </strong></center></td>
<td><center><a href='{% url 'Task-Pen' some.id %}'>Task Done</a></center></td>
<td><a href='{% url 'Task-Data' some.id %}'><center>Details </center></td>
<td><center> <strong>{{ some.owner }} </strong></center></td>
<td><center><a href='{% url 'Del-Page' some.id %}'>Remove</a></center></td>
</tr>
{% else %}
<tr class="table-default">
<td><center> <strong>{{ some.Task_Name }} </strong></center></td>
<td><center><a href='{% url 'Task-Done' some.id %}'>Task Pending </a></center></td>
<td><a href='{% url 'Task-Data' some.id %}'><center>Details </center></td>
<td><center> <strong>{{ some.owner }} </strong></center></td>
<td><center><a href='{% url 'Del-Page' some.id %}'>Remove</a></center></td>
</tr>
{% endif %}
{% endfor %}
</table>
{% else %}
<table class="table table-bordered">
<thead class="thead-dark">
<tr>
<th><center><font color='#218838'>Task Name </font></center></th>
<th><center><font color='#218838'>Task Completion </font></center></th>
<th><center><font color='#218838'>Task Details </font></center></th>
<th><center><font color='#218838'>Task Done </font></center></th>
</tr>
</thead>
{% for some in all_items %}
{% if some.Task_Done %}
<tr class="table-Success">
<td><center> <strong>{{ some.Task_Name }} </strong></center></td>
<td><center><a href='{% url 'Task-Pen' some.id %}'>Task Done</a></center></td>
<td><a href='{% url 'Task-Data' some.id %}'><center>Details </center></td>
<td><center><a href='{% url 'Del-Page' some.id %}'>Remove</a></center></td>
</tr>
{% else %}
<tr class="table-default">
<td><center> <strong>{{ some.Task_Name }} </strong></center></td>
<td><center><a href='{% url 'Task-Done' some.id %}'>Task Pending </a></center></td>
<td><a href='{% url 'Task-Data' some.id %}'><center>Details </center></td>
<td><center><a href='{% url 'Del-Page' some.id %}'>Remove</a></center></td>
</tr>
{% endif %}
{% endfor %}
{% endif %}
</div>
{% endif %}
{% endblock %}
Base.html
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<style>
body {
background-color:#fffff7;
}
</style>
<body >
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href='{% url 'Display-Page' %}'>Django</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<!----><!----><!----><!---->
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href='{% url 'Home-Page' %}'>Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item active">
<a class="nav-link" href='{% url 'Logout-Page' %}'>Logout<span class="sr-only">(current)</span></a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0" method="POST">
{% csrf_token %}
<input type="hidden" name="owner_id" value="{{request.user.id}}">
<input class="form-control mr-sm-2" type="search"placeholder="Add TO-DO" aria-label="Search" name="Task_Name">
<button class="btn btn-success my-2 my-sm-0" type="submit" >Add TODO</button>
</form>
</div>
</nav>
<div class="container">
{% block asd %}
{% endblock %}
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
html for the subtask
{% extends 'ToDo_Files/base.html' %}
{% block asd %}
<title>Task Details</title>
{% if item_all %}
<form class="form-inline my-2 my-lg-0" method="POST" action="">
{% csrf_token %}
<br> <br>
<input class="form-control mr-sm-2" placeholder='Subtask' aria-label="Search" name="subTask">
<br>
<button class="btn btn-success my-2 my-sm-2" type="submit" >Add</button>
</form>
<br><br><br>
{% endif %}
{% endblock %}
urls
from django.conf.urls import url
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^(?i)Home/', views.HomeFun, name='Home-Page'),
url(r'^(?i)Display/', views.Display_Page, name='Display-Page'),
url(r'^(?i)delete/(?P<To_DO_Fun_id>\d+)/$', views.remove, name='Del-Page'),
url(r'^(?i)details/(?P<To_DO_Fun_id>\d+)/$', views.data, name='Task-Data'),
url(r'^(?i)registraion/', views.Reg_Fun, name='Reg-Page'),
url(r'^(?i)login/', auth_views.LoginView.as_view(template_name='ToDo_Files/login.html'), name='Login-Page'),
url(r'^(?i)logout/', auth_views.LogoutView.as_view(template_name='ToDo_Files/logout.html'), name='Logout-Page'),
url(r'^(?i)Done/(?P<To_DO_Fun_id>\d+)/$', views.Done_status, name='Task-Done'),
url(r'^(?i)Pending/(?P<To_DO_Fun_id>\d+)/$', views.Pen_status, name='Task-Pen'),
]
I want to see a progress bar on the main page that shows how much % the task is done after comparing or getting input from the sub task checkbox.
also that I am able to add and remove new sub tasks in the sub tasks page where I can check the and uncheck any sub task.
Thank you in advance

Related

Django- Template not found

I can't seem to get my delete, edit and add review functionality working. The errors come as soon as I try to navigate to the urls I have set up. When I try and add a new review using my link on the reviews page I get the below message:
TemplateDoesNotExist at /reviews/add
I don't understand why because I have linked the url above to the template, which I have created.
The issue I have with my edit/delete views is that the url it searches for when I click the button is just /edit/ or /delete/ rather than reviews/edit/int:pk or reviews/delete/int:pk as per my urls.
I have pasted my code below, any help would be much appreciated! I have the feeling I am going to kick myself when I realise!
reviews.html:
{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="container-fluid home-container">
<div class="row align-items-center">
<div class="col-sm-12 text-center mt-4">
<h2><strong>Reviews</strong></h2>
</div>
</div>
{% for review in reviews %}
<hr class="hr-1">
<div class="row featurette">
<div class="col-sm-12">
<h2 class="featurette-heading">{{ review.title }}</h2>
<p class="lead">{{ review.content }}</p>
<div class="row justify-content-between mx-1">
<p>By: {{ review.user }}</p>
<p>Created on: {{ review.created }}</p>
<p>Last Updated: {{ review.updated }}</p>
</div>
<!-- Add user authentication if -->
<div class="text-center">
<a href="edit/{{ review.id }}" class="mx-2">
<button class="positive-button mb-2">Edit</button></a>
<a href="delete/{{ review.id }}" class="mx-2 mb-2">
<button class="negative-button">Delete</button></a>
</div>
</div>
</div>
{% endfor %}
<div class="row">
<div class="col-sm-12 text-center py-4">
{% if user.is_authenticated %}
<a href="{% url 'home:add_review' %}">
<button class="positive-button-lg">Add a review</button>
</a>
{% else %}
<p>If you would like to add your own review, please login or sign up if you haven't already!</p>
{% endif %}
</div>
</div>
</div>
{% endblock %}
add_review.html:
{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-auto text-center p-3">
<form method="post" style="margin-top: 1.3em;">
{{ review_form }}
{% csrf_token %}
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</form>
</div>
</div>
{% endblock %}
views.py:
from django.shortcuts import render
from django.views import View
from django.urls import reverse_lazy
from django.views.generic import UpdateView, DeleteView
from .models import Reviews
from .forms import ReviewForm
def home(request):
''' Returns the home page.'''
return render(request, 'home/index.html')
def reviews(request):
''' Returns the reviews page.'''
serialized_reviews = []
reviews = Reviews.objects.all()
for review in reviews:
serialized_reviews.append({
"title": review.title,
"content": review.content,
"user": review.user,
"created": review.created,
"updated": review.updated,
})
context = {
"reviews": serialized_reviews
}
print(serialized_reviews)
return render(request, 'home/reviews.html', context)
class AddReview(View):
'''View which allows the user to add a new review.'''
def get(self, request, *args, **kwargs):
review = Reviews
review_form = ReviewForm
context = {
'review': review,
'review_form': review_form,
'user': review.user,
'title': review.title,
'content': review.content,
}
return render(request, 'add_review.html', context)
def post(self, request, *args, **kwargs):
review_form = ReviewForm(data=request.POST)
if review_form.is_valid():
obj = review_form.save(commit=False)
obj.user = request.user
obj.save()
return redirect("home:reviews")
class DeleteReview(DeleteView):
'''View which allows the user to delete the selected review.'''
model = Reviews
template_name = 'delete_review.html'
success_url = reverse_lazy('reviews')
class EditReview(UpdateView):
'''View which allows the user to edit the selected review.'''
model = Reviews
template_name = 'edit_review.html'
fields = ['title', 'content']
urls.py:
from django.urls import path
from . import views
app_name = 'home'
urlpatterns = [
path('', views.home, name='home'),
path('reviews', views.reviews, name='reviews'),
path('reviews/add', views.AddReview.as_view(), name='add_review'),
path('reviews/delete/<int:pk>', views.DeleteReview.as_view(), name='delete_review'),
path('reviews/edit/<int:pk>', views.EditReview.as_view(), name='edit_review'),
]
The main difference is my app name, which is 'core'. Also, I forgot to add the content field to the model, but that is easily done, the form will just handle it as soon as you do the migration. (except on list.html)
models.py
from django.db import models
from django.contrib.auth import get_user_model
from django.utils import timezone
class Reviews(models.Model):
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
title = models.CharField(max_length=128)
created_at = models.DateTimeField(auto_now_add=timezone.now())
updated_at = models.DateTimeField(auto_now=timezone.now())
forms.py
from django import forms
from core.models import Reviews
class ReviewsForm(forms.ModelForm):
class Meta:
model = Reviews
fields = '__all__'
views.py
from core.models import Reviews
from core.forms import ReviewsForm
from django.shortcuts import render, redirect
def list_reviews(request):
reviews = Reviews.objects.all()
context = {
"reviews": reviews
}
return render(request, 'reviews/list.html', context)
def add_review(request):
if request.method == 'POST':
form = ReviewsForm(request.POST)
if form.is_valid():
form.save()
return redirect('/reviews/')
else:
form = ReviewsForm()
context = {
'form': form
}
return render(request, 'reviews/detail.html', context)
def edit_review(request, pk):
if request.method == 'POST':
form = ReviewsForm(request.POST)
if form.is_valid():
obj = Reviews.objects.get(id=pk)
obj.title = form.cleaned_data['title']
obj.user = form.cleaned_data['user']
obj.save()
return redirect('/reviews/')
else:
obj = Reviews.objects.get(id=pk)
form = ReviewsForm(instance=obj)
context = {
'form': form
}
return render(request, 'reviews/detail.html', context)
def delete_review(request, pk):
obj = Reviews.objects.get(id=pk)
obj.delete()
return redirect('/reviews/')
urls.py
from django.urls import path
import core.views as views
app_name = 'core'
urlpatterns = [
path('reviews/', views.list_reviews, name='list-reviews'),
path('reviews/add', views.add_review, name='add-review'),
path('reviews/edit/<int:pk>/', views.edit_review, name='edit-review'),
path('reviews/delete/<int:pk>/', views.delete_review, name='delete-review'),
]
list.html
{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="container-fluid home-container">
<div class="row align-items-center">
<div class="col-sm-12 text-center mt-4">
<h2><strong>Reviews</strong></h2>
</div>
</div>
{% for review in reviews %}
<hr class="hr-1">
<div class="row featurette">
<div class="col-sm-12">
<h2 class="featurette-heading">{{ review.title }}</h2>
<p class="lead">{{ review.content }}</p>
<div class="row justify-content-between mx-1">
<p>By: {{ review.user }}</p>
<p>Created on: {{ review.created_at }}</p>
<p>Last Updated: {{ review.updated_at }}</p>
</div>
<!-- Add user authentication if -->
<div class="text-center">
<a href="{% url 'core:edit-review' pk=review.id %}" class="mx-2">
<button class="positive-button mb-2">Edit</button></a>
<a href="{% url 'core:delete-review' pk=review.id %}" class="mx-2 mb-2">
<button class="negative-button">Delete</button></a>
</div>
</div>
</div>
{% endfor %}
<div class="row">
<div class="col-sm-12 text-center py-4">
{% if user.is_authenticated %}
<a href="{% url 'core:add-review' %}">
<button class="positive-button-lg">Add a review</button>
</a>
{% else %}
<p>If you would like to add your own review, please login or sign up if you haven't already!</p>
{% endif %}
</div>
</div>
</div>
{% endblock %}
detail.html
{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-auto text-center p-3">
<form method="post" style="margin-top: 1.3em;">
{% csrf_token %}
<table>
{{ form }}
</table>
<button type="submit" class="btn btn-primary btn-lg">Save</button>
</form>
</div>
</div>
{% endblock %}
According to your urls, It is a review/edit/<int:pk>.
So you must add same thing in href tag.
Change this:
<a href="edit/{{ review.id }}"
To this:
<a href="review/edit/{{ review.id }}"
That's why you are getting that error
I've fixed it, firstly the path in my add_review view was wrong, which I have amended and it now works (thanks Ivan).
I also was not actually bringing the ID through on my 'reviews' view in the first place, so when following the links on my edit and review buttons, it didn't know what I meant by 'id', as I hadn't specified what that was in the view context.
Thanks for the help all!
I think you're writing in your urls the wrong way, like this below your div text-center:
<a href="edit/{{ review.id }}" class="mx-2">
It should be:
<a href="{% url 'yourappname:edit' review.id %}">

Django messages not showing up on redirects, only render

For a couple days now, I've been trying to figure out why my messages don't show up on redirects. All of the dependencies are there in my settings.py file as you can see. I don't think that's the problem because I am getting two messages to show up on signup and login if the user's passwords don't match on signup or if the user enters the wrong password on login. I notice it only works on renders, but not on redirects. I'll post an image of my file structure and also the relevant files next.
File structure images:
settings.py
from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
messages.DEBUG: 'alert-info',
messages.INFO: 'alert-info',
messages.SUCCESS: 'alert-success',
messages.WARNING: 'alert-warning',
messages.ERROR: 'alert-danger',
}
INSTALLED_APPS = [
...
'django.contrib.messages',
...
]
MIDDLEWARE = [
...
'django.contrib.sessions.middleware.SessionMiddleware',
...
'django.contrib.messages.middleware.MessageMiddleware',
...
]
TEMPLATES = [
...
'context_processors': [
...
'django.contrib.messages.context_processors.messages',
],
},
},
]
My urls.py in the main virtual_library folder
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from book.views import *
urlpatterns = [
path('admin/', admin.site.urls),
# Book paths
path('', include('book.urls')),
# Added Django authentication system after adding members app
path('members/', include('django.contrib.auth.urls')),
path('members/', include('members.urls')),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My urls.py in the book folder
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from .views import *
from book import views
urlpatterns = [
# Default path
path('', views.home, name='home'),
# Book paths
path('create/', views.createbook, name='createbook'),
path('current/', views.currentbooks, name='currentbooks'),
path('wanttoread/', views.wanttoreadbooks, name='wanttoreadbooks'),
path('currentlyreading/', views.currentlyreading, name='currentlyreading'),
path('read/', views.read, name='read'),
path('book/<int:book_pk>', views.viewbook, name='viewbook'),
path('book/<int:book_pk>/editbook', views.editbook, name='editbook'),
path('book/<int:book_pk>/viewonly', views.viewonly, name='viewonly'),
path('book/<int:book_pk>/delete', views.deletebook, name='deletebook'),
# Genres
path('genre/', AddGenreView.as_view(), name='addgenre'),
]
My urls.py in the members folder
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.contrib.auth import views as auth_views
from django.conf.urls.static import static
from members import views
from . import views
from .views import UserEditView, CreateProfilePageView, ShowProfilePageView, EditProfilePageView, PasswordsChangeView
urlpatterns = [
# User auth
path('signupuser/', views.signupuser, name='signupuser'),
path('loginuser/', views.loginuser, name='loginuser'),
path('logoutuser/', views.logoutuser, name='logoutuser'),
# User settings
path('edit_settings/', UserEditView.as_view(), name='edit_settings'),
# path('password/', auth_views.PasswordChangeView.as_view(template_name='registration/change_password.html')),
path('password/', PasswordsChangeView.as_view(template_name='registration/change_password.html')),
path('password_success/', views.password_success, name="password_success"),
# User profile
path('create_profile_page/', CreateProfilePageView.as_view(), name='create_profile_page'),
path('<int:pk>/edit_profile_page/', EditProfilePageView.as_view(), name='edit_profile_page'),
path('<int:pk>/profile/', ShowProfilePageView.as_view(), name='show_profile_page'),
]
base.html in the book folder
<div class="container mt-5">
{% for message in messages %}
<div class="container-fluid p-0">
<div class="alert {{ message.tags }} alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button> {{ message }}
</div>
</div>
{% endfor %} {% block content %}{% endblock %}
</div>
my currentbooks.html template to view user's books in the book folder
{% extends "book/base.html" %} {% load static %} { % block title % } Your Books { % endblock % } {% block content %}
<div class="row justify-content-center mt-5">
<div class="col-md-10">
<h1>{% if book_list %} {{ book_list.count }} total book{{ book_list.count|pluralize }} in your Mibrary...</h1>
</div>
</div>
<div class="row justify-content-center mt-5">
<div class="col-md-10">
{% if page_obj %}
<div class="container mt-1">
{% for book in page_obj %}
<div class="card-body">
{% if book.book_img %}
<img src="{{ book.book_img.url }}" alt="{{ book.title }}" class="img-fluid" style="height:150px; width:100px"> {% else %}
<img src="{% static 'book/images/logo.png' %}" alt="{{ book.title }}" class="img-fluid" style="height:150px; width:100px"> {% endif %}
<blockquote class="blockquote mt-3">
<a href="{% url 'viewonly' book.id %}">
<strong><p class="mb-0">{{ book.title|capfirst }}</p></strong>
</a>
<p class="mb-0">{% if book.summary %}{{ book.summary|truncatechars:80|safe }}{% endif %}</p>
</blockquote>
<footer class="blockquote-footer">by <cite title="Source Title">{{ book.author }}</cite></footer>
<small><p class="mb-0"><em>{{ book.user }}</em></p></small>
</div>
<hr> {% endfor %}
<div class="pagination">
<span class="step-links mr-2">
{% if page_obj.has_previous %}
« first
previous
{% endif %}
<span class="current mr-2">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}
</span> {% if page_obj.has_next %}
next
last » {% endif %}
</span>
</div>
</div>
{% endif %} {% else %}
<div class="row">
<div class="col mt-5">
<a role="button" class="btn btn-outline-primary btn-lg" href="{% url 'createbook' %}">Add book</a>
</div>
<div class="col">
<h2>You haven't added any books yet...</h2>
<br>
<img src="../static/book/images/reading-list.svg" class="img-fluid mt-3" style="width:400px;" alt="Responsive image" title="stack of books">
</div>
</div>
</div>
{% endif %} {% endblock %}
views.py for currentbooks
from django.contrib import messages
...
#login_required
def currentbooks(request):
book_list = Book.objects.filter(user=request.user)
paginator = Paginator(book_list, 2)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return render(request, 'book/currentbooks.html', {'page_obj': page_obj, 'book_list': book_list})
my createbook.html to add books in the book folder
{% extends 'book/base.html' %} {% block title %} Add Book{% endblock %} {% block content %}
<div class="container mt-5">
<h1>Create Book...</h1>
</div>
<div class="form-group mt-3">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %} {{ error }} {{ form.media }} {{ form.as_p }}
<button type="submit" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-outline-warning" onclick="$('#cancel').click()">Cancel</button>
</form>
<form style='display: none;' method="POST" action="{% url 'currentbooks' %}">
{% csrf_token %}
<button id="cancel" type="submit">Cancel</button>
</form>
</form>
</div>
{% endblock %}
My editbook.html view to delete in the book folder
{% extends "book/base.html" %} {% block title %} Edit Book {% endblock %} {% block content %} {% if user.id == book.user_id %}
<div class="container mt-5">
<h1>Edit Book...</h1>
{% if error %}
<div class="alert alert-danger" role="alert">
{{ error }}
</div>
{% endif %}
</div>
<div class="form-group mt-3">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %} {{ form.media }} {{ form.as_p }}
<button type="submit" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-warning" onclick="$('#cancel').click()">Cancel</button>
<button type="button" class="btn btn-danger" onclick="$('#delete').click()">Delete</button>
</form>
<form style='display: none;' method="POST" action="{% url 'deletebook' book.id %}">
{% csrf_token %}
<button id="delete" type="submit">Delete</button>
</form>
<form style='display: none;' method="POST" action="{% url 'currentbooks' %}">
{% csrf_token %}
<button id="cancel" type="submit">Cancel</button>
</form>
</div>
{% else %}
<div class="row justify-content-center mt-5">
<h1>You are not allowed to edit this book...</h1>
</div>
{% endif %} {% endblock %}
views.py in the book folder
from django.contrib import messages
...
# Create
#login_required
def createbook(request):
if request.method == 'GET':
form = BookForm()
return render(request, 'book/createbook.html', {'form': form})
else:
try:
form = BookForm(request.POST, request.FILES)
newbook = form.save(commit=False)
newbook.user = request.user
if form.is_valid():
newbook.save()
# This message does not show up under the redirect
messages.success(request, 'Book saved!')
return redirect('currentbooks')
except ValueError:
messages.error(request, 'Bad data passed in. Try again.')
return render(request, 'book/createbook.html', {'form':BookForm()})
# Delete
#login_required
def deletebook(request, book_pk):
book = get_object_or_404(Book, pk=book_pk, user=request.user)
if request.method == 'POST':
book.delete()
# This message does not show up under redirect
messages.info(request, 'Book deleted!')
return redirect('currentbooks')
My loginuser.html to login in the members folder
{% extends 'book/base.html' %} {% block title %} Login {% endblock %} {% block content %}
<div class="container">
<h1>User Login...</h1>
<div class="row">
<div class="col mt-5">
<form method="POST">
<div class="form-group">
{% csrf_token %} {{ error }}
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control" id="username" aria-describedby="usernameHelp">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" class="form-control" id="password">
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-outline-danger btn-lg">Sign In</button>
</div>
</form>
</div>
<div class="col">
<img src="../../static/book/images/studying.svg" class="img-fluid" alt="Responsive image" title="woman reading II">
</div>
</div>
</div>
{% endblock %}
views.py in the members folder
from django.shortcuts import render, redirect, get_object_or_404, HttpResponseRedirect
...
from django.contrib import messages
...
# Auth functions
def signupuser(request):
if request.method == 'GET':
return render(request, 'registration/signupuser.html', {'form':UserCreationForm()})
else:
if request.POST['password1'] == request.POST['password2']:
try:
user = User.objects.create_user(request.POST['username'], password=request.POST['password1'])
user.save()
login(request, user)
# This message does not show in the redirect
messages.success(request, 'User successfully created.')
return redirect('currentbooks')
except IntegrityError:
return render(request, 'registration/signupuser.html', {'form':UserCreationForm()})
else:
# This message does show up under render
messages.error(request, 'Passwords do not match.')
return render(request, 'registration/signupuser.html', {'form':UserCreationForm()})
def loginuser(request):
if request.method == 'GET':
return render(request, 'registration/loginuser.html', {'form':AuthenticationForm()})
else:
user = authenticate(request, username=request.POST['username'], password=request.POST['password'])
if user is None:
messages.error(request, 'Username and password do not match.')
# This message does show up under render
return render(request, 'registration/loginuser.html', {'form':AuthenticationForm()})
else:
login(request, user)
# This message does not show up under redirect
messages.success(request, 'Logged in successfully.')
return redirect('currentbooks')
#login_required
def logoutuser(request):
if request.method == 'POST':
logout(request)
# This message does not show up. I tried HttpResponseRedirect as a last option.
messages.success(request, 'Logged out successfully!')
return HttpResponseRedirect(reverse_lazy('loginuser'))
So ultimately, the messages don't seem to work with redirects, but they do work if I render and declare the folder and template name. Otherwise, no message displays if there is a redirect. I'm not quite sure what is wrong or why redirects are not working with these messages.
Matt Gleason's answer is incorrect, because messages framework doesn't store it in request object: https://docs.djangoproject.com/en/3.2/ref/contrib/messages/#storage-backends
Messages do work with redirects just fine out of the box. Check if everything is OK with your cookies (it's a default storage)

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

I'm getting this error when I use
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
but there is no such error when path is..
path('create_order', views.createOrder, name="create_order"),
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('products/', views.products, name='products'),
path('customer/<str:pk_test>/', views.customer, name="customer"),
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
path('update_order/<str:pk>/', views.updateOrder, name="update_order"),
path('delete_order/<str:pk>/', views.deleteOrder, name="delete_order"),
]
views.py
def createOrder(request, pk):
OrderFormSet = inlineformset_factory(Customer, Order , fields=('product','status'), extra=9)
customer = Customer.objects.get(id=pk)
formset = OrderFormSet(queryset=Order.objects.none(), instance=customer)
#form = OrderForm(initial={'customer':customer})
if request.method == 'POST':
#print('printing post', request.POST)
formset = OrderFormSet(request.POST, instance=customer)
if formset.is_valid():
formset.save()
return redirect('/')
context = {'formset': formset}
#return redirect('accounts/order_form.html', context)
return render(request, 'accounts/order_form.html', context)
i also have tried redirect, that's not working the problem is with urls.py.
customer.html
{% extends 'accounts/main.html' %}
{% block content %}
<br>
<div class="row">
<div class="col-md">
<div class="card card-body">
<h5>Customer:</h5>
<hr>
<a class="btn btn-outline-info btn-sm btn-block" href="">Update Customer</a>
<a class="btn btn-outline-info btn-sm btn-block" href="{% url 'create_order' customer.id %}">Place Order</a>
</div>
</div>
<div class="col-md">
<div class="card card-body">
<h5>Contact Information</h5>
<hr>
<p>Email: {{customer.email}}</p>
<p>Phone: {{customer.phone}}</p>
</div>
</div>
<div class="col-md">
<div class="card card-body">
<h5>Total Order</h5>
<hr>
<h1 style="text-align: center;padding: 10px;">{{order_count}}</h1>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col">
<div class="card card-body">
<form method="POST">
<button class="btn btn-primary" type="submit">Search</button>
</form>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-md">
<div class="card card-body">
<table class="table table-sm">
<tr>
<th>Product</th>
<th>Category</th>
<th>Date Ordered</th>
<th>Status</th>
<th>Update</th>
<th>Remove</th>
</tr>
{% for order in orders %}
<tr>
<td>{{order.product}}</td>
<td>{{order.product.category}}</td>
<td>{{order.date_created}}</td>
<td>{{order.status}}</td>
<td><a class="btn btn-outline-info btn-md " href="{% url 'update_order' order.id %}">Update</a></td>
<td><a class="btn btn-outline-danger btn-md " href="{% url 'delete_order' order.id %}">Delete</a></td>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock %}
models.py
class Customer(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
phone = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.name
order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<div class="row">
<div class="col-md-6">
<div class="card card-body">
<form action="" method="POST">
{% csrf_token %}
{{formset.managment_form}} <!-- to remove the managmentForm data missing or has been tempered wiith , error -->
{% for form in formset %}
{{formset}} <!--in context of views.py -->
<hr>
{% endfor %}
<input class="btn btn-outline-success btn-md" type="submit" name="submit">
</form>
</div>
</div>
</div>
{% endblock %}
I have added the templates , and thanks to all but I think the only problem is with urls.py , because if I use
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
instead of
path('create_order', views.createOrder, name="create_order"),
then I get error, otherwise there is no such error for the above path.
I finally got the error.
So, error was here
the href which we have used id {% url 'create_order' customer.id %}
and this is in customer.html ,so the customer.id will get value provided by the views.customer
but if you see in your view.customer,
context = {'customers':customers,'orders': orders,'orders_count': orders_count}
because we followed a tutorial video, that guy did some changes which we didn't because it isn't shown in the video.
the changes he did was that
he changed 'customers' to 'customer' and now context of customer.html is good
because now it knows what the hell is customer.id
i know where the problem is
in the dashboard.html you should delete the line includes {% url 'create_order' %}
I don't know what is the problem but just replaced the file urls.py from GitHub with the same context and it's not showing that error.
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('products/', views.products, name='products'),
path('customer/<str:pk_test>/', views.customer, name="customer"),
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
path('update_order/<str:pk>/', views.updateOrder, name="update_order"),
path('delete_order/<str:pk>/', views.deleteOrder, name="delete_order"),
]
views.py
from django.forms import inlineformset_factory
def createOrder(request, pk):
OrderFormSet = inlineformset_factory(Customer, Order, fields=('product', 'status'), extra=10 )
customer = Customer.objects.get(id=pk)
formset = OrderFormSet(queryset=Order.objects.none(),instance=customer)
#form = OrderForm(initial={'customer':customer})
if request.method == 'POST':
#print('Printing POST:', request.POST)
#form = OrderForm(request.POST)
formset = OrderFormSet(request.POST, instance=customer)
if formset.is_valid():
formset.save()
return redirect('/')
context = {'form':formset}
return render(request, 'accounts/order_form.html', context)
order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<div class="row">
<div class="col-md-6">
<div class="card card-body">
<form action="" method="POST">
{% csrf_token %}
{{ form.management_form }}
{% for field in form %}
{{field}}
<hr>
{% endfor %}
<input type="submit" name="Submit">
</form>
</div>
</div>
</div>
{% endblock %}
Again I don't know why it was showing this error and where was the problem but just relapced it with the same code from GitHub and it worked.if someone know how it worked, that will be really helpful in near future.
in dashboard you should remove the line with create order
cause there is use of create_order url without id so there's an error

Searchbar in Django not working: like query is not executed

I am developing an app in Django.
I have contents of a database displayed on my template glossario.html ad I want to implement a search bar to query the database and display only the query results.
So I have set up the toolbar in glossario.html
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<div class="topnav">
<a id="pulsante_ricerca_avanzata" href="#Ricerca_avanzata">Ricerca avanzata</a>
<div id="blocco_ricerca_semplice" class="search-container">
<form method="GET" action="{% url 'glossario' %}">
<input type="text" placeholder="Ricerca terminologia..." name="q" value="{{request.GET.q}}">
<button id="cancel_search_button" type=""><i class="fa fa-trash"></i></button>
<button id="search_button" type="submit"><i class="fa fa-search"></i></button>
</form>
</div>
</div>
In views.py have prepared a function to show only the query results:
def vista_ricerca_semplice(request):
template = "glossario.html"
query = request.GET.get('q')
selected_entries = glossary_entry.objects.filter(Q(Lemma_it__icontains=query))
context = {'selected_entries':selected_entries}
return render(request, template, context)
Note: Lemma_it is the field of my model I want to search and glossary_entry is the name of my model
To tell the truth I am looking for a command to do the query on all the model fields without typing
selected_entries = glossary_entry.objects.filter(Q(Lemma_it__icontains=query) | Q(field2__icontains=query) | Q(field3__icontains=query) ...)
In app/urls.py I have mapped the url of the search results:
from django.urls import path
from . import views
from .views import vista_ricerca_semplice
urlpatterns=[
path('', views.home, name='home'),
path('glossario', views.glossario, name="glossario"),
path('glossario', views.vista_ricerca_semplice, name="vista_ricerca_semplice"),
]
But it simply does not work.
If for example I type "attempt1", the console returns
[19/Sep/2019 18:08:00] "GET /glossario?q=attempt1 HTTP/1.1" 200 126941
And it updates the page but there is no query. The view does not change.
What's the error here?
I have been working on a similar project like yours but mine is a school management system.
I have implemented a search bar and it is working perfectly.
in views.py
def search_student(request):
student_list = DataStudent.objects.all()
student_filter = StudentFilter(request.GET, queryset=student_list)
return render(request, 'accounts/Students/Search/student_list.html', {'filter': student_filter})
and in urls.py
from django.conf.urls import url, include
from . import views
urlpatterns=[
url(r'^search_student', views.search_student, name="search_student")
]
in student_list.html
{% extends 'base.html' %}
{% block body %}
<div class="container" style="margin-left: 200px;font-size: 20px; padding: 0px 10px;">
{% load crispy_forms_tags %}
<form method="get">
<nav class="container nav navbar-expand navbar" >
<div style="color:black; font-size:160%">
<ul class="navbar-nav mr-auto" >
<li class="nav-item">
{{ filter.form.name|as_crispy_field }}
</li>
<li class="nav-item">
{{ filter.form.Class|as_crispy_field }}
</li>
<li class="nav-item">
{{ filter.form.stream|as_crispy_field }}
</li>
<li style="margin-left:5%"> <button type="submit" style="margin-top:60%;" class="btn btn-primary">Search </button>
</li>
</ul>
</div>
</nav>
</form>
<ul>
<div class="container" style="margin-left:2px; font-size:15px; padding:3px">
<table class="table table-hover" border="2">
<thead class="table-success">
<tr>
<td>Reg Number</td>
<td>Photo</td>
<td>Name</td>
<td>Class</td>
<td>Stream</td>
<td>Admision No</td>
<td>Action</td>
</tr>
</thead>
<tbody>
{% for student in filter.qs %}
<tr>
<td>{{ student.admission_no}}</td>
<td>{% if student.Student_Photo %}<img src="{{ student.Student_Photo.url}}" width="50">{% endif %}</td>
<td>{{ student.name}}</td>
<td>{{ student.Class}}</td>
<td>{{ student.stream}}</td>
<td>{{ student.admission_no}}</td>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<td><a class="btn btn-primary a-btn-slide-text" href="{% url 'singlestudentdetails' pk=student.id %}"><span class="glyphicon glyphicon-eye-open" aria-hidden="true"></span>
<span><strong>View</strong></span></a>
<a class="btn btn-danger a-btn-slide-text" href="{% url 'deletestudent' pk=student.id %}"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
<span><strong>Delete</strong></span> </a>
</td>
{% endfor %}
</tr>
</tbody>
</table>
</div>
</div>
{% endblock %}
I hope this helps you fellow dev, happy coding
SOLVED
As pointed by ,the problem was that I had two views functions pointing at the same path (template).
This cannot be. One template/path cannot be pointed by more than one view function.
So I eliminated all the code related to my previous view function vista_ricerca_semplice
I solved my problem by changing code in urls.py and views.py like this:
In views.py:
def glossario(request):
query = request.GET.get('q')
template = "glossario.html"
# query executed
if query:
query = request.GET.get('q')
selected_entries = glossary_entry.objects.filter(Q(Lemma_it__icontains=query))
return render(request, template, {'all_entries':selected_entries})
# no query
else:
all_entries = glossary_entry.objects.all
return render(request, template, {'all_entries':all_entries})
In Urls.py
urlpatterns=[
path('', views.home, name='home'),
path('glossario', views.glossario, name="glossario"),
]

How load to Django Paginator Page (next/ previous)?

Hy,
i followed a tutorial for a multiple model search and it worked. now i want to paginate the output. But how can i load my paginator page (next/ previous) data into my template? So far if i push next i get an error.
views.py
from django.views.generic import TemplateView, ListView
from django.views.generic import View
from django.shortcuts import render
from django.db.models import Q
from django.core.paginator import Paginator
from itertools import chain
# --- Import Models
from datainput.models import Animal
from datainput.models import Farmer
<....>
class SearchView(ListView):
template_name = 'farmapi/searchview.html'
paginate_by = 2
count = 0
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['count'] = self.count or 0
context['query'] = self.request.GET.get('q')
return context
def get_queryset(self):
request = self.request
query = request.GET.get('q', None)
if query is not None:
farmer_results = Farmer.objects.search(query)
animal_results = Animal.objects.search(query)
# combine querysets
queryset_chain = chain(
farmer_results,
animal_results
)
qs = sorted(queryset_chain,
key=lambda instance: instance.pk,
reverse=True)
self.count = len(qs) # since qs is actually a list
return qs
return Farmer.objects.none() # just an empty queryset as default
template.html
{% extends 'base.html' %}
{% load class_name %}
{% load static %}
{% block custom_css %}
<link rel="stylesheet" type="text/css" href="{% static 'css/home_styles.css' %}">
{% endblock %}
{% block content %}
<div style="height: 10px;">
</div>
<div class="container-fluid">
<div class='row'>
<div class="col-4 offset-md-8">
<form method='GET' class='' action='.'>
<div class="input-group form-group-no-border mx-auto" style="margin-bottom: 0px; font-size: 32px;">
<span class="input-group-addon cfe-nav" style='color:#000'>
<i class="fa fa-search" aria-hidden="true"></i>
</span>
<input type="text" name="q" data-toggle="popover" data-placement="bottom" data-content="Press enter to search" class="form-control cfe-nav mt-0 py-3" placeholder="Search..." value="" style="" data-original-title="" title="" autofocus="autofocus">
</div>
</form>
</div>
</div>
</div>
<div style="height: 10px;">
</div>
<div class="container-fluid">
<div class="row">
<div class="col-6 offset-md-4">
{% for object in object_list %}
{% with object|class_name as klass %}
{% if klass == 'Farmer' %}
<div class='row'>
Farmer: <a href='{{ object.get_absolute_url }}'> {{ object.first_name }} {{ object.last_name }}</a>
</div>
{% elif klass == 'Animal' %}
<div class='row'>
Animal: <a href='{{ object.get_absolute_url }}'> {{ object.name }} {{ object.species }}</a>
</div>
{% else %}
<div class='row'>
<a href='{{ object.get_absolute_url }}'>{{ object }} | {{ object|class_name }}</a>
</div>
{% endif %}
{% endwith %}
{% empty %}
{% endfor %}
<div style="height: 10px;">
</div>
<div class='row'>
<results>{{ count }} results for <b>{{ query }}</b></results>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<!-- Pagniator Data -->
<div class="paginator">
<span class="step-links">
<span class="current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_previous %}
« first
previous
{% endif %}
{% if page_obj.has_next %}
next
last »
{% endif %}
</span>
</div>
</div>
{% endblock %}
if i my template shows me for instance "4 Results for xyz" and "Page 1 of 2" and i push next or last Page, then i get this Error Message:
Page not found (404) Request Method: GET Request URL:
http://127.0.0.1:8000/data/searchview/?page=2 Raised by:
farmapi.views.SearchView
Invalid page (2): That page contains no results
So as far as i understand i have to explicit paginate the return of my queryset so that the paginator will put it into? Or did i miss to set a request for the paginator?
I also use a paginator where the number of items per page can be defined by the user. I added following method:
def get_paginate_by(self, queryset):
limit = int(self.request.POST.get('limit', 25))
return limit
In the template it looks like:
{% if is_paginated %}
{{ page_obj|render_paginator }}
{% endif %}
where render_paginator a template tag is.
In your template call a url like: your_url?page=2