Skip to content

Instantly share code, notes, and snippets.

@taizarm
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taizarm/9aaa2b94f87ed3d49b79 to your computer and use it in GitHub Desktop.
Save taizarm/9aaa2b94f87ed3d49b79 to your computer and use it in GitHub Desktop.
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