Run middleware for specific links - python

do I'm trying to write the code for a social media website. I need every use link to be checked, for e.g. if the user has no followers, turn the number to 0, and if it has no followings, turn it back to 0. it works fine for certain users, but creates issues with some other ones, I will put my code below.
*UserFollowing is a model which determines who follows who.
models:
`class UserFollowing(models.Model):
user = models.ForeignKey(User, related_name="following",on_delete=models.CASCADE)
following_user= models.ForeignKey(User, related_name="followers",on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)`
URLS:
from django.urls import path
from . import views
from.views import CreatePost
urlpatterns = [
path('explore/', views.Listexplore.as_view(), name='page-explore'),
path('user/<str:username>/', views.UserList.as_view(), name='user-posts'),
path('post/<int:pk>/', views.DetailPost.as_view(), name='post-detail'),
path('post/<int:pk>/update/', views.UpdatePost.as_view(), name='post-update'),
path('post/<int:pk>/delete/', views.DeletePost.as_view(), name='post-delete'),
path('post/create/', CreatePost.as_view(), name='post-create'),
path('about/',views.about,name='page-about'),
path('home/',views.Listhome.as_view(),name='page-home'),
path('tests/',views.test,name="page-test"),
]
view:
def post(self, request,**kwargs):
user2 = get_object_or_404(User, username=self.kwargs.get("username"))
try:
UserFollowing.objects.get(following_user=user2, user=request.user)
created = UserFollowing.objects.get(following_user=user2, user=request.user)
created.delete()
request.user.profile.follower -= 1
user2.profile.following -= 1
request.user.save()
user2.save()
except UserFollowing.DoesNotExist :
created = UserFollowing.objects.create(following_user=user2, user=request.user)
request.user.profile.follower += 1
user2.profile.following += 1
created.save()
request.user.save()
user2.save()
return redirect(request.META['HTTP_REFERER'])
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get("username"))
return post.objects.filter(author=user).order_by("-time")
def get_context_data(self, **kwargs):
context = super(UserList, self).get_context_data(**kwargs)
context['user2'] = get_object_or_404(User, username=self.kwargs.get("username"))
my_user= User.objects.get(username=self.request.user.username)
try:
UserFollowing.objects.get(following_user=context['user2'], user=my_user)
follow=True
except UserFollowing.DoesNotExist :
follow=False
context['follow']=follow
return context
the middleware i wrote:
from django.http.response import HttpResponseForbidden
from django.shortcuts import get_object_or_404
from django.http.response import HttpResponse
from django.http import HttpRequest
from .models import User,UserFollowing
def follow_middleware(get_response):
def middleware(request):
response = get_response(request)
if 'user' in request.path_info:
username=request.path_info.split('/')
username=username[2]
user2 = get_object_or_404(User, username=username)
if len(UserFollowing.objects.filter(following_user=user2)) == 0:
user2.profile.following = 0
if len(UserFollowing.objects.filter(user=user2)) == 0:
user2.profile.follower = 0
user2.save()
return response
return middleware
any help would be appreciated
edit:
i managed to fix the issue, the only problem is that if i delete all of the objects, the numbers reset only if I reload the page
what should I do?

Related

Django assign "score" to each "user"

