Skip to content

Instantly share code, notes, and snippets.

@taizarm
Last active Aug 29, 2015
Embed
What would you like to do?
Form + Context Processor
<!DOCTYPE html>
<html lang="pt-br">
<head>
{% load staticfiles %}
{% block head %}{% endblock %}
</head>
<body>
<div id="all">
<div id="busca">
<form action="/noticias_busca" method="post">{% csrf_token %}
<div class="search">
{{ form_search.as_p }}
<button class="search-ico" type="submit"><img
src="{% static 'busca.png' %}" /></button>
</div>
</form>
</div>
<div id="menu">
...
</div>
</div>
{% block content %}{% endblock %}
</body>
</html>
from forms import SearchIndex
def form_search(request):
return {'form_search': SearchIndex()}
class SearchIndex(forms.Form):
search = forms.CharField(max_length=255, required=False,
widget=forms.TextInput(attrs={'placeholder': 'O que está procurando?',
'class': 'search-input', }), )
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'site.context_processors.form_search',
)
from django.conf.urls import patterns, url, include
from django.contrib.auth import views as auth_views
urlpatterns = patterns('site.views',
url(r'^noticias_busca', 'noticias_busca', name='noticias_busca'),
)
def noticias_busca(request):
if request.method == 'POST':
form = SearchIndex(data=request.POST)
if form.is_valid():
search = form.cleaned_data['search']
noticias = Noticia.objects.filter(texto__contains=search)
return noticias_render(request, noticias)
else:
return noticias_render(request, [])
else:
return noticias_render(request, [])
def noticias_render(request, noticias):
paginator = Paginator(noticias, 10)
page = request.GET.get('page')
try:
noticias = paginator.page(page)
except PageNotAnInteger:
noticias = paginator.page(1)
except EmptyPage:
noticias = paginator.page(paginator.num_pages)
return render(request, 'site/noticias.html', {'noticias': noticias})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment