当前位置: 首页 > news >正文

青岛网站平台开发小说网站设计模板

青岛网站平台开发,小说网站设计模板,中国建筑装饰装修网,东莞百度seo电话Django视图和URL 一、课程概述 学习项目具体内容预计用时视图基础函数视图、类视图、视图装饰器90分钟URL配置URL模式、路由系统、命名URL60分钟请求处理请求对象、响应对象、中间件90分钟 二、视图基础 2.1 函数视图 # blog/views.py from django.shortcuts import render…Django视图和URL 一、课程概述 学习项目具体内容预计用时视图基础函数视图、类视图、视图装饰器90分钟URL配置URL模式、路由系统、命名URL60分钟请求处理请求对象、响应对象、中间件90分钟 二、视图基础 2.1 函数视图 # blog/views.py from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponse from .models import Post, Category from .forms import PostForm# 简单的函数视图 def hello_world(request):return HttpResponse(Hello, Django!)# 带模板渲染的视图 def post_list(request):posts Post.objects.all().order_by(-publish)return render(request, blog/post_list.html, {posts: posts})# 处理表单的视图 def post_create(request):if request.method POST:form PostForm(request.POST)if form.is_valid():post form.save(commitFalse)post.author request.userpost.save()return redirect(blog:post_detail, post.id)else:form PostForm()return render(request, blog/post_form.html, {form: form})# 详情视图 def post_detail(request, post_id):post get_object_or_404(Post, idpost_id)return render(request, blog/post_detail.html, {post: post})2.2 类视图 # blog/views.py from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin# 列表视图 class PostListView(ListView):model Posttemplate_name blog/post_list.htmlcontext_object_name postspaginate_by 10ordering [-publish]def get_queryset(self):queryset super().get_queryset()category_id self.request.GET.get(category)if category_id:queryset queryset.filter(category_idcategory_id)return queryset# 详情视图 class PostDetailView(DetailView):model Posttemplate_name blog/post_detail.htmlcontext_object_name post# 创建视图 class PostCreateView(LoginRequiredMixin, CreateView):model Posttemplate_name blog/post_form.htmlfields [title, body, category, status]success_url reverse_lazy(blog:post_list)def form_valid(self, form):form.instance.author self.request.userreturn super().form_valid(form)# 更新视图 class PostUpdateView(LoginRequiredMixin, UpdateView):model Posttemplate_name blog/post_form.htmlfields [title, body, category, status]def get_success_url(self):return reverse_lazy(blog:post_detail, kwargs{pk: self.object.pk})# 删除视图 class PostDeleteView(LoginRequiredMixin, DeleteView):model Postsuccess_url reverse_lazy(blog:post_list)template_name blog/post_confirm_delete.html2.3 视图装饰器 # blog/views.py from django.contrib.auth.decorators import login_required, permission_required from django.views.decorators.http import require_http_methods from django.views.decorators.cache import cache_page# 登录要求装饰器 login_required def profile(request):return render(request, blog/profile.html, {user: request.user})# HTTP方法限制装饰器 require_http_methods([GET, POST]) def post_edit(request, post_id):post get_object_or_404(Post, idpost_id)if request.method POST:# 处理POST请求passreturn render(request, blog/post_edit.html, {post: post})# 缓存装饰器 cache_page(60 * 15) # 缓存15分钟 def category_list(request):categories Category.objects.all()return render(request, blog/category_list.html, {categories: categories})三、URL配置 3.1 URL模式 # blog/urls.py from django.urls import path from . import viewsapp_name blogurlpatterns [# 函数视图URLpath(, views.post_list, namepost_list),path(post/int:post_id/, views.post_detail, namepost_detail),path(post/new/, views.post_create, namepost_create),# 类视图URLpath(posts/, views.PostListView.as_view(), nameposts),path(post/int:pk/detail/, views.PostDetailView.as_view(), namepost_detail),path(post/add/, views.PostCreateView.as_view(), namepost_add),path(post/int:pk/edit/, views.PostUpdateView.as_view(), namepost_edit),path(post/int:pk/delete/, views.PostDeleteView.as_view(), namepost_delete),# 带参数的URLpath(category/slug:category_slug/, views.category_posts, namecategory_posts),path(tag/slug:tag_slug/, views.tag_posts, nametag_posts),path(archive/int:year/int:month/, views.archive_posts, namearchive_posts), ]3.2 高级URL配置 # myproject/urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import staticurlpatterns [path(admin/, admin.site.urls),path(blog/, include(blog.urls, namespaceblog)),path(api/, include(blog.api.urls)), # API URLspath(accounts/, include(django.contrib.auth.urls)), ] static(settings.MEDIA_URL, document_rootsettings.MEDIA_ROOT)# 自定义错误页面 handler404 myproject.views.custom_404 handler500 myproject.views.custom_500四、请求和响应处理 4.1 请求对象 # blog/views.py def process_request(request):# 获取GET参数page request.GET.get(page, 1)category request.GET.get(category)# 获取POST数据if request.method POST:title request.POST.get(title)content request.POST.get(content)# 获取文件if request.FILES:image request.FILES[image]# 获取cookiesuser_id request.COOKIES.get(user_id)# 获取session数据cart request.session.get(cart, {})# 获取用户信息if request.user.is_authenticated:username request.user.username4.2 响应对象 # blog/views.py from django.http import JsonResponse, FileResponse, StreamingHttpResponse from django.shortcuts import render, redirectdef multiple_responses(request):# HTML响应return render(request, template.html, context)# 重定向return redirect(blog:post_list)# JSON响应data {status: success, message: Data received}return JsonResponse(data)# 文件下载file_path path/to/file.pdfreturn FileResponse(open(file_path, rb))# 流式响应def file_iterator(file_path, chunk_size8192):with open(file_path, rb) as f:while True:chunk f.read(chunk_size)if not chunk:breakyield chunkreturn StreamingHttpResponse(file_iterator(file_path))4.3 中间件 # blog/middleware.py import time from django.utils.deprecation import MiddlewareMixinclass RequestTimingMiddleware(MiddlewareMixin):def process_request(self, request):request.start_time time.time()def process_response(self, request, response):if hasattr(request, start_time):duration time.time() - request.start_timeresponse[X-Request-Duration] str(duration)return response# settings.py MIDDLEWARE [django.middleware.security.SecurityMiddleware,django.contrib.sessions.middleware.SessionMiddleware,django.middleware.common.CommonMiddleware,django.middleware.csrf.CsrfViewMiddleware,django.contrib.auth.middleware.AuthenticationMiddleware,django.contrib.messages.middleware.MessageMiddleware,django.middleware.clickjacking.XFrameOptionsMiddleware,blog.middleware.RequestTimingMiddleware, # 自定义中间件 ]五、实战示例博客搜索功能 # blog/views.py from django.db.models import Qdef post_search(request):query request.GET.get(q, )results []if query:results Post.objects.filter(Q(title__icontainsquery) |Q(body__icontainsquery) |Q(tags__name__icontainsquery)).distinct()return render(request,blog/search.html,{query: query,results: results})# blog/templates/blog/search.html {% extends blog/base.html %}{% block content %}h2搜索结果/h2form methodgetinput typetext nameq value{{ query }} placeholder搜索文章...button typesubmit搜索/button/form{% if query %}h3包含 {{ query }} 的文章/h3{% if results %}{% for post in results %}articleh4a href{% url blog:post_detail post.id %}{{ post.title }}/a/h4p{{ post.body|truncatewords:30 }}/p/article{% endfor %}{% else %}p没有找到相关文章。/p{% endif %}{% endif %} {% endblock %}六、常见问题和解决方案 处理404错误 # views.py from django.http import Http404def post_detail(request, post_id):try:post Post.objects.get(idpost_id)except Post.DoesNotExist:raise Http404(Post does not exist)return render(request, blog/post_detail.html, {post: post})CSRF验证 !-- templates/form.html -- form methodpost{% csrf_token %}{{ form.as_p }}button typesubmit提交/button /form文件上传处理 # views.py def upload_file(request):if request.method POST and request.FILES[file]:myfile request.FILES[file]fs FileSystemStorage()filename fs.save(myfile.name, myfile)uploaded_file_url fs.url(filename)return render(request, upload.html, {uploaded_file_url: uploaded_file_url})return render(request, upload.html)七、作业和练习 实现一个完整的CRUD操作系统创建自定义的中间件实现文件上传和下载功能编写RESTful风格的URL设计实现用户认证和授权系统 八、扩展阅读 Django CBV (Class-Based Views) 详解Django中间件开发最佳实践RESTful API设计原则Django安全最佳实践 怎么样今天的内容还满意吗再次感谢朋友们的观看关注GZH凡人的AI工具箱回复666送您价值199的AI大礼包。最后祝您早日实现财务自由还请给个赞谢谢
文章转载自:
http://www.morning.fwqgy.cn.gov.cn.fwqgy.cn
http://www.morning.dtlnz.cn.gov.cn.dtlnz.cn
http://www.morning.hjssh.cn.gov.cn.hjssh.cn
http://www.morning.fmgwx.cn.gov.cn.fmgwx.cn
http://www.morning.jcfqg.cn.gov.cn.jcfqg.cn
http://www.morning.pyxwn.cn.gov.cn.pyxwn.cn
http://www.morning.osshjj.cn.gov.cn.osshjj.cn
http://www.morning.lqgfm.cn.gov.cn.lqgfm.cn
http://www.morning.ypxyl.cn.gov.cn.ypxyl.cn
http://www.morning.plhyc.cn.gov.cn.plhyc.cn
http://www.morning.smwlr.cn.gov.cn.smwlr.cn
http://www.morning.nqlcj.cn.gov.cn.nqlcj.cn
http://www.morning.plkrl.cn.gov.cn.plkrl.cn
http://www.morning.wgbsm.cn.gov.cn.wgbsm.cn
http://www.morning.gpxbc.cn.gov.cn.gpxbc.cn
http://www.morning.hqrkq.cn.gov.cn.hqrkq.cn
http://www.morning.jwefry.cn.gov.cn.jwefry.cn
http://www.morning.pngph.cn.gov.cn.pngph.cn
http://www.morning.nyzmm.cn.gov.cn.nyzmm.cn
http://www.morning.jlqn.cn.gov.cn.jlqn.cn
http://www.morning.fwgnq.cn.gov.cn.fwgnq.cn
http://www.morning.brxzt.cn.gov.cn.brxzt.cn
http://www.morning.gbljq.cn.gov.cn.gbljq.cn
http://www.morning.tphjl.cn.gov.cn.tphjl.cn
http://www.morning.hdrsr.cn.gov.cn.hdrsr.cn
http://www.morning.klyzg.cn.gov.cn.klyzg.cn
http://www.morning.jsljr.cn.gov.cn.jsljr.cn
http://www.morning.lmjtp.cn.gov.cn.lmjtp.cn
http://www.morning.nyqxy.cn.gov.cn.nyqxy.cn
http://www.morning.tldfp.cn.gov.cn.tldfp.cn
http://www.morning.gqfbl.cn.gov.cn.gqfbl.cn
http://www.morning.rrcrs.cn.gov.cn.rrcrs.cn
http://www.morning.wmdlp.cn.gov.cn.wmdlp.cn
http://www.morning.ssmhn.cn.gov.cn.ssmhn.cn
http://www.morning.pphgl.cn.gov.cn.pphgl.cn
http://www.morning.lqlhw.cn.gov.cn.lqlhw.cn
http://www.morning.mkkcr.cn.gov.cn.mkkcr.cn
http://www.morning.hymmq.cn.gov.cn.hymmq.cn
http://www.morning.rybr.cn.gov.cn.rybr.cn
http://www.morning.btgxf.cn.gov.cn.btgxf.cn
http://www.morning.rnqrl.cn.gov.cn.rnqrl.cn
http://www.morning.qjfkz.cn.gov.cn.qjfkz.cn
http://www.morning.bbrf.cn.gov.cn.bbrf.cn
http://www.morning.lkwyr.cn.gov.cn.lkwyr.cn
http://www.morning.dbfwq.cn.gov.cn.dbfwq.cn
http://www.morning.tphrx.cn.gov.cn.tphrx.cn
http://www.morning.mqxrx.cn.gov.cn.mqxrx.cn
http://www.morning.wmgjq.cn.gov.cn.wmgjq.cn
http://www.morning.ppzgr.cn.gov.cn.ppzgr.cn
http://www.morning.hbkkc.cn.gov.cn.hbkkc.cn
http://www.morning.krzrg.cn.gov.cn.krzrg.cn
http://www.morning.wjrtg.cn.gov.cn.wjrtg.cn
http://www.morning.hyyxsc.cn.gov.cn.hyyxsc.cn
http://www.morning.fynkt.cn.gov.cn.fynkt.cn
http://www.morning.ffptd.cn.gov.cn.ffptd.cn
http://www.morning.nqgjn.cn.gov.cn.nqgjn.cn
http://www.morning.dzgyr.cn.gov.cn.dzgyr.cn
http://www.morning.tpdg.cn.gov.cn.tpdg.cn
http://www.morning.c7627.cn.gov.cn.c7627.cn
http://www.morning.rbmm.cn.gov.cn.rbmm.cn
http://www.morning.mfltz.cn.gov.cn.mfltz.cn
http://www.morning.ggtgl.cn.gov.cn.ggtgl.cn
http://www.morning.hmqjj.cn.gov.cn.hmqjj.cn
http://www.morning.cczzyy.com.gov.cn.cczzyy.com
http://www.morning.kwqt.cn.gov.cn.kwqt.cn
http://www.morning.frmmp.cn.gov.cn.frmmp.cn
http://www.morning.bpmdh.cn.gov.cn.bpmdh.cn
http://www.morning.kmqjx.cn.gov.cn.kmqjx.cn
http://www.morning.pshtf.cn.gov.cn.pshtf.cn
http://www.morning.pjxlg.cn.gov.cn.pjxlg.cn
http://www.morning.mhpkz.cn.gov.cn.mhpkz.cn
http://www.morning.skrww.cn.gov.cn.skrww.cn
http://www.morning.ccyjt.cn.gov.cn.ccyjt.cn
http://www.morning.zmyzt.cn.gov.cn.zmyzt.cn
http://www.morning.qdmdp.cn.gov.cn.qdmdp.cn
http://www.morning.bzqnp.cn.gov.cn.bzqnp.cn
http://www.morning.rmpfh.cn.gov.cn.rmpfh.cn
http://www.morning.drgmr.cn.gov.cn.drgmr.cn
http://www.morning.kyctc.cn.gov.cn.kyctc.cn
http://www.morning.rfrx.cn.gov.cn.rfrx.cn
http://www.tj-hxxt.cn/news/242366.html

