1. 设计数据结构
问题表Question:作用存放问题
id 主键 自增
question_text 题目 varchar120
created 创建时间 datetime
选项表Choice:作用 存放选项
id 主键 自增
question 外键 问题表
choice_text varchar120
vote int default=0
打开polls/models.py, 编写如下代码
# 问题模型 class Question(models.Model): question_text = models.CharField("题目", max_length=120) created = models.DateTimeField("创建时间", auto_created=True, null=True) # 选项模型 class Choice(models.Model): question=models.ForeignKey(Question,verbose_name=”题目", on_delete=models.CASCADE) choice_text = models.CharField("选项", max_length=120) vote = models.PositiveIntegerField("投票数", default=0)
打开mysite/settings.py,找到InstalledApps
INSTALLED_APPS = [ 'django.contrib.admin', ……… # 自己编写的应用 'polls.apps.PollsConfig', # 第三方应用 ]
将我们的模型的生成或者变动,形成一个脚本,通过运行这个脚本,生成数据库中的表
需要控制台【Terminal】执行两条命令
python manage.py makemigrations #创建迁移脚本
python manage.py migrate #执行迁移 生成数据库中的表
在控制台执行
q=Question.objects.create(question_text=”世界上最好的编程语言是?”)
q1 = Quesiotn.objects.get(pk=1)
q2=Question.objects.all()
q1. question_text
def __str__(self):
return self.question_text
在控制台输入如下命令:
python manage.py createsuperuser
打开polls/admin.py文件
加入如下代码
from polls.models import Question
admin.site.register(Question)
python manage.py runserver
访问 127.0.0.1:8000/admin
使用注册的超级用户的账号密码登录即可
针对多对一关系的管理页面
from django.contrib import admin
from polls.models import Question, Choice
# 针对多对一中 多的一方,可以让它继承 TabularInline类,作为 “一”的一方 管理界面的嵌入
class ChoiceInlineAdmin(admin.TabularInline):
model = Choice
# 配置Question的管理界面
class QuestionAdmin(admin.ModelAdmin):
#配置QUestion的外键的内嵌界面
inlines = [ChoiceInlineAdmin, ]
#把模型和配置类注册到一起
admin.site.register(Question, QuestionAdmin)
1.1 集中在项目中
创建mysite/templates/polls 文件夹
1.2 分散在应用中
创建polls/templates/polls
1.3 生成文件
在polls/templates/polls文件夹创建一个文件 index.html
{% for obj in question_list%}
<li>{{obj.question_text}}</li>
{% endfor%}
打开polls/views文件,把index方法改为:
def index(request):
question_list = Question.objects.all()
template = loader.get_template("polls/index.html")
return HttpResponse(template.render({'question_list': question_list}, request))
该方法 将字典({'question_list': question_list} 传到"polls/index.html" 模板中,进行渲染,把渲染后的结果发给浏览器
def index(request):
# question_list中存放数据库中查询的数据
question_list = Question.objects.all()
# 上下文 填充 模板中的数据
context = {'question_list': question_list}
# 将模板和上下文 进行组装, 渲染之后返回给浏览器
return render(request, "polls/index.html", context)
转载于:https://www.cnblogs.com/dyd520/p/11530325.html