Django入门笔记(一)_建站基本流程

news/2024/5/20 15:11:48/文章来源:https://blog.csdn.net/weixin_39532362/article/details/93752647

Django入门笔记(一)_建站基本流程

  • 逻辑总览
  • 基本环境
  • 虚拟配置
  • 命令行
  • 创建模型
  • URLconf
  • 视图编写
  • 模板编写
  • 全局settings
  • 测试
  • 超级用户

逻辑总览

在这里插入图片描述

基本环境

# 安装python3# 安装virtualenv
pip3 install virtualenv

虚拟配置

# 生成激活
# win
virtualenv -p python3 BASE_DIR/../venv
venv/Scripts/activate#linux
find / -name virtualenv
source venv/bin/activate# 退出
deactivate

命令行

# 安装django
pip install django# 查看版本
python -m django --version# 创建项目
django-admin startproject mysite# 创建app
django-admin startapp polls# 运行服务器
python manage.py runserver# 默认主页
http://127.0.0.1:8000/

创建模型

  • 模型脚本
  • vi BASE_DIR/polls/ + models.py
from django.db import modelsclass Question(models.Model):question_text = models.CharField(max_length=200,)pub_date = models.DateTimeField('date published')def __str__(self):return self.question_textclass Choice(models.Model):question = models.ForeignKey(Question,on_delete=models.CASCADE,related_name='choice')choice_text = models.CharField(max_length=200)votes = models.IntegerField(default=0)def __str__(self):return self.choice_text
# 迁移数据库
python manage.py makemigrations
python manage.py makemigrations polls
python manage.py migrate

URLconf

  • vi BASE_DIR/ + urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import url,includeurlpatterns = [url(r'polls/', include('polls.urls')),url(r'admin/', admin.site.urls),
]
  • vi BASE_DIR/polls/ + urls.py
from django.conf.urls import urlfrom . import viewsapp_name = 'polls'
urlpatterns = [url(r'^$', views.polls, name='polls'),url(r'^question_list/$', views.question_list, name='question_list'),url(r'^question_list/detail/(?P<question_id>\d+)/$', views.detail, name='detail'),url(r'^vote/(\d+)/$', views.vote, name='vote'),url(r'^results/(\d+)/$', views.results, name='results'),
]

视图编写

  • vi BASE_DIR/polls/ + views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from django.urls import reversefrom .models import Question,Choicedef polls(request):context = "the polls index"return render(request,'polls.html',{'context':context})# return HttpResponse(context)def question_list(request):questions = Question.objects.all()return render(request,'question_list.html',{'questions':questions})def detail(request,question_id):question = get_object_or_404(Question,pk=question_id)return render(request,'detail.html',{'question':question})def vote(request,question_id):question = get_object_or_404(Question, pk=question_id)try:selected_choice = question.choice.get(pk=request.POST['choice'])except (KeyError, Choice.DoesNotExist):# 重新显示问题的投票表单return render(request, 'detail.html', {'question': question,'error_message': "You didn't select a choice.",})selected_choice.votes += 1selected_choice.save()return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))def results(request,question_id):question = get_object_or_404(Question, pk=question_id)return render(request, 'results.html', {'question': question})

模板编写