I am trying to practice my skills with django as a beginner, I built this platform with users and quiz. If logged in, the user can take a quiz. My goal here is to print on the "user profile" page the scores of the tests he/she has taken. Do you have any suggestions on how I can link the score to the user? Or do you have any resource to follow?
account/forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class FormRegistrazione(UserCreationForm):
email = forms.CharField(max_length=30, required=True, widget=forms.EmailInput())
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
account/urls.py
from django.urls import path
from .views import registrazioneView
urlpatterns = [
path('registrazione/', registrazioneView, name='registration_view')
]
account/views.py
from django.shortcuts import render, HttpResponseRedirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from accounts.forms import FormRegistrazione
# Create your views here.
def registrazioneView(request):
if request.method == "POST":
form = FormRegistrazione(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
email = form.cleaned_data["email"]
password = form.cleaned_data["password1"]
User.objects.create_user(username=username, password=password, email=email)
user = authenticate(username=username, password=password)
login(request, user)
return HttpResponseRedirect("/")
else:
form = FormRegistrazione()
context = {"form": form}
return render(request, 'accounts/registrazione.html', context)
core/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.homepage, name='homepage'),
path("users/", views.UserList.as_view(), name='user_list'),
path("user/<username>/", views.userProfileView, name='user_profile'),
]
core/views.py
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.models import User
from django.views.generic.list import ListView
# Create your views here.
def homepage(request):
return render(request, 'core/homepage.html')
def userProfileView(request, username):
user= get_object_or_404(User, username=username)
context = {'user' : user}
return render(request, 'core/user_profile.html' , context)
class UserList(ListView):
model = User
template_name = 'core/users.html'
quiz/admin.py
from django.contrib import admin
from .models import Questions
# Register your models here.
admin.site.register(Questions)
quiz/models.py
from django.db import models
# Create your models here.
class Questions(models.Model):
CAT_CHOICES = (
('datascience', 'DataScience'),
('productowner', 'ProductOwner'),
('businessanalyst', 'BusinessAnalyst'),
#('sports','Sports'),
#('movies','Movies'),
#('maths','Maths'),
#('generalknowledge','GeneralKnowledge'),
)
question = models.CharField(max_length = 250)
optiona = models.CharField(max_length = 100)
optionb = models.CharField(max_length = 100)
optionc = models.CharField(max_length = 100)
optiond = models.CharField(max_length = 100)
answer = models.CharField(max_length = 100)
category = models.CharField(max_length=20, choices = CAT_CHOICES)
class Meta:
ordering = ('-category',)
def __str__(self):
return self.question
quiz/urls.py
from django.urls import path, re_path, include
from . import views
# urlpatterns = [
# path("quiz/", views.quiz, name='quiz'),
# path("questions/<choice>/", views.questions, name='questions'),
# path("result/", views.result, name='result'),
#
# ]
urlpatterns = [
re_path(r'^quiz', views.quiz, name = 'quiz'),
re_path(r'^result', views.result, name = 'result'),
re_path(r'^(?P<choice>[\w]+)', views.questions, name = 'questions'),
]
quiz/views.py
from django.shortcuts import render
# Create your views here.
from django.shortcuts import render
from .models import Questions
# Create your views here.
def quiz(request):
choices = Questions.CAT_CHOICES
print(choices)
return render(request,
'quiz/quiz.html',
{'choices':choices})
def questions(request , choice):
print(choice)
ques = Questions.objects.filter(category__exact = choice)
return render(request,
'quiz/questions.html',
{'ques':ques})
def result(request):
print("result page")
if request.method == 'POST':
data = request.POST
datas = dict(data)
qid = []
qans = []
ans = []
score = 0
for key in datas:
try:
qid.append(int(key))
qans.append(datas[key][0])
except:
print("Csrf")
for q in qid:
ans.append((Questions.objects.get(id = q)).answer)
total = len(ans)
for i in range(total):
if ans[i] == qans[i]:
score += 1
# print(qid)
# print(qans)
# print(ans)
print(score)
eff = (score/total)*100
return render(request,
'quiz/result.html',
{'score':score,
'eff':eff,
'total':total})
#
#
#
#
#
#
#
Maybe use a model to store user, questions and score is a good start.
quiz/models.py
class Quiz(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="quizs", on_delete=models.CASCADE)
question = models.ManyToManyField(Questions, related_name="quizs")
score = models.IntegerField()

Reverse for 'add_to_cart' with arguments '('',)' not found. 1 pattern(s) tried:

