Django Website - TemplateDoesNotExist at /edit/117/ - python

I'm using UpdateView to edit data using forms.
After cliking the Edit button a modal is being popped up with a few forms that can be edited and then after I edit and click confirm I get an error:
TemplateDoesNotExist at /edit/117/ (or other pk...)
DevOpsWeb/serverlist_form.html
Request Method: POST
Request URL: http://devopsweb:8000/edit/117/
Django Version: 1.11.6
Exception Type: TemplateDoesNotExist
Exception Value:
DevOpsWeb/serverlist_form.html
Why do I get this error?
Why when I get the modal the information of the PK is blank...?
Does anyone know any of these questions? I'm really stuck :(
Thank you!
view.py-
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.shortcuts import render, redirect
from django.template import RequestContext
from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView
from DevOpsWeb.forms import HomeForm
from DevOpsWeb.models import serverlist
from django.core.urlresolvers import reverse_lazy
from simple_search import search_filter
from django.db.models import Q
class HomeView(TemplateView):
template_name = 'serverlist.html'
def get(self, request):
form = HomeForm()
query = request.GET.get("q")
posts = serverlist.objects.all()
if query:
posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query))
else:
posts = serverlist.objects.all()
args = {'form' : form, 'posts' : posts}
return render(request, self.template_name, args)
def post(self,request):
form = HomeForm(request.POST)
posts = serverlist.objects.all()
if form.is_valid(): # Checks if validation of the forms passed
post = form.save(commit=False)
#if not form.cleaned_data['ServerName']:
#post.servername = " "
post.save()
#text = form.cleaned_data['ServerName']
form = HomeForm()
return redirect('serverlist')
args = {'form': form, 'text' : text}
return render(request, self.template_name,args)
class PostDelete(DeleteView):
model = serverlist
success_url = reverse_lazy('serverlist')
class PostEdit(UpdateView):
model = serverlist
#post = serverlist.objetcs.get(server_id=server_id)
fields = ['ServerName','Owner','Project','Description','IP','ILO','Rack','Status']
success_url=reverse_lazy('serverlist')
urls.py -
from django.conf.urls import url, include
from DevOpsWeb.views import HomeView
from DevOpsWeb.views import PostDelete
from DevOpsWeb.views import PostEdit
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
# Examples:
url(r'^$', HomeView.as_view(), name='serverlist'),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
#DevOpsWeb:8000/Delete/
url(r'^delete/(?P<pk>\d+)/$', PostDelete.as_view(), name="delete_post"),
url(r'^django_popup_view_field/', include('django_popup_view_field.urls', namespace="django_popup_view_field")),
url(r'^admin/', include(admin.site.urls)),
#DevOpsWeb:8000/edit/
url(r'^edit/(?P<pk>\d+)/$', PostEdit.as_view(), name="edit_post"),
]
forms.py -
from django import forms
from DevOpsWeb.models import serverlist
class HomeForm(forms.ModelForm):
ServerName = forms.CharField(widget=forms.TextInput,max_length = 30,required=False)
Owner = forms.CharField(max_length = 50,required=False)
Project = forms.CharField(max_length = 30,required=False)
Description = forms.CharField(max_length = 255,required=False)
IP = forms.CharField(max_length = 30,required=False)
ILO = forms.CharField(max_length = 30,required=False)
Rack = forms.CharField(max_length = 30,required=False)
Status = forms.CharField(max_length = 30,required=False)
class Meta:
model = serverlist
fields = ('ServerName' ,'Owner','Project','Description','IP','ILO','Rack','Status',)
class AutoCompleteModelChoiceField(forms.ModelChoiceField):
widget = forms.TextInput
def clean(self, value):
value = super(AutoCompleteModelChoiceField, self).clean(value)
return value
class serverForm(forms.ModelForm):
hotel = AutoCompleteModelChoiceField(queryset=serverlist.objects.all())
index.html (The part with the edit button)-
<div class="modal fade bd-example-modal-sm" id="Edit{{server.id}}" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit Server <b>{{ server.ServerName }}</b> </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="{% url 'edit_post' server.id %}" method="post"> {% csrf_token %}
<!--<center> {{ form.as_p }} </center> -->
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
<!-- {{ field.label_tag }} -->
<small><b>{{ field.html_name }}<p align="left"></b> {{ field }}</small> </p>
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
</div>
<div class="wrapper">
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
<h2><button type="submit" class="save btn btn-success btn-lg">Confirm</button></h2>&nbsp&nbsp&nbsp
<h2><button type="submit" class="btn btn-secondary btn-lg" data-dismiss="modal">Cancel</button></h2>
</div>
</form>
</td>
</div>
</tr>
{% endfor %}