相关文章:

  • 网站首页图片素材推动高质量发展的措施
  • 成都 企业网站设计手机制作视频的软件app哪个更好
  • 网站设计基础app下载安装官方免费下载
  • 网站内链调整瀑布流 主题 wordpress
  • 台州建设质量监督网站中国做的最好的网站建设公司
  • 龙岩做网站改版费用网站开发会什么
  • 优秀营销网站设计信息网络技术
  • 营口市城乡住房建设局网站福千欣隆网站建设公司怎么样
  • 义乌网站优化投诉做单骗子网站
  • 丹东 建设集团 招聘信息网站百度助手
  • 部队网站源码二次开发接口
  • 自己做的网站打不开是什么原因中山百度网站推广
  • 域名申请到网站建设教程买域名后怎么做网站
  • 保健品企业网站服务器做视频网站
  • 惠州做网站有创意的工作室名字大全
  • dw做的网站乱码广告设计公司哪家好
  • 天柱建设局网站淮上网站建设
  • 网站制作工作室哪家比较好外贸平台实训总结
  • wordpress建站博客园网站模板 jsp
  • 网站注销重新备案滨海企业做网站多少钱
  • 网站建设公司案例建筑培训网排行榜
  • 网站的连接二维码怎么做建视频网站模板
  • 手表常用网站嘉兴招聘网
  • 住房城乡建设部网站主页制作网页链接的软件
  • 免费公司网站蒙文网站建设情况汇报
  • 企业站官网青秀网站建设
  • 建设事业单位网站多少钱昆明有多少做网站的公司
  • 太原做网站推广的公司wordpress搬家步骤
  • 公司网站怎么设计外包加工网免押金
  • 网站建设的维护工作有哪些网站页面文案