I am creating an ecommerce site. I have a product detail page that has a button on it which points to the method "add_to_cart". Add to cart requires an item_id pk in the URL, in order to add that item to the corresponding order_item to order object.
How can I send the item_id from the current productdetail page to the add_to_cart view within the ProductDetailView
Error:
Exception Value:
Reverse for 'add_to_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['checkout/add-to-cart/(?P<item_id>[-\\w]+)/$']
portal/views.py
from django.shortcuts import render, redirect
from django.shortcuts import render
from django.views.generic import CreateView, DetailView, ListView, RedirectView, UpdateView
from django.views import generic
from django.contrib.auth.decorators import login_required # This is to block pages to non users using function views
from django.contrib.auth.mixins import LoginRequiredMixin
from .forms import ProductForm, ContactForm
from .models import Product, Contact
from checkout.models import OrderItem, Order
from users.models import User, Profile
# Create your views here.
class ProductDetailView(generic.DetailView):
model = Product
template_name = 'portal/product_detail.html'
def get_context_data(self, **kwargs):
#item_id = self.kwargs['pk']
filtered_orders = Order.objects.filter(owner=self.request.user.user_profile, is_ordered=False)
current_order_products = []
if filtered_orders.exists():
user_order = filtered_orders[0]
user_order_items = user_order.items.all()
current_order_products = [product.product for product in user_order_items] #not sure what this does
context = {
'current_order_products': current_order_products
}
return context
portal/views.py
url(r'^product/(?P<pk>\d+)$', views.ProductDetailView.as_view(), name='product_detail'),
checkout/views.py
def add_to_cart(request, **kwargs):
#get the user Profile
user_profile = get_object_or_404(Profile, user=request.user)
#filter products for id
product = Product.objects.filter(id=kwargs.get('item_id', "")).first()
#check if the user already owns the product
if product in request.user.user_profile.merchandise.all():
messages.info(request, "You already own this product")
return redirect(reverse('product_list'))
#create OrderItem of the selected product
order_item, status = OrderItem.objects.get_or_create(product=product)
#create order associate with the user
user_order, status = Order.objects.get_or_create(owner=user_profile, is_ordered=False)
user_order.items.add(order_item)
if status:
#generate a reference code
user_order.ref_code = generate_order_id()
user_order.save()
#show confirmataion message and redirect to same page
messages.info(request, "item added to cart")
#return redirect(reverse('product_list'))
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
checkout/urls.py
url(r'^add-to-cart/(?P<item_id>[-\w]+)/$', views.add_to_cart, name='add_to_cart'),
EDIT:
It works for my ProductListView, that is not a CBV
def ProductListView(request):
model_list = Product.objects.filter(data_type="1")
script_list = Product.objects.filter(data_type="2")
filtered_orders = Order.objects.filter(owner=request.user.user_profile, is_ordered=False)
current_order_products = []
if filtered_orders.exists():
user_order = filtered_orders[0]
user_order_items = user_order.items.all()
current_order_products = [product.product for product in user_order_items]
context = {
'model_list': model_list,
'script_list': script_list,
'current_order_products': current_order_products
}
return render(request, "portal/product_list.html", context)

Django 127.0.0.1:8000/admin/ stopped working