Since you are not overriding one of UpdateView attributes, template_name_suffix, template_name or get_templates_names(), default template name that your view would be looking is <model_name>_form.html. And you don't have that template

Related

Django: child model edit comment not working

I got problem with my edit comments when i press the edit comment from the template i get no error but is redirected to the top of the same page. Anyone got any idea how i can get it to allow me to edit the comment?
This post is edited with only the code needed and i fixed the delete comment from before so that code is removed.
Here is my code:
views.py:
from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.db.models.functions import Lower
from .models import Product, Category, Review
from .forms import ProductForm, ReviewForm
def product_detail(request, product_id):
product = get_object_or_404(Product, pk=product_id)
if request.method == 'POST':
rating = request.POST.get('rating', 3)
content = request.POST.get('content', '')
Review.objects.create(
product=product,
rating=rating,
content=content,
created_by=request.user
)
# redirect to the same page
return redirect('product_detail', product_id=product_id)
reviews = Review.objects.filter(product=product)
context = {
'product': product,
'reviews': reviews
}
return render(request, 'products/product_detail.html', context)
#login_required
def edit_review(request, review_id):
"""
Saves review form edited by user
"""
review = get_object_or_404(Review, pk=review_id)
product = Product.objects.get(name=review.product)
if request.method == 'POST':
review_form = ReviewForm(request.POST or None, instance=review)
if review_form.is_valid():
review_form.save()
messages.success(request, 'Successfully updated product!')
return redirect(reverse('product_detail', args=[product.id]))
# Success message if added
messages.success(request, 'Thank You! Review was edited')
else:
# Error message if form was invalid
messages.error(request, 'Something went wrong. '
'Make sure the form is valid.')
form = ReviewForm(instance=review)
messages.info(request, f'You are editing {review_id}')
template = 'products/edit_review.html'
context = {
'form': form,
'product': review,
}
return redirect(reverse('product_detail', args=[product.id]))
models.py:
from django.db import models
from django.contrib.auth.models import User
class Review(models.Model):
product = models.ForeignKey(Product, related_name='reviews', on_delete=models.CASCADE)
rating = models.IntegerField(default=3)
content = models.TextField()
created_by = models.ForeignKey(User, related_name='reviews', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s - %s' % (self.product.name, self.created_by)
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.all_products, name='products'),
path('<int:product_id>/', views.product_detail, name='product_detail'),
path('add/', views.add_product, name='add_product'),
path('edit/<int:product_id>/', views.edit_product, name='edit_product'),
path('delete/<int:product_id>/', views.delete_product, name='delete_product'),
path('delete_review/<int:review_id>/delete_review', views.delete_review, name='delete-review'),
path('edit_review/<review_id>', views.edit_review, name="edit_review"),
]
forms.py:
from django import forms
from .widgets import CustomClearableFileInput
from .models import Product, Category, Review
class ReviewForm(forms.ModelForm):
class Meta:
model = Review
fields = ('content', 'rating')
widgets = {
'content': forms.Textarea(attrs={'class': 'form-control'}),
'rating': forms.Select(attrs={'class': 'form-control'}),
}
edit_review.html template
{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="overlay"></div>
<div class="container">
<div class="row">
<div class="col-12 col-md-6">
<hr>
<h2 class="logo-font mb-4">Reviews</h2>
<h5 class="text-muted">Edit you're Review</h5>
<hr>
</div>
</div>
<div class="row">
<div class="col-12 col-md-6">
<form method="POST" action="{% url 'edit_review' review.id %}" class="form mb-2" enctype="multipart/form-data">
{% csrf_token %}
{% for field in form %}
{% if field.name != 'image' %}
{{ field | as_crispy_field }}
{% else %}
{{ field }}
{% endif %}
{% endfor %}
<div class="text-right">
<a class="btn btn-outline-black rounded-0" href="{% url 'reviews' %}">Cancel</a>
<button class="btn btn-black rounded-0" type="submit">Update Review</button>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
for the first problem in the delete view you must refer to the model with capital Review
#login_required
def delete_review(request, review_id):
review = Review.objects.filter(review_id).last()
For the second problem you can see detailed information about this error and how to handle it, from Here

Django CBV ModelForm hx-post not working with HTMX

I have a partial form rendered with HTMX rendered in my page upload.html:
{% extends 'base.html' %}
<p>Veuillez choisir ci-dessous entre l'upload d'un fichier de commandes ou l'upload d'un fichier fournisseur :</p>
<h2>Upload fichier <u>transporteur</u></h2>
<button hx-get="{% url 'tool:upload-form' %}" hx-swap="afterend" hxtarget="#transporterforms">Add transporter</button>
<div class="transporterforms">
</div>
{% block content %}
And my upload-form.html:
<div hx-target="this" hx-swap="outerHTML">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
<button type="submit" hx-post=".">Submit</button>
</form>
</form>
</div>
Here is how I manage my form in views.py:
class TransporterFileFormPartialView(FormView):
form_class = TransporterFileForm
template_name = 'tool/upload-form.html'
success_url = '.'
def form_valid(self, form):
transporter_file = TransporterFile.objects.create(
file=form.cleaned_data['file'],
transporter=form.cleaned_data['transporter']
)
transporter_file_pk = transporter_file.pk
return super().form_valid(form)
class CompareFormView(CustomLoginRequiredMixin, RequestFormMixin, TemplateView):
""" View to show results of comparison between two files. """
template_name = 'tool/upload.html'
# success_url = '.'
def post(self, *args, **kwargs):
form = TransporterFileForm(self.request.POST)
if form.is_valid():
obj = form.save(commit=False)
# transporter_file = get_object_or_404(TransporterFile, pk=form.pk)
obj.save()
transporter_file = TransporterFile.objects.get(pk=obj.pk)
transporter_file_pk = transporter_file.pk
return redirect(reverse_lazy('tool:upload'))
And in my forms.py:
class TransporterFileForm(forms.ModelForm):
class Meta:
model = TransporterFile
fields = ('file', 'transporter')
My urls.py are as follows:
urlpatterns = [
path('', TemplateView.as_view(template_name="tool/home.html"), name="home"),
path('upload-form/', TransporterFileFormPartialView.as_view(), name="upload-form"),
path('upload-detail/<int:pk>', TransporterFileFormDetailView.as_view(), name="upload-detail"),
path('upload-detail/<int:pk>/delete/', TransporterFileFormDeleteView.as_view(), name="upload-delete"),
path('report/add-report', UserAddReportView.as_view(), name='add-report'),
path('report/add-report/2', CompareFormView.as_view(), name='upload'),
path('reports/', UserReportsView.as_view(), name='reports'),
]
My main issue is with upload-form.html. When I try
<button type="submit" hx-post=".">Submit</button>
It is not working. I have the following message:
[19/May/2022 15:00:05] "GET /upload-form/ HTTP/1.1" 200 896
Not Found: /report/add-report/
But when I try without hx-post, it is working
<button type="submit">Submit</button>
I cannot figure out why?
As the error message indicates, the /report/add-report/ path with a trailing slash does not exist, because you have defined it without trailing slash: path('report/add-report', UserAddReportView.as_view(), name='add-report'),. So you can just add the missing slash, or use the url function in the template to obtain the correct path of the endpoint:
<button type="submit" hx-post="{% url 'tool:add-report' %}">Submit</button>

The view budget.views.budget didn't return an HttpResponse object. It returned None instead

I recently added second form to my project and im struggling to make it work. The form is named AddIncome and when i fill the form and submit nothing happen, i don't see the new income. When i fill the income from admin panel on model page everthing works. Don't know how to make it work from main page.
Here is my view (second form that i added is b_form, a_form is working):
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.db.models import Sum
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.utils import timezone
from .forms import AddIncome, AddItem
from .models import BudgetData
#login_required
def budget(request):
expense_items = BudgetData.objects.filter(user_expense=request.user).order_by(
"-date_added"
)
# Setting up pagination per expense_items
paginator = Paginator(expense_items, 10, 3) # Show 10 items per page.
page_number = request.GET.get("page")
page_obj = paginator.get_page(page_number)
total_cost = BudgetData.objects.filter(user_expense=request.user).aggregate(
Sum("cost")
)
total_income = BudgetData.objects.filter(user_expense=request.user).aggregate(
Sum("income")
)
# AddItem{category, cost} form
a_form = AddItem()
b_form = AddIncome()
# form = AddItem(use_required_attribute=False) # ignores the field required text
if request.method == "POST" and "expense" in request.POST:
a_form = AddItem(request.POST)
if a_form.is_valid():
a_form = a_form.save(commit=False)
a_form.user_expense = request.user
a_form.date_added = timezone.now()
a_form.save()
return HttpResponseRedirect(reverse("budget"))
if request.method == "POST" and "income" in request.POST:
b_form = AddIncome(request.POST)
if b_form.is_valid():
b_form = b_form.save(commit=False)
b_form.user_expense = request.user
b_form.date_added = timezone.now()
b_form.save()
return HttpResponseRedirect(reverse("budget"))
return render(
request,
"budget/budget.html",
context={
"user": request.user,
"expense_items": expense_items,
"total_cost": total_cost,
"total_income": total_income,
"a_form": a_form,
"b_form": b_form,
"page_obj": page_obj,
},
)
The template section:
<section>
<div class="form-group">
<form method="post">
{% csrf_token %}
{{ b_form|crispy }}
<input name="income" type="submit" value="Add income">
</form>
</div>
<div class="form-group">
<form method="post">
{% csrf_token %}
{{ a_form|crispy }}
<input name="expense" type="submit" value="Add item">
</form>
</div>
{% for key, value in total_cost.items %}
<h1>Total expenses: {{value|floatformat:2}} zł</h1>
{% endfor %}
{% for key, value in total_income.items %}
<h1>Total income: {{value|floatformat:2}} zł</h1>
{% endfor %}
<h1>Diff: 500 zł</h1>
</section>

Django - Comments

I am new to Django and I'm having problems with comment forms. I just want to add a text field for comment on a specific Post's page, but it is hidden. Here is my models.py file in blog app:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
author = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
class Meta:
ordering = ['date_posted']
def __str__(self):
return '{} - {}'.format(self.author, self.date_posted)
forms.py:
from django import forms
from .models import Comment
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('content',)
views.py file:
from django.db import models
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.mixins import UserPassesTestMixin
from django.contrib.auth.models import User
from django.shortcuts import redirect, render
from django.shortcuts import get_object_or_404
from django.views.generic import ListView
from django.views.generic import DetailView
from django.views.generic import CreateView
from django.views.generic import UpdateView
from django.views.generic import DeleteView
from .forms import CommentForm
from .models import Post
from .models import Comment
def home(request):
context = {
'title': 'Home',
'posts': Post.objects.all()
}
return render(request, 'blog/home.html', context)
class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name='posts'
ordering = ['-date_posted']
paginate_by = 7
class UserPostListView(ListView):
model = Post
template_name = 'blog/user_posts.html'
context_object_name='posts'
paginate_by = 7
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get('username'))
return Post.objects.filter(author=user).order_by('-date_posted')
def post_detail(request, slug):
template_name = 'post_detail.html'
post = get_object_or_404(Post, slug=slug)
comments = post.comments.filter(active=True)
new_comment = None
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.post = post
new_comment.save()
else:
comment_form = CommentForm()
return render(request, template_name, {'post': post,
'comments': comments,
'new_comment': new_comment,
'form': comment_form})
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
fields = ['title', 'content']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Post
fields = ['title', 'content']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Post
success_url = '/'
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
def about(request):
return render(request, 'blog/about.html', {'title': 'About'})
and finally, the post_detail.html template where everything should be displayed:
{% extends 'blog/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user-posts' object.author.username %}">
{{ object.author }}
</a>
<small class="text-muted">{{ object.date_posted | date:"F d, Y" }}</small>
{% if object.author == user %}
<div>
<a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'post-update' object.id %}">Update</a>
<a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete</a>
</div>
{% endif %}
</div>
<h2 class="article-title">
{{ object.title }}
</h2>
<p class="article-content">{{ object.content }}</p>
</div>
</article>
<div>
<strong><h2>Comments Section</h2></strong>
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Leave A Comment</legend>
{{ form | crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Leave A Comment</button>
</div>
</form>
<ul>
{% for comment in object.comments.all %}
<div>
<img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
{{ comment.author }} - {{ comment.date_posted | date:"F d, Y" }}
<br>
{{ comment.content }}
</div>
{% endfor %}
</ul>
</div>
{% endblock content %}
I am stuck with the problem. Any suggestions are appreciated.

Django for loop is not showing my items on webpage

I have a table on my webpage that I want to iterate product information into and it worked up until I tried adding a paginator. The server runs fine and the rest of the website is functional.
Here are my files:
shop/products.html
{% extends 'base.html' %}
{% block content %}
<h1>On sale here</h1>
<div class="col-sm-3">
<h4>Categories</h4>
<ul class="list-group">
All Categories
{% for c in countcat %}
<a href="{{ c.get_absolute_url }}" class="list-group-item catheight">{{c.name}}
<span class="badge">{{c.num_products}}</span>
</a>
{% endfor %}
</ul>
</div>
<div class="col-sm-9">
<h4>Note that all products are second hand, unless otherwise stated.</h4>
<form class="form-inline my-2 my-lg-0" action="{% url 'search_result' %}" method="get">
{% csrf_token %}
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="q">
<button class="glyphicon glyphicon-search h-100" type="submit"></button>
</form>
<table class="table table-bordered table-hover table-condensed">
<thead>
<!-- The header row-->
<tr>
<th>ID</th>
<th>Name</th>
<th>Image</th>
<th>Category</th>
<th>Description</th>
<th>Stock</th>
<th>Price</th>
<th>Buy</th>
</tr>
</thead>
<tbody>
<!-- Product row(s) -->
{% for product in products %}
<tr>
<td>{{product.id}}</td>
<td>{{product.name}}</td>
{% if product.image %}
<td><img src="{{product.image.url}}"></td>
{% endif %}
<td>{{product.category}}</td>
<td>{{product.description}}</td>
<td>{{product.stock}}</td>
<td>€{{product.price}}</td>
{% if product.stock > 0 %}
<td><a href="{% url 'add_cart' product.id %}" class="btn btn-default btn-xs"><span
class="glyphicon glyphicon-shopping-cart"></span></a></td>
{% else %}
<td><a href="" class="btn btn-default btn-xs"><span
class="glyphicon glyphicon-warning-sign red"></span></a></td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
<hr>
<div class="text-center">
{% for pg in products.paginator.page_range %}
<a href="?page={{pg}}" class="btn btn-light btn-sm
{% if products.number == pg %}
active
{% endif %}">{{pg}}</a>
{% endfor %}
</div>
</div>
{% endblock content %}
shop/models.py
from django.db import models
from django.urls import reverse
class Category(models.Model):
name = models.TextField()
products = models.ManyToManyField('Product')
def get_products(self):
return Product.objects.filter(category=self)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('product_list_by_category',args=[self.id])
class Product(models.Model):
name = models.TextField()
description = models.TextField()
stock = models.IntegerField()
price = models.DecimalField(max_digits=10,decimal_places=2)
image = models.ImageField(upload_to='images/', blank=True)
def __str__(self):
return self.name
shop/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.product_list,
name='products'),
path('<int:category_id>/', views.product_list,
name='product_list_by_category'),
]
shop/views.py
from django.shortcuts import render, get_object_or_404, redirect
from .models import Category, Product
from django.db.models import Count
from django.contrib.auth.models import Group, User
from .forms import SignUpForm
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login, authenticate, logout
from django.core.paginator import Paginator, EmptyPage, InvalidPage
def product_list(request, category_id=None):
category = None
products = Product.objects.all()
ccat = Category.objects.annotate(num_products=Count('products'))
if category_id :
category = get_object_or_404(Category, id=category_id)
products = products.filter(category=category)
paginator = Paginator('products', 3)
try:
page = int(request.GET.get('page', 1))
except:
page = 1
try:
products = paginator.page(page)
except(EmptyPage, InvalidPage):
products = paginator.page(paginator.num_pages)
return render(request, 'products.html',
{'products': products,
'countcat':ccat})
def signupView(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get("username")
signup_user = User.objects.get(username=username)
customer_group = Group.objects.get(name= 'Customer')
customer_group.user_set.add(signup_user)
else:
form = SignUpForm()
return render(request, 'accounts/signup.html', {'form':form})
def signinView(request):
if request.method == 'POST':
form = AuthenticationForm(data=request.POST)
if form.is_valid():
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect('products')
else:
return redirect('signup')
else:
form = AuthenticationForm()
return render(request, 'accounts/signin.html', {'form':form})
def signoutView(request):
logout(request)
return redirect('signin')
I'm sort of a django noob so any help would be greatly appreciated, thanks :)
You are passing a string to Paginator here:
paginator = Paginator('products', 3)
You should pass an object_list:
paginator = Paginator(products, 3)

Categories

Resources