Question

<p>Hello, my name is {{ name }} ! </p>

Where/how do I set the variable: name = 'mike'? I've tried putting this in the settings.py and models.py file and it does not work.

Any info of proper code to put in a .py file would be great! I've searched through the docs page but didn't see how to set a variable for retrieval.

Was it helpful?

Solution

You need to set your variable value in the view function which normally put in view.py

e.g.

def hello(request):
    return render(request, "hello.html", {"name": "mike"})

And you may would like to check https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#render to find more about how to render templates with passed variables.

You need also learn more about how does Django's URL mapping works https://docs.djangoproject.com/en/dev/ref/urls/

OTHER TIPS

Use context processors in django. Django handles this dilemma of making some information available to all pages with something called context processors.

Some Code is like this,

Create a new file called context_processors.py inside your utils app directory, and add the following code to it:

from project import settings
def context_data(request):
  return {
          'name': settings.name,
          'request': request
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top