Django的MVC

polls/
    __init__.py
    admin.py
    apps.py
    templates/
        index.html
        404.html
    migrations/
        __init__.py
    models.py
    urls.py
    tests.py
    views.py

 models

from django.db import models
from django.utils import timezone
import datetime


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

controls

from django.http import HttpResponse
from .models import Question, Choice
from django.db import connection
from django.template import loader



def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    template = loader.get_template('index.html')
    context = {
        'latest_question_list':latest_question_list
    }
    return HttpResponse(template.render(context, request))

views

{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

 

 

 

上一篇:java设计模式之观察者模式


下一篇:Django入门问题总结