python - 学习Django,却对变量一头雾水

标签 python django django-views

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

这是我的文件:

View .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)

网址.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'),
]

模型.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

谢谢你的帮助, 内敏

最佳答案

显示的三个 View 中的question_id 是由django 自动创建的。为此,它将 url 作为输入。在这里定义

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

因此,如果您在浏览器中输入 polls/somenumber/,您的名为 detail 的 View 将传递一个名为 question_id 的变量和一个值一些

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

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

关于python - 学习Django,却对变量一头雾水,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41709358/

相关文章:

python - 在 Bokeh 中创建选择列表时出错

python - django 文件上传 : [Errno 13] Permission denied: '/static'

python:如何改进我的代码片段以按顺序解析元素

Django 。如何设置默认选项使用通用 CreateView

python - 基数为 10 的 int() 无效文字 : 'on' Python-Django

python - Python/Jython 中低效的随机掷骰子

python - 反转为 'str_team',没有找到参数。尝试了 1 个模式 : ['str_application\\-1/(?P<startup_id>[^/]+)/$' ]

Django 管理媒体未加载

django - 如何使用 "reverse"或等效项来引用 Hook 到 DjangoCMS 的 url?

django - 我可以从另一个 View 中调用一个 View 吗?