Search Functionality on a Django Site - python

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.

Related

Run middleware for specific links

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?

ImproperlyConfigured at /catalog/borrowed/

I'm a beginner in python-django coding. Currently I am trying to complete the challenge on https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication but I am facing
LoanedBooksByAllUserListView is missing the permission_required attribute. Define LoanedBooksByAllUserListView.permission_required, or override LoanedBooksByAllUserListView.get_permission_required().
In urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('books/', views.BookListView.as_view(), name='books'),
path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'),
path('authors/', views.AuthorListView.as_view(), name='authors'),
path('author/<int:pk>', views.AuthorDetailView.as_view(), name='author-detail'),
path('mybooks/', views.LoanedBooksByUserListView.as_view(), name='my-borrowed'),
path('borrowed/', views.LoanedBooksByAllUserListView.as_view(), name='all-borrowed'),
]
In views.py
from django.shortcuts import render
# Create your views here.
from .models import Book, Author, BookInstance, Genre
def index(request):
"""View function for home page of site."""
# Generate counts of some of the main objects
num_books = Book.objects.all().count()
num_instances = BookInstance.objects.all().count()
# Available books (status = 'a')
num_instances_available = BookInstance.objects.filter(status__exact='a').count()
# The 'all()' is implied by default.
num_authors = Author.objects.count()
# Number of visits to this view, as counted in the session variable.
num_visits = request.session.get('num_visits', 0)
request.session['num_visits'] = num_visits + 1
context = {
'num_books': num_books,
'num_instances': num_instances,
'num_instances_available': num_instances_available,
'num_authors': num_authors,
'num_visits': num_visits,
}
# Render the HTML template index.html with the data in the context variable.
return render(request, 'index.html', context=context)
from django.views import generic
class BookListView(generic.ListView):
model = Book
paginate_by = 5
class BookDetailView(generic.DetailView):
model = Book
class AuthorListView(generic.ListView):
model = Author
paginate_by = 5
class AuthorDetailView(generic.DetailView):
model = Author
from django.contrib.auth.mixins import LoginRequiredMixin
class LoanedBooksByUserListView(LoginRequiredMixin,generic.ListView):
"""Generic class-based view listing books on loan to current user."""
model = BookInstance
template_name ='catalog/bookinstance_list_borrowed_user.html'
paginate_by = 10
def get_queryset(self):
return BookInstance.objects.filter(borrower=self.request.user).filter(status__exact='o').order_by('due_back')
from django.contrib.auth.mixins import PermissionRequiredMixin
class LoanedBooksByAllUserListView(PermissionRequiredMixin,generic.ListView):
model = BookInstance
template_name ='catalog/allbookinstancelistborrowed.html'
paginate_by = 10
def get_queryset(self):
return BookInstance.objects.filter(status__exact='o').order_by('due_back')

I have this error in Django regarding a failed test

