6 Template The source I wrote earlier looks like this:
views.py
...
def current_datetime(request):
now = datetime.datetime.now()
html = "It is now %s." % now
return HttpResponse(html)
...
Creating pages one by one is hard, and the source is also hard to write the front end.
So let's make a template
Template looks like this:
index.html
<!DOCTYPE html>
<html>
<head>
<title>What's the time?</title>
</head>
<body>
It is now {{ time }}.
</body>
</html>
It's a normal HTML-like source, but the part you want to switch to is in {{}}
.
You can also realize simple logic. For example:
{% if user.gender == 'F' %}
Hello
{% endif %}
{% for question in questions %}
question.text
{% endfor %}
Rewrite views.py:
views.py
...
def current_datetime(request):
now = datetime.datetime.now()
data = {'now': now}
#render(request,Template name,Parameters), Put the data in the template.
return render(request, 'index.html', data)
...
7 Models The Django Model is in Models.py.
This shape:
models.py
from django.db import models
import django.utils.timezone as timezone
class Question(models.Model):
text = models.CharField(max_length=100)
uploadtime = models.DateTimeField('updated time', default = timezone.now)
...
You can easily create a class and Django will automatically create a table for you.
When you want to use Question Model in views.js:
views.py
from .models import Question
import django.utils.timezone as timezone
from django.shortcuts import render
def index():
#Get all the data from the database
allQuestions = Question.objects.all().order_by('-uploadtime')
now = timezone.now()
data = {'questions': allQuestions, 'now': now}
return render(request, 'index.html', data)
template
index.html
<!DOCTYPE html>
<html>
<head>
<title>Exercise books</title>
</head>
<body>
It is now {{ time }}.
{% for question in questions %}
question.text
<br />
{% endfor %}
</body>
</html>
urls.py
...
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^hello/$', hello),
url(r'^time/$', current_datetime),
url(r'^index/$', index),
...
]
visit: http://127.0.0.1:8000/time/
Recommended Posts