I am trying to understand the following code better. It’s working, but I just don’t fully understand several elements (questions below):
from django.shortcuts import render_to_response
from mywiki.wiki.models import Page
from django.http import HttpResponseRedirect
from django import forms
import markdown
class SearchForm(forms.Form):
text = forms.CharField(label='Enter search term')
def search_page(request):
if request.method =='POST':
f = SearchForm(request.POST)
if not f.is_valid():
return render_to_response('search.html', {'form':f})
else:
pages = Page.objects.filter(name__contains = f.cleaned_data['text'])
return render_to_response('search.html', {'form':f, 'pages':pages})
f = SearchForm()
return render_to_response('search.html', {'form':f})
specialPages = {'SearchPage':search_page}
def view_page(request, page_name):
if page_name in specialPages:
return specialPages[page_name](request)
try:
page = Page.objects.get(pk=page_name)
except Page.DoesNotExist:
return render_to_response('create.html', {'page_name':page_name})
content = page.content
return render_to_response('view.html', {'page_name':page_name, 'content':markdown.markdown(content)})
-
Why do we need to specify that the
request.methodhas to bePOST– wouldn’t clicking an HTML button implicitly signal an intent to change/affect something? OrPOSTis only appropriate when the action affects the database? -
How does the line
pages = Page.objects.filter(name__contains = f.cleaned_data['text'])work? It takes the modelPage(models.Model), but what do the ‘objects’ and ‘filter’ methods do in this case? -
In the
view_page, why do we need to add(request)inreturn specialPages[page_name](request)
Thanks!
The
POSTtest is used as a differentiator.When the view is called with
GET, the form is rendered. The form specifies that it needs to be submitted with usingPOST, so the code assumes that aPOSTrequest signals the form is submitted.The
objectsattribute triggers the actual database query. By adding the.filter()call you specify a more specific database query, one where thenameattribute contains the value off.cleaned_data['text']. The result is a set of database results that match that query.the
specialPagesdictionary values are themselves views, and for these to work, you call them with therequestparameter. Just like theview_pageview callable itself.