It says that 1 test has failed in the tests.py file in the HomeTests. I am doing a product application. Here is my tests.py file.
from django.urls import reverse
from django.urls import resolve
from django.test import TestCase
from .views import home, product_topics
from .models import Product
class HomeTests(TestCase):
def test_home_view_status_code(self):
url = reverse('home')
response = self.client.get(url)
self.assertEquals(response.status_code, 200)
def test_home_url_resolves_home_view(self):
view = resolve('/')
self.assertEquals(view.func, home)
def test_home_view_contains_link_to_topics_page(self):
product_topics_url = reverse('product_topics', kwargs={'pk': self.product.pk})
self.assertContains(self.response, 'href="{0}"'.format(product_topics_url))
class ProductTopicsTests(TestCase):
def setUp(self):
Product.objects.create(name='Light Bulb', description='Conserver energy',price=25.99,qtyOnHand=25)
def test_product_topics_view_success_status_code(self):
url = reverse('product_topics', kwargs={'pk': 1})
response = self.client.get(url)
self.assertEquals(response.status_code, 200)
def test_product_topics_view_not_found_status_code(self):
url = reverse('product_topics', kwargs={'pk': 99})
response = self.client.get(url)
self.assertEquals(response.status_code, 404)
def test_product_topics_url_resolves_board_topics_view(self):
view = resolve('/products/1/')
self.assertEquals(view.func, product_topics)
The AttributeError says that HomeTests has no attribute Product.
and here is my views.py
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse
from .models import Product
# Create your views here.
def home(request):
products = Product.objects.all()
return render(request, 'home.html', {'products': products})
def product_topics(request, pk):
product = get_object_or_404(Product, pk=pk)
return render(request, 'topics.html', {'product': product})
In the urls.py, I have the following.
from django.conf.urls import url
from django.contrib import admin
from inventories import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^products/(?P<pk>\d+)/$', views.product_topics, name='product_topics'),
url(r'^admin/', admin.site.urls),
]
I would like to know why I am getting this error and what this error means so I can fix it. I am following the tutorial at Urls
The problem is the whole of this test!
def test_home_view_contains_link_to_topics_page(self):
product_topics_url = reverse('product_topics', kwargs={'pk': self.product.pk})
self.assertContains(self.response, 'href="{0}"'.format(product_topics_url))
There is no product or response objects in self while you are calling self.response & self.product. Maybe you wanted to do something like this?:
from django.test import Client
class HomeTests(TestCase):
def setUp(self):
self.client = Client()
# the other tests
def test_home_view_contains_link_to_topics_page(self):
product = Product.objects.create(
name='name', description='descr', price=1.0, qtyOnHand=2
)
product_topics_url = reverse('product_topics', kwargs={'pk': product.pk})
response = self.client.get(url)
content = response.content.decode('utf-8')
self.assertContains(content, 'href="{0}"'.format(product_topics_url))

HttpRequestResponse reloading to same page in django 2.0.3

1.I am trying to develop a simple blog using django 2.0.3. in the view.py when i was trying to redirect to page from edit.html or create.html it is redirecting to it self when i was giving the url manually it is still loading to same page i don't know why.
views.py
from django.shortcuts import render,get_object_or_404,redirect
from django.http import HttpResponseRedirect,HttpResponse
from posts.models import Post
from posts.forms import PostForm
from django.contrib import messages
from django.urls import reverse
def post_create(request):
form = PostForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
HttpResponseRedirect(instance.get_absolute_url())
context = {"title":"Create Blog","form":form}
return render(request,"create.html",context)
def post_detail(request,id):
instance = get_object_or_404(Post,id=id)
context = {
"title": instance.title,
"instance":instance
}
return render(request,"detail.html",context)
def post_update(request,id):
instance = get_object_or_404(Post,id=id)
form = PostForm(request.POST or None,instance=instance)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
messages.success(request,"Saved")
HttpResponseRedirect(instance.get_absolute_url())
context = {
"title": "Edit Blog",
"instance":instance,
"form":form
}
return render(request,"edit.html",context)
def post_delete(request):
context = {"title":"Delete"}
return HttpResponse("<h1>delete</h1>")
def post_list(request):
queryset = Post.objects.all().order_by('-timestamp')
context = {
"title":"List",
"object_list":queryset
}
return render(request,"index.html",context)
2.this my urls.py
urls.py
from django.contrib import admin
from django.urls import path,include,re_path
from . import views
app_name = 'posts'
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^$',views.post_list,name="list"),
re_path(r'^create/$',views.post_create,name="create"),
re_path(r'^(?P<id>\d+)/$',views.post_detail,name="detail"),
re_path(r'^(?P<id>\d+)/edit/$',views.post_update,name="update"),
re_path(r'^delete$',views.post_delete),
]
3.this my models.py
model.py
from django.db import models
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=120)
content = models.TextField()
timestamp = models.DateTimeField(auto_now=False,auto_now_add=True)
updated = models.DateTimeField(auto_now=True,auto_now_add=False)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("posts:detail", kwargs={"id":self.id})

CSRF token missing or incorrect. Django 1.8 restaurant app

