学习Django,但与变量混淆

时间:2017-01-18 00:20:06

标签: python django django-views

我正在阅读Django教程,我正在创建民意调查应用程序的第3步。有一个名为“question_id”的变量,我无法理解这个定义的确切位置或来自何处。我将发布下面的文件。我唯一的猜测是,当在Models.py中定义类Question时,这个变量以某种方式由Django内部创建,但我不确定。它没有在“问题”类中定义。

以下是我的文件:

views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader

from .models import Question


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


#def index(request):
#    return HttpResponse("Hello, world. You're at the polls index.")

def detail(request, question_id):
    return HttpResponse("You're looking at question %s." % question_id)

def results(request, question_id):
    response = "Your looking at result of question %s."
    return HttpResponse(response % question_id)

def vote(reqeust, question_id):
    return HttpResponse("You're voting on question %s." % question_id)

urls.py

from django.conf.urls import url

from . import views

urlpatterns = [
    #ex: /polls/
    url(r'^$', views.index, name='index'),
    #ex: /polls/5
    url(r'^(?P<question_id>[0-9]+/$)', views.detail, name='detail'),
    #ex: /polls/5/result/
    url(r'^(?P<question_id>[0-9]+/results/$)', views.results, name='results'),
    #ex: /polls/5/vote
    url(r'^(?P<question_id>[0-9]+/vote/$)', views.vote, name='vote'),
]

models.py

import datetime

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


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

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)



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

    def __str__(self):
        return self.choice_text

感谢您的帮助, Nermin

4 个答案:

答案 0 :(得分:1)

显示的三个视图中的question_id由django自动创建。它将url作为输入用于此目的。它在这里定义

url(r'^(?P<question_id>[0-9]+/$)', views.detail, name='detail'),

因此,如果您在浏览器中输入polls/somenumber/,则名为detail的视图会传递一个名为question_id的变量,值为somenumber

urls.py中使用的正则表达式确保这是一个数字而不是其他内容。

有关更多信息,请参阅:https://docs.djangoproject.com/en/1.10/topics/http/urls/

答案 1 :(得分:0)

这是views.py中函数中的参数,以及urls.py中指定的网址格式。

答案 2 :(得分:0)

question_id只是分配给数据库记录中主键的名称。希望这有助于:)

答案 3 :(得分:0)

当你在Django中有一个没有定义其他ForeignKey变量的模型时,框架会自动生成一个id字段,作为这些对象的唯一标识符。

如果教程问题定义为:

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

def __str__(self):
    return self.question_text

def was_published_recently(self):
    return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

在封面后面,Django正在添加一个隐藏的ID字段,其外观如下:

id = models.ForeignKey(Integer)

您创建的每个Question对象都会有一个与之关联的唯一递增ID(请查看管理门户网站)。

为了更具体地回答您的问题,从视图中传递了question_id。如果您仔细阅读教程,他们会将question_id更改为pk(主键)。

网址http://127.0.0.1/question/polls/4将调用详细信息(request,question_id)。在这种情况下,只需将值4传递给函数,然后在HttpResponse中返回该id即可。在本教程的后面,您将返回ID为4的Question对象。

这里的这一位基本上是传递一个名为question_id的变量,它看起来像一个数字。     (ΔP[0-9] + / $)