Alvaro E
Alvaro E

Reputation: 85

Django - not showing my var in template

I'm starting in Django.

I'm trying to pass to my template my var to be shown in my browser but not working.

here's my views.py

from django.shortcuts import render
from django.http import HttpResponse
from preguntasyrespuestas.models import Pregunta
from django.shortcuts import render_to_response

# Create your views here.
def index(request):
    string = 'hi world'
    return render_to_response('test/index.html',
                                {'string': string})

here's my urls:

from django.conf.urls import *
from django.contrib import admin
from django.contrib.auth.views import login
from preguntasyrespuestas.views import index

urlpatterns = [
    url(r'^$', index, name='index'),
]

my html:

<!DOCTYPE html>
<html>
<head>
    <title> Preguntas </title>
</head>
<body>
    <p>{{ string }}</p>
</body>
</html>

Basicaly I want to show what's in string in my template. but not working..

My error:

Using the URLconf defined in django_examples.urls, Django tried these URL patterns, in this order:

    ^$ [name='index']

The current URL, test/index.html, didn't match any of these.

What am I doing wrong? Thanks..

Upvotes: 0

Views: 39

Answers (2)

H&#229;ken Lid
H&#229;ken Lid

Reputation: 23064

Django's url routing uses regular expressions to match routes.

url(r'^$', index, name='index'),

In this case you have just a single valid route, which is the empty string r'^$'. So you can only get a response by visiting for example http://localhost:8000. All other urls will fail.

Django's url routing is completely independent from where your template files are located on your file system. Therefore http://localhost/test/index.html will not be valid, even though there is a template file with that name.

You could make a catch-all route by using this pattern that will match any url path.

url(r'', index, name='index'),

Upvotes: 0

ettanany
ettanany

Reputation: 19806

You should not add test/index.html at the end of your url in the browser, just something like http://127.0.0.1:8000/ and make sure that templates/test/index.html exists.

Upvotes: 1

Related Questions