We've summarized everything from designing a URL scheme in Django to displaying it in a template.
urls.py
from django.template import Context, loader
from polls.models import Test
from django.http import HttpResponse
def index(request):
latest_test_list = Test.objects.all().order_by('-pub_date')[:5]
t = loader.get_template('test/index.html')
c = Context({
'latest_test_list': latest_test_list,
})
return HttpResponse(t.render(c))
Design the url using regular expressions in urls.py.
As a way of thinking Django tests from the first tuple until the requested URL matches the regular expression in the tuple.
If a matching regular expression is found, Django will call the callback function specified for that tuple. Pass the HttpRequest object as the first argument to the callback function. In addition, in the regular expression, "pass the captured value as a keyword argument. If an optional dictionary object (the third element of the tuple) is specified, its contents are also passed as additional keyword arguments.
Set the directory that specifies the above URL scheme in setting.py
setting.py
TEMPLATE_DIRS = (
'/Path to the directory where the template is/', #You need to adapt to your environment.
)
The URL setting is completed up to the above, but the method corresponding to the URL is not defined. Set it in view.py.
from django.shortcuts import render_to_response
from polls.models import Test
def index(request):
latest_test_list = Test.objects.all().order_by('-pub_date')[:5]
return render_to_response('test/index.html',
{'latest_test_list': latest_test_list})
Finally, specify the front end and design as a template, Display the passed context.
templete.html
{% if latest_test_list %}
<ul>
{% for test in latest_test_list %}
<li><a href="/test/{{ test.id }}/">{{ test.text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>There is no test.</p>
{% endif %}
Recommended Posts