I am getting this error (on Chrome):
CSRF token missing or incorrect
What I am trying to do is make a restaurant application. I have my menu items and am trying to create a record in my orders table. Any time one button is clicked I want to add that entry into the orders table
Here are my files:
views.py
from django.shortcuts import render, render_to_response
from django.http import HttpRequest, HttpResponseRedirect
from django.template import RequestContext
from datetime import datetime
from app.models import *
def menu(request):
menus = Menu.objects.all()
return render_to_response('app/menu.html', {'menus':menus})
def menudetails(request,id):
menu = Menu.objects.get(pk = id)
return render_to_response('app/menudetails.html', {'menu':menu})
def myorders(request,id):
# if request.method == "POST":
#order = Order.createorder(Menu(pk=id))
# order.save()
if request.method == "GET":
form = OrderForm()
return render(request, 'app/menudetails.html',{ 'form':form })
elif request.method == "POST":
form = OrderForm(request.POST)
form.save()
return HttpResponseRedirect('/menu');
def addmenu(request):
if request.method == "GET":
form = MenuForm()
return render(request, 'app/addmenu.html',{ 'form':form })
elif request.method == "POST":
form = MenuForm(request.POST)
form.save()
return HttpResponseRedirect('/menu');
def home(request):
"""Renders the home page."""
assert isinstance(request, HttpRequest)
return render(
request,
'app/index.html',
context_instance = RequestContext(request,
{
'title':'Home Page',
'year':datetime.now().year,
})
)
def contact(request):
"""Renders the contact page."""
assert isinstance(request, HttpRequest)
return render(
request,
'app/contact.html',
context_instance = RequestContext(request,
{
'title':'Contact',
'message':'Your contact page.',
'year':datetime.now().year,
})
)
def about(request):
"""Renders the about page."""
assert isinstance(request, HttpRequest)
return render(
request,
'app/about.html',
context_instance = RequestContext(request,
{
'title':'About',
'message':'Your application description page.',
'year':datetime.now().year,
})
)
urls.py
from datetime import datetime
from django.conf.urls import patterns, url
from app.forms import BootstrapAuthenticationForm
# Uncomment the next lines to enable the admin:
# from django.conf.urls import include
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
#url(r'^myorders$', 'app.views.myorders', name = 'myorders'),
url(r'^menu$', 'app.views.menu', name = 'menu'),
url(r'^addmenu$', 'app.views.addmenu', name = 'addmenu'),
url(r'^menu/(?P<id>\d+)$', 'app.views.menudetails', name = 'menudetails'),
url(r'^menu/(?P<id>\d+)/order$', 'app.views.myorders', name = 'myorders'),
url(r'^$', 'app.views.home', name='home'),
url(r'^contact$', 'app.views.contact', name='contact'),
url(r'^about', 'app.views.about', name='about'),
url(r'^login/$',
'django.contrib.auth.views.login',
{
'template_name': 'app/login.html',
'authentication_form': BootstrapAuthenticationForm,
'extra_context':
{
'title':'Log in',
'year':datetime.now().year,
}
},
name='login'),
url(r'^logout$',
'django.contrib.auth.views.logout',
{
'next_page': '/',
},
name='logout'),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
)
models.py
from django.db import models
from django import forms
from datetime import datetime
class Menu(models.Model):
name = models.CharField("Menu Item", max_length = 50)
desc = models.CharField("Description", max_length = 100)
price = models.DecimalField(max_digits=6, decimal_places = 2)
class MenuForm(forms.ModelForm):
class Meta:
model = Menu;
fields = ['name','desc','price'];
class Order(models.Model):
menuItem = models.ForeignKey(Menu)
ordercreated = models.DateTimeField(auto_now_add = True)
orderupdate = models.DateTimeField(auto_now = True)
completed = models.BooleanField(default = False)
user = models.CharField(max_length = 30, blank = True)
def createorder(cls, menu):
order = cls(menuItem = menu)
return order
How to avoid this error, solutions as below:
Add {% csrf_token %} in your template
Link:csrf_token
Add #csrf_exempt on your view
Link:csrf_exempt

Categories

Resources