Designing URL schemes and creating templates in Django

We've summarized everything from designing a URL scheme in Django to displaying it in a template.

Specify URL scheme with regular expression

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.

Specify the directory to search for Template

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.
)

Set the template and the context to be passed in view

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 template settings

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

Designing URL schemes and creating templates in Django
PHP var_dump in Django templates
Handle constants in Django templates
Get parameter values ​​in Django templates
Notes on creating static files in Django
Specify the view URL in your Django template
Create initial settings and staff apps in Django
Image URL is blank in GAE & GCS & Django
Models in Django
Forms in Django
Django URL settings
Code that enumerates URL resolver view names in Django
How to use Decorator in Django and how to make it
Small and nifty Vim Plugins useful in Python / Django