这篇文章主要介绍了django的环境配置和view的使用 ,具有一定借鉴价值,需要的朋友可以参考下。步骤简单适合新手,希望你能收获更多。下面是配置和使用的步骤内容。
mkdir djanad cd djanad/ pyenv virtualenv 3.6.5 djanad pyenv local djanad
结果如下
pip install django==2.1
django-admin startproject demo . django-admin startapp app
结果如下
数据库配置如下
基本时区和mysql配置及相关时区配置请看django基础
https://blog.51cto.com/11233559/2444627
启动结果如下
django内置了自己的模板引擎,和jinjia 很像,使用简单
使用 Template 进行定义模板,使用Context 将数据导入到该模板中,其导入默认使用字典
django 默认会去到app_name/templates下寻找模板,这是settings中的默认设置,默认会去app_name/static找那个寻找静态文件(css,js,jpg,html)等
在 app/models.py 中创建数据库表模板,具体配置如下:
from django.db import models # Create your models here. # 问题 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=Question) 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 migrate
结果如下
创建后台登陆用户,设置用户名为admin,密码为admin@123
app/admin.py中添加
# Register your models here. from django.contrib import admin from .models import Question, Choice # Register your models here. class ChoiceInline(admin.TabularInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ] inlines = [ChoiceInline] list_display = ('question_text', 'pub_date') admin.site.register(Choice) admin.site.register(Question, QuestionAdmin)
url : localhost:port/admin/
demo/setting.py 中配置添加
STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ]
项目中创建static 并上传图片django.jpg
demo/urls.py中配置如下
from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^app/', include("app.urls",namespace="app")), #此处配置名称空间,用于处理后面的翻转 ]
from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^index/$', views.index, name="index"), # name 指定名称, ]
from django.shortcuts import render from django.template import Template, Context from . import models from django.http import HttpResponse # Create your views here. def index(request): lastes_question_list = models.Question.objects.order_by('-pub_date')[:5] template = Template(""" <img src="/static/django.jpg"> {% if lastes_question_list %} <ul> {% for question in lastes_question_list %} <li> <a href="/app/ {{question.id}}/"> {{ question.question_text }} </a> </li> {% endfor %} </ul> {% endif %} """) context = Context({"lastes_question_list": lastes_question_list}) return HttpResponse(template.render(context))
访问配置,结果如下
index 代码如下
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>测试数据</title> </head> <body> <img src="/static/django.jpg"> {% if lastes_question_list %} <ul> {% for question in lastes_question_list %} <li> <a href="/app/{{question.id}}/"> {{question.question_text}} </a> </li> {% endfor %} </ul> {% endif%} </body> </html>
app/view.py 中代码如下
from . import models from django.http import HttpResponse from django.template import loader # Create your views here. def index(request): lastes_question_list = models.Question.objects.order_by('-pub_date')[:5] template = loader.get_template("app/index.html") context = {"lastes_question_list": lastes_question_list} return HttpResponse(template.render(context))
from . import models from django.shortcuts import render # Create your views here. def index(request): lastes_question_list = models.Question.objects.order_by('-pub_date')[:5] context = {"lastes_question_list": lastes_question_list} return render(request, template_name="app/index.html", context=context)
根据根路由中注册的namespace和子路由中注册的name来动态获取路径。在模板中使用"{% url namespace:name %}"
如果携带位置参数
“{% url namespace:name args %}"
如果携带关键字参数
“{% url namespace:name k1=v1 k2=v2 %}"
配置 详情页面添加数据
app/view.py 中添加数据如下
from . import models from django.shortcuts import render # Create your views here. def index(request): lastes_question_list = models.Question.objects.order_by('-pub_date')[:5] context = {"lastes_question_list": lastes_question_list} return render(request, template_name="app/index.html", context=context) def detal(request, question_id): detal = models.Question.objects.get(pk=question_id) context = {"detal": detal} return render(request, template_name="app/detal.html", context=context)
app/urls.py中如下
from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^index/$', views.index, name="index"), url(r'^(?P<question_id>[0-9]+)/$', views.detal, name="detal"),# name 指定名称,用于后面的反向解析 ] ]
详情页html 配置如下
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>测试数据</title> </head> <body> {% if detal %} <h2>{{ detal.question_text }}</h2> {% for question in detal.choice_set.all %} <li> {{ question.votes }} {{ question.choice_text }} </li> {% endfor %} {% endif %} </body> </html>
index.html 修改如下
<!DOCTYPE html> <html> <head> {% load static %} <meta charset="UTF-8"> <title>测试数据</title> </head> <body> <img src="{% static 'django.jpg'%}"> {% if lastes_question_list %} <ul> {% for question in lastes_question_list %} <li> <a href="{% url 'detal' question.id %}"> {{question.question_text}} </a> </li> {% endfor %} </ul> {% endif%} </body> </html>
看完上述内容,你们掌握django的环境配置和view的使用方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。