Not sure what I've done to break the admin site, but going to 127.0.0.1:8000/admin/ is not working and gives me the error in the screenshot below:
Here's the two urls.py files:
myproject/urls.py
from django.conf.urls import include, url
from django.contrib import admin
import product_app.urls
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include(product_app.urls)),
]
and the product_app urls.py:
from django.conf.urls import url
from django.conf import settings
from django.views.static import serve
from . import views
from .views import *
urlpatterns = [
url(r'^$', views.HomePage.as_view(), name='home'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^subscribe/$', views.subscribe, name='subscribe'),
url(r'^products/$', views.products, name = 'products'),
url(r'^product/$', ProductListView.as_view(), name='product_list'),
url(r'^user/(\w+)/$', views.profile, name='profile'),
url(r'post_url/', views.post_product, name='post_product'),
url(r'^([0-9]+)/$', views.detail, name = 'detail'),
url(r'^login/$', views.login_view, name='Login'),
url(r'^logout/$', views.logout_view, name='Logout'),
url(r'^like_product/$', views.like_product, name='like_product' ),
url(r'^profile/edit/$', views.edit_profile, name='edit_profile'),
url(r'^(?P<pk>\d+)/edit/$', PostUpdateView.as_view(), name='product-edit'),
url(r'^(?P<pk>\d+)/delete/$', PostDeleteView.as_view(), name='product-delete'),
]
if settings.DEBUG:
urlpatterns += [
url(r'^product/(?P<path>.*)$', serve, {
'document_root': settings.MEDIA_ROOT,
}),
]
...and just in case, the models.py:
from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
def get_image_path(instance, filename):
return '/'.join(['product_images', str(instance.name), filename])
class Product(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=100)
description = models.CharField(max_length=300)
price = models.DecimalField(max_digits=10, decimal_places=2)
url = models.CharField(max_length=200)
product_type = models.CharField(max_length=100)
image = models.ImageField(upload_to='product_images', blank=True, null=True)
image_url = models.CharField(max_length=200, blank=True)
likes = models.IntegerField(default=0)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('index', kwargs={})
...finally, my views.py:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import UserCreationForm
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from .models import Product #, HashTag
from .forms import ProductForm, LoginForm, ContactForm, SubscribeForm, EditProfileForm
from django.views import generic
# edit / delete views
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.generic.edit import UpdateView, DeleteView
# contact and subscribe forms
from django.core.mail import EmailMessage
from django.template import Context
from django.template.loader import get_template
from django.contrib.auth import get_user_model
from . import forms
from django.shortcuts import render
from django.views.generic.list import ListView
class HomePage(generic.TemplateView):
template_name = "index.html"
def get_context_data(self, *args, **kwargs):
context=super(HomePage, self).get_context_data(*args, **kwargs)
context['form'] = ContactForm
return context
def products(request):
username = request.GET.get('username',None)
user = None
if username:
try:
user = User.objects.get(username=username)
except (User.DoesNotExist, User.MultipleObjectsReturned):
pass
if user:
return Product.objects.filter(user=user)
else:
products = Product.objects.all()
form = ProductForm()
return render(request, 'products.html', {'products': products, 'form':form})
class ProductListView(ListView):
template_name = 'product_list.html'
context_object_name = 'product_list'
paginate_by = None
def get_queryset(self):
username = self.request.GET.get('username',None)
user = None
if username:
try:
user = User.objects.get(username=username)
except (User.DoesNotExist, User.MultipleObjectsReturned):
pass
if user:
return Product.objects.filter(user=user)
return Product.objects.none()
def post_product(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = ProductForm(data = request.POST, files = request.FILES)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
product = form.save(commit = False)
product.user = request.user
product.likes = 0
product.save()
# redirect to a new URL:
return HttpResponseRedirect('/products')
def detail(request, product_id):
product = Product.objects.get(id=product_id)
#hashtags = HashTag.objects.filter(product=product_id)
return render(request, 'detail.html', {'product': product})
def profile(request, username):
user = get_object_or_404(User, username=username)
products = Product.objects.filter(user=user)
if not request.user == user:
return render(request, 'no.html')
else:
return render(request, 'profile.html', {'user':user,'products': products})
def edit_profile(request):
user = request.user
products = Product.objects.filter(user=user)
form = EditProfileForm(request.POST or None, initial={'first_name':user.first_name, 'last_name':user.last_name})
if request.method == 'POST':
if form.is_valid():
user.first_name = request.POST['first_name']
user.last_name = request.POST['last_name']
user.save()
return render(request, 'profile.html', {'user':user,'products': products})
context = {"form": form}
return render(request, "edit_profile.html", context)
def like_product(request):
product_id = request.POST.get('product_id', None)
likes = 0
if (product_id):
product = Product.objects.get(id=int(product_id))
if product is not None:
likes = product.likes + 1
product.likes = likes
product.save()
return HttpResponse(likes)
def login_view(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username=form.cleaned_data['username']
password=form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None:
# the password verified for the user
if user.is_active:
print("User is valid, active and authenticated")
login(request, user)
products = Product.objects.filter(user=user)
return render(request, 'profile.html', {'user':user,'products': products})
else:
print("The password is valid, but the account has been disabled!")
else:
# the authentication system was unable to verify the username and password
print("The username and password were incorrect.")
else:
form = LoginForm()
return render(request, 'login.html', {'form': form})
def logout_view(request):
logout(request)
return HttpResponseRedirect('/')
class PostUpdateView(UpdateView):
model = Product
form_class = ProductForm
template_name = 'edit_product.html'
def form_valid(self, form):
self.object = form.save(commit=False)
# Any manual settings go here
self.object.save()
# return HttpResponseRedirect(self.object.get_absolute_url())
return redirect ('products')
#method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(PostUpdateView, self).dispatch(request, *args, **kwargs)
class PostDeleteView(DeleteView):
model = Product
template_name = 'product_confirm_delete.html'
def get_success_url(self):
return reverse ('products')
#method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(PostDeleteView, self).dispatch(request, *args, **kwargs)
User = get_user_model()
def subscribe(request):
form_class = SubscribeForm
# new logic!
if request.method == 'POST':
form = form_class(data=request.POST)
if form.is_valid():
contact_name = request.POST.get('contact_name', '')
contact_email = request.POST.get('contact_email', '')
# Email the profile with the
# contact information
template = get_template('contact/subscribe_template.txt')
context = dict({'contact_name': contact_name, 'contact_email': contact_email,})
content = template.render(context)
email = EmailMessage(
"New subscribe form submission",
content,
"Your website" +'',
['steve#steve-shead.com'],
headers = {'Reply-To': contact_email }
)
email.send()
return render(request, 'contact/thank_you_subscribe.html')
return render(request, 'contact/subscribe.html', {
'form': form_class,
})
def contact(request):
form_class = ContactForm
# new logic!
if request.method == 'POST':
form = form_class(data=request.POST)
if form.is_valid():
contact_name = request.POST.get('contact_name', '')
contact_email = request.POST.get('contact_email', '')
form_content = request.POST.get('content', '')
# Email the profile with the
# contact information
template = get_template('contact/contact_template.txt')
context = dict({'contact_name': contact_name, 'contact_email': contact_email, 'form_content': form_content,})
content = template.render(context)
email = EmailMessage(
"New contact form submission",
content,
"Your website" +'',
['steve#steve-shead.com'],
headers = {'Reply-To': contact_email }
)
email.send()
return render(request, 'contact/thank_you.html')
return render(request, 'contact/contact.html', {
'form': form_class,
})
I have no clue what I changed to make the admin site not work - any help gratefully received!
Check your ROOT_URLCONF setting - it needs to be set to myproject.urls but looks like it is currently set to product_app.urls.

Django - How to allow only the owner of a new post to edit or delete the post?

I will be really grateful if anyone can help to resolve the issue below.
I have the following Django project coding. The problem is: when the browser was given "/posts/remove/<post_id>/" or "/posts/edit/(<post_id>/" as the url, it will allow the second user (not owner) to perform the remove and edit jobs, respectively.
How can I allow only the owner of a new post to edit or delete the post?
account.models.py:
from django.db import models
from django.conf import settings
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
def __str__(self):
return 'Profile for user {}'.format(self.user.username)
posts.models.py:
from django.db import models
from django.conf import settings
from django.utils import timezone
from django.utils.text import slugify
from django.core.urlresolvers import reverse
from taggit.managers import TaggableManager
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager, self).get_queryset().filter(status='published')
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name='posts_created')
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique_for_date='created')
image = models.ImageField(upload_to='images/%Y/%m/%d', null=True, blank=True)
description = models.TextField(blank=True)
created = models.DateTimeField(default=timezone.now,
db_index=True)
updated = models.DateTimeField(auto_now=True)
users_like = models.ManyToManyField(settings.AUTH_USER_MODEL,
related_name='posts_voted',
blank=True)
status = models.CharField(max_length=10, default='published')
objects = models.Manager() # The default manager.
published = PublishedManager() # The Dahl-specific manager.
tags = TaggableManager()
class Meta:
ordering = ('-created',)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('posts:detail', args=[self.id, self.slug])
posts.view.py:
from django.views.decorators.http import require_POST
from django.shortcuts import render, redirect, get_object_or_404, render_to_response
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.conf import settings
from django.core.context_processors import csrf
from .forms import PostCreateForm, EmailPostForm, CommentForm, SearchForm
from .models import Post
from actions.utils import create_action
#login_required
def post_create(request):
"""
View for creating a new post.
"""
if request.method == 'POST':
# form is sent
form = PostCreateForm(data=request.POST, files=request.FILES)
if form.is_valid():
cd = form.cleaned_data
new_item = form.save(commit=False)
# assign current user to the item
new_item.user = request.user
tags = form.cleaned_data['tags']
new_item.save()
for tag in tags:
new_item.tags.add(tag)
new_item.save()
create_action(request.user, 'created a post:', new_item)
messages.success(request, 'Post added successfully')
form = PostCreateForm()
else:
messages.error(request, 'Error adding new post')
else:
# build form
form = PostCreateForm(data=request.GET)
return render(request, 'posts/post/create.html', {'section': 'posts',
'form': form})
#login_required
def post_remove(request, post_id):
Post.objects.filter(id=post_id).delete()
return redirect('posts:mypost')
#login_required
def post_edit(request, post_id):
item = Post.objects.get(pk=post_id)
if request.method == 'POST':
form = PostCreateForm(request.POST, instance=item)
if form.is_valid():
form.save()
return redirect('posts:mypost')
else:
form = PostCreateForm(instance=item)
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('posts/post/post_edit.html', args)
posts.urls.py
from django.conf.urls import url
from . import views
from .feeds import LatestPostsFeed
urlpatterns = [
url(r'^create/$', views.post_create, name='create'),
url(r'^remove/(?P<post_id>\d+)/$', views.post_remove, name='post_remove'),
url(r'^edit/(?P<post_id>\d+)/$', views.post_edit, name='post_edit'),
]
Add request.user == item.user check inside your method.
#login_required
def post_remove(request, post_id):
item = Post.objects.get(pk=post_id)
if request.user == item.user:
Post.objects.filter(id=post_id).delete()
return redirect('posts:mypost')
#login_required
def post_edit(request, post_id):
item = Post.objects.get(pk=post_id)
if request.user == item.user:
...
//write your code here