# 复制样式文件
cp bootstrap.min.css BASE_DIR/polls/static/
  • cd BASE_DIR/polls/templates/
  • polls.html
{% load static %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
<div class="container"><ol class="breadcrumb my-4"><li class="breadcrumb-item active">polls</li><li class="breadcrumb-item"><a href="{% url 'polls:question_list' %}">question_list</a></li></ol><h1 class="breadcrumb my-4">{{ context }}</h1><a href="{% url 'polls:question_list' %}"> show all question</a>
</div>
  • question_list.html
{% load static %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
<div class="container"><ol class="breadcrumb my-4"><li class="breadcrumb-item"><a href="{% url 'polls:polls' %}">polls</a></li><li class="breadcrumb-item active">question_list</li></ol><h1 class="breadcrumb my-4">question_list</h1>{% if not questions %}<p><strong>empty question</strong></p>{% else %}<table class="table"><thead class="thead-dark"><tr><th>question_text</th><th>pub_date</th></tr></thead><tbody>{% for question in questions %}<tr><td><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a><small class="text-muted d-block">{{ forloop.counter }}</small></td><td class="align=middle">{{ question.pub_date }}</td></tr>{% endfor %}</tbody></table>{% endif %}
</div>
  • detail.html
{% load static %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
<div class="container"><ol class="breadcrumb my-4"><li class="breadcrumb-item"><a href="{% url 'polls:polls' %}">polls</a></li><li class="breadcrumb-item"><a href="{% url 'polls:question_list' %}">question_list</a></li><li class="breadcrumb-item active">detail</li></ol><h1 class="breadcrumb my-4">{{ question.question_text }}</h1>{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}{% if not question.choice.all %}<p><strong> empyt choice </strong></p>{% else %}<form action="{% url 'polls:vote' question.id %}" method="post">{% csrf_token %}{% for choice in question.choice.all %}<input type="radio" id="choice_{{ forloop.counter }}" name="choice" value="{{ choice.id }}" /><label for="choice_{{ forloop.counter }}">{{ choice.choice_text }}</label><br />{% endfor %}<input type="submit" value="Vote" /></form>     {% endif %}
</div>
  • results.html
{% load static %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
<div class="container"><ol class="breadcrumb my-4"><li class="breadcrumb-item"><a href="{% url 'polls:polls' %}">polls</a></li><li class="breadcrumb-item"><a href="{% url 'polls:question_list' %}">question_list</a></li><li class="breadcrumb-item active">result</li></ol><h1 class="breadcrumb my-4">{{ question.question_text }}</h1><table class="table"><thead class="thead-dark"><tr><th>choice</th><th>count</th></tr></thead><tbody>{% for choice in question.choice.all %}<tr><td>{{ choice.choice_text }}</td><td>{{ choice.votes }} vote{{ choice.votes|pluralize }}</td></tr>{% endfor %}</tbody></table><a href="{% url 'polls:detail' question.id %}">Vote again?</a>	
</div>

全局settings

  • vi BASE_DIR/mysite/ + settings.py
# 添加app
INSTALLED_APPS = [#...'polls',  
]# 设置html模版文件路径
TEMPLATES = [{#...'DIRS': [os.path.join(BASE_DIR, 'templates')],'APP_DIRS': True,#...},
]# 静态文件
STATIC_URL = '/static/'STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),
]

测试

  • vi BASE_DIR/polls/ + tests.py
from django.test import TestCase
from django.urls import reverse,resolvefrom .views import polls, question_list, detail, vote ,results
from .models import Question
from django.utils import timezoneclass PollsTests(TestCase):def test_polls_view_status_code(self):url = reverse('polls:polls')response = self.client.get(url)self.assertIs(response.status_code,200)self.assertContains(response,'polls')def test_polls_url_resolve_polls_view(self):view = resolve('/polls/')self.assertEqual(view.func,polls)class Question_listTests(TestCase):def test_question_list_status_code(self):Question.objects.create(question_text="test_question_list_status_code",pub_date=timezone.now())url = reverse('polls:question_list')response = self.client.get(url)self.assertIs(response.status_code,200) def test_question_list_status_code_empty(self):url = reverse('polls:question_list')response = self.client.get(url)self.assertIs(response.status_code,200) self.assertContains(response,'empty')self.assertQuerysetEqual(response.context['questions'],[])def test_question_list_url_resolve_polls_view(self):view = resolve('/polls/question_list/')self.assertEquals(view.func,question_list)class DetailTests(TestCase):def setUp(self):q1=Question.objects.create(question_text="DetailTests",pub_date=timezone.now())q1.choice.create(choice_text='someone')q2=Question.objects.create(question_text="DetailTests_empty",pub_date=timezone.now())def test_detail_view_status_code(self):url = reverse('polls:detail',args=(1,))response = self.client.get(url)self.assertIs(response.status_code,200)def test_detail_view_status_code_empty(self):url = reverse('polls:detail',args=(2,))response = self.client.get(url)self.assertContains(response,'empty')def test_detail_url_resolve_polls_view(self):view = resolve('/polls/question_list/detail/1/')self.assertEqual(view.func,detail)class VoteTests(TestCase):def test_vote_url_resolve_polls_view(self):view = resolve('/polls/vote/1/')self.assertEqual(view.func,vote)class ResultsTests(TestCase):def setUp(self):Question.objects.create(question_text="ResultsTests",pub_date=timezone.now())   def test_result_view_status_code(self):url = reverse('polls:results',args=(1,))response = self.client.get(url)self.assertIs(response.status_code,200)def test_result_url_resolve_polls_view(self):view = resolve('/polls/results/1/')self.assertEqual(view.func,results)
# 执行测试
python manage.py test

超级用户

# 创建超级用户
python manage.py createsuperuser# 复制模板到项目模板文件
cp django/contirb/admin/templates/base_site.html BASE_DIR/templates/admin/# vi BASE_DIR/templates/admin/base_site.html
#...
<h1 id="site-name"><a href="{% url 'admin:index' %}">Polls Administration</a></h1>
#...
  • vi BASE_DIR/polls/ + admin.py
from django.contrib import adminfrom .models import Question, Choiceclass ChoiceInline(admin.TabularInline):model = Choiceextra = 3class QuestionAdmin(admin.ModelAdmin):fieldsets = [('Question',{'fields':['question_text']}),('Date information',{'fields':['pub_date'],'classes': ['collapse']}),]inlines = [ChoiceInline]list_display = ('question_text', 'pub_date')list_filter = ['pub_date']search_fields = ['question_text']class ChoiceAdmin(admin.ModelAdmin):fields=['question','choice_text','votes']list_display = ('choice_text','question','votes')admin.site.register(Question, QuestionAdmin)
admin.site.register(Choice, ChoiceAdmin)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_899305.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

存图网站

http://imagehosting.biz

Wordress博客网站查看文章时显示进度条

可以在Wordress的插件里面下载 Post Reading Progress 插件 安装完之后&#xff0c;可以在后台的&#xff1a; 设置->读取进度条->中设置 如下图 我们就可以设置进度条相对应的功能

20多个漂亮的使用jQuery交互的网站设计欣赏

jQuery是使用最多的JS库之一&#xff0c;它有很多优点&#xff0c;比如轻量、易用、完善的Ajax、良好的浏览器兼容&#xff0c;以及它有健壮的选择器等。这些优点使得jQuery成为帮助前端开发人员的有力工具。越来越多的大型网站开始使用jQuery及其插件实现其前端交互。 这里&am…

老旧asp.net网站搬家导致的反编译实例1

2020年12月&#xff0c;朋友的海外win2008r2的服务器就要到期了&#xff0c;上面也没几个站了&#xff0c;租服务器就不合算了。3个人合伙买了一个海外的虚拟主机&#xff0c;算下来&#xff0c;平均下来每人每年一百不到。无限流量、无限网站、无限空间&#xff0c;放一些小站…

老旧asp.net网站搬家导致的反编译实例2

https://blog.csdn.net/liufile/article/details/112001740 前面提到了&#xff0c;迁移老破旧asp.net网站出现的兼容性问题&#xff0c;在反编译dll&#xff0c;修补了相应代码&#xff0c;编译的dll出现&#xff0c;新的错误&#xff1a; 未能加载文件或程序集“NVelocity,…

老旧asp.net网站搬家导致的反编译实例3

https://blog.csdn.net/liufile/article/details/112002023 前一篇已经介绍了&#xff0c;如何解决无源代码的老旧asp.net的兼容性或小范围修改问题&#xff0c;但是&#xff0c;对于我调试的网站&#xff0c;又出现新的问题&#xff0c;就是功能有缺失&#xff0c;这可能是反…

CodeIgniter开发实际案例-新闻网站

1、建立数据库 运用Navicat For Mysql工具&#xff0c;创建一个数据库&#xff0c;名称为"news"&#xff0c; 并建立如下表&#xff08;鼠标右键&#xff0c;命令行运行如下sql语句&#xff09;&#xff1a; CREATE TABLE news (id int(11) NOT NULL AUTO_INCREMENT,…

使用github搭建个人网站

使用github搭建个人网站 首先注册一个账号 然后新建一个仓库。点击New repository 名称使用 你的名字.github.io 之后在打开设置Setting 拉到下面有一个git 博客&#xff0c;点击它的选择主题&#xff0c;然后用它的模板创建一个。 创建了以后&#xff0c;就不会…

使用阿里云ecs搭建网站

最近两天在弄自己的服务器&#xff0c;尽管配置是最低的&#xff0c;不过终于算是弄好了&#xff0c;其中许多波折&#xff0c;希望以后有机会弄一下wordpress。 在一开始的时候&#xff0c;就只是熟悉一下过程&#xff0c;所以网站也是很简单的静态网站&#xff0c;估计以后会…

Chrome插件: 网站收藏

在工作中我们会收藏很多网址。以前一直都是用的chrome里面的收藏夹。后面觉得一点都不方便。看一下Chrome插件开发挺容易入手的所以自己写了一个Chrome插件. 基于:Angularjs Bootstrap的. 主界面: 功能描述: 1.Add: 支持添加网址功能&#xff1a; 2.Collect current page: 获…

说一下这两天比较红火的航班追踪网站

这两天一款本来名不见经传的“小众民航好物”&#xff0c;一夜爆红。其实时追踪航班的功能&#xff0c;昨夜吸引30万人齐齐涌入&#xff0c;直接把这小破网站搞得流量爆炸&#xff0c;一度崩溃。 如果你睡得比较早&#xff0c;现在可以再一起看一眼这个名叫Flightradar24的网站…

nginx+mysql8+php8建站

nginxmysql8php8rhel7.6建站&#xff08;20220111&#xff09; 1、Nginx安装配置 1.1 安装前工作 ​ 首先更新系统软件源&#xff0c;使用以下命令更新系统 - [rootswordman ~]# yum update有关两个命令的一点解释&#xff1a; yum -y update - 升级所有包&#xff0c;改变…

织梦模板:响应式手机电子配件类网站织梦模板

模板名称&#xff1a; 响应式手机电子配件类网站织梦模板(自适应设备) 模板介绍&#xff1a; 织梦最新内核开发的模板&#xff0c;该模板属于HTML5响应式、手机配件、电子配件、手机套类企业使用&#xff0c;一 款适用性很强的模板&#xff0c;基本可以适合各行业的企业网站&am…

dedecms模板自带的网站地图如何优化?

dedecms模板自带的网站地图如何优化&#xff1f;使用织梦CMS模板做网站的人应该都知道&#xff0c;在它的robots.txt是屏蔽掉了data目录的&#xff0c;不巧的是dedecms默认的网站地图是在data下的&#xff0c;为了让蜘蛛更好的爬行&#xff0c;有必要将dedecms生成的网站地图放…

响应式摄影类企业网站织梦模板(自适应设备)

模板介绍&#xff1a;织梦最新内核开发的模板&#xff0c;该模板属于HTML5响应式、户外摄影、婚纱摄影设计类网站企业使用&#xff0c;一款适用性很强的模板&#xff0c;基本可以适合各行业的企业网站&#xff01;响应式自适应各种移动设备&#xff0c;同一个后台&#xff0c;数…

汽车租赁服务类网站织梦模板(带手机移动端) 2017-07-17 17:15 模板名称:汽车租赁服务类网站织梦模板(带手机移动端)

模板名称&#xff1a;汽车租赁服务类网站织梦模板(带手机移动端) 模板介绍&#xff1a; 1、织梦最新内核开发的模板&#xff0c;该模板属于企业通用类、汽车租赁服务、汽车4S店类企业都可使用&#xff0c; 2、这款模板使用范围极广&#xff0c;不仅仅局限于一类型的企业&#x…

如何在阿里云虚拟主机上绑定多个域名创建多个网站

其实&#xff0c;很多时候我们购买的虚拟主机在建立一个站点之后会剩余很多空间&#xff0c;会很浪费。其实一台虚拟主机也可以拥有多个独立的网站、独立的域名。今天就跟大家分享一下如何在在阿里云虚拟主机上绑定多个域名创建多个网站。 方法如下&#xff1a; 第一步、在虚拟…

织梦网站地图生成插件下载

网站地图不但可以让浏览用户一览网站框架&#xff0c;对于搜索引擎对网站的收录和抓取同样起着相当重要的作用。今天跟大家分享一款好用的织梦织梦网站地图生成插件。 用过织梦的朋友应当都知道&#xff0c;织梦自带的网站地图只包含了顶级栏目的链接&#xff0c;并没有网站二级…

如何知道自己的网站是utf8还是gbk编码

用过织梦建站的站长们应当都知道网站代码有utf8与gbk两种编码格式&#xff0c;如果两种编码混用网站就有可能出现乱码。 而我们在初次搭建网站的过程中往往没有在意自己使用的是utf8编码格式还是gbk编码格式&#xff0c;导致自己在选用织梦模板、安装织梦插件时不知所措。 今天…

织梦dedecms怎么安装?如何本地环境搭建网站?

对于新手建站玩家&#xff0c;直接购买服务器和域名可能不太现实&#xff0c;容易出现很多问题。在网站上线之前&#xff0c;其实大可以在自己的电脑上安装织梦dedecms进行网站后台的熟悉以及站点的建立、调试&#xff0c;等到需要上线的时候直接保存数据进行上传到服务器即可。…