Search Functionality on a Django Site

I'm trying to add a search function to my website but I'm having some issues. It's currently telling me that "Search" is not defined, but I have the class in my views file. This is what I have thus far:
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^player/(?P<pk>\d+)/$', views.player, name='player'),
url(r'^season/(?P<pk>\d+)/$', views.season, name='season'),
url(r'^seasons/$', views.seasons, name='seasons'),
url(r'^search/$', Search.as_view(), name='search'),
]
views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import ListView
from .models import Player, Season, PxS, Statistics
def home(request):
seasons = Season.objects.order_by('sid')
return render(request, 'webapp/home.html', {'seasons': seasons})
def player(request, pk):
player = get_object_or_404(Player, pk=pk)
return render(request, 'webapp/player.html', {'player': player, 'seasons': player.season_set.order_by('sid'), 'statistics': player.statistics_set.all()})
def season(request, pk):
season = get_object_or_404(Season, pk=pk)
return render(
request,
'webapp/season.html',
{'season': season, 'players': season.players.order_by('lastname')}
)
def seasons(request):
seasons = Season.objects.order_by('sid')
return render(request, 'webapp/seasons.html', {'seasons': seasons})
class Search(ListView):
template_name = 'search.html'
model = Player
context_object_name = 'list'
def get_context_data(self, **kwargs):
context = super(Search, self).get_context_data(**kwargs)
context['count'] = self.get_queryset().count()
return context
def get_queryset(self):
pobj = Player.objects.all()
var_get_search = self.request.GET.get('search_box')
var_get_order_by = self.request.GET.get('pid')
if var_get_search is not None:
pobj = pobj.filter(playername__icontains=var_get_search)
if var_get_order_by is not None:
pobj = pobj.order_by(var_get_order_by)
return pobj
Any insight is greatly appreciated. I'm kind of just piecing this stuff together little by little. Thanks!
The problem is in the urls.py
Give url(r'^search/$', views.Search.as_view(), name='search'),
instead of just Search.

Categories

Resources