Django 学习笔记(十五②)

Two scoops of Django 1.5第八章混合类,原先说实在的真是没接触过mixin(混合类),现在就翻译这一部分吧

mixins(混合类)

在程序设计中,混合类提供的功能是可继承的,但它本身不能被实例化。在编程语言使用多重继承,   

混合类是实现聚类一种手段。

当使用混合类合成自己的视图类,我们推荐Kenneth Love提出的继承规则。这些规则遵循Python的方法规则,

尽可能用最简单的定义方式,方法解析是从左到右(也就是说继承类是混合类在左边,普通类在右边):

注:所说的方位都是继续的类的设置方位

Django基础视图类总是放在右边

混合类在基础视图的左边

混合类继承于Python内建object类型

下面给出实例:

from django.views.generic import TemplateView
class FreshFruitMixin(object):
def get_context_data(self, **kwargs):
context = super(FreshFruitMixin,self).get_context_data(**kwargs)
context["has_fresh_fruit"] = True
r
return context

class FruityFlavorView(FreshFruitMixin, TemplateView):
template_name = "fruity_flavor.html"
   

在上面相当silly的列子中,这FruityFlavorView 类是从  FreshFruitMixin 和 TemplateView继承而来的。因为TemplateView

是基础视图类所提供,它被放在最右,我们把FreshFruitMixin放在最左。我们知道这一方式我们的方法与性能都将执行顺畅。

Which Django CBV Should Be Used For What Task?

对与确定在哪里使用哪一视图对于开发者来说是很有挑战性的一些观点是显而易的,比如那些执行操作,创建、读取、更新或删除数据

的操作,但是其他的操作就比较难以确定

此处有一便捷图表其列出其名称,以及每一Django CVBs的目的。所以列出的视图都被假设为Django.views.generic的前缀。

NamepurposeTwo Scoops Example
View 基础视图可以被重用到任何地方See the section called Implementing a
Simple JSON API.
RedirectView重定向到其他UrlSend users who visit ‘/log-in/’ to ‘/login/’.
TemplaetView展示Django HTML模版The ‘/about/’ page of our site.
ListView列出objectsList ice cream flavors.
DetailView列出一个objectDetails on an ice cream flavor
FormView提交一表单The site's contact or email form.
CreateView创建一对象实例Create a new ice cream flavor
UpdateView更新一对象实例Update an existing ice cream flavor.
DelteView删除一对象实例Delete an unpleasant ice cream flavor
like Vanilla Steak.
Generic date ViewsFor display of object that occur over a range of timeBlogs are a common reason to use
them. For Two Scoops, we could create a
nice, public history of when flavors were
added to the database.

Generals Tips For Django CBVs 

这一部分涵盖对于大多数Django CBVs开发 有用的建议

Constranging Django CBV Access to Aunthentication Users

虽然Django CBV文档提供了一个django.contrib.auth.decorators.login_required CBVs应用的例子,这使用起来很不方便。幸运的是,django-braces提供了一个现成的实现方式,您可以随时使用。例如:

# flavors/views.py
from django.views.generic import DetailView
from braces import LoginRequiredMixin
from .models import Flavor
class FlavorDetailView(LoginRequiredMixin, DetailView):
model = Flavor

TIP:不要忘记CBV 混合类的要求!

记住:

LoginRequiredMixin 必须在左边

基础视图类必须在右边

如果忘记或者改变规则,那么将引起不可预估的结果

依据表单在视图中定制逻辑操作

当您需要在一个视图中执行一个自定义操作时CBV工作流发送form_valid()方法请求。返回django.http.HttpResponseRedirect。

from django.views.generic import CreateView
from braces.views import LoginRequiredMixin
from .models import Flavor
class FlavorCreateView(LoginRequiredMixin, CreateView):
model = Flavor
def form_valid(self, form):
# Do custom logic here
return super(FlavorCreateForm, self).form_valid(form)

为无效表单在视图中定义操作

当你需要为无效表单在视图中执行自定义操作,form_invalid()方法是从Django CBV工作流发出request。这一方法返回django.http.HttpResponse

from django.views.generic import CreateView
from braces.views import LoginRequiredMixin
from .models import Flavor
class FlavorCreateView(LoginRequiredMixin, CreateView):
model = Flavor
def form_invalid(self, form):
# Do custom logic here
return super(FlavorCreateForm, self).form_invalid(form)


这一章总算翻译出来了,我了个艹,居然3:16了,汗!


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Two Scoops of Django 1.11 Will Help You Build Django Projects. In this book we introduce you to the various tips, tricks, patterns, code snippets, and techniques that we've picked up over the years. We have put thousands of hours into the fourth edition of the book, writing and revising its material to include significant improvements and new material based on feedback from previous editions. Table of Contents Chapter 1: Coding Style Chapter 2: The Optimal Django Environment Setup Chapter 3: How To Lay Out Django Projects Chapter 4: Fundamentals of Django App Design Chapter 5: Settings and Requirements Files Chapter 6: Model Best Practices Chapter 7: Queries and the Database Layer Chapter 8: Function- and Class-Based Views Chapter 9: Best Practices for Function-Based Views Chapter 10: Best Practices for Class-Based Views Chapter 11: Form Fundamentals Chapter 12: Common Patterns for Forms Chapter 13: Templates: Best Practices Chapter 14: Template Tags and Filters Chapter 15: Django Templates and Jinja2 Chapter 16: Building APIs with Django Rest Framework Chapter 17: Consuming REST APIs Chapter 18: Tradeoffs of Replacing Core Components Chapter 19: Working With the Django Admin Chapter 20: Dealing with the User Model Chapter 21: Django's Secret Sauce: Third-Party Packages Chapter 22: Testing Chapter of Doom! Chapter 23: Documentation: Be Obsessed Chapter 24: Finding and Reducing Bottlenecks Chapter 25: Asynchronous Task Queues Chapter 26: Security Best Practices Chapter 27: Logging: Tips and Tools Chapter 28: Signals: Use Cases and Avoidance Techniques Chapter 29: What About Those Random Utilities? Chapter 30: Deployment: Platforms as a Service Chapter 31: Deploying Django Projects Chapter 29: Identical Environments: The Holy Grail Chapter 32: Continuous Integration Chapter 33: The Art of Debugging Chapter 34: Where and How to Ask Django Questions Chapter 35: Closing Thoughts Appendix A: Packages Mentioned In This Book Appendix B: Troubleshooting Appendix C: Additional Resources Appendix D: Internationalization and Localization Appendix E: Settings Alternatives Appendix F: Working with Python 2 Appendix G: Channels and Websockets What People Say About Two Scoops of Django This is the swiss army knife for every Django developer. -- Jannis Gebauer, djangopackages.org maintainer and pyup.io founder We buy this book for every new engineer on our team. It's a must for Django development! -- Jacinda Shelly, CTO of Doctor On Demand I wanted to write a book about best practices in Django, except Two Scoops is that book, no need to write another one. -- Buddy Lindsey, Host of GoDjango Audrey's illustrations reinforce Audrey and Daniel's Django technical excellence. (Art + ice cream) * 2 tech experts = Two Scoops of Django. -- Carol Willing, Project Jupyter Core Dev and Python Software Foundation director Simply the best book on Django. Whenever I am not sure if I am following the best practices, I look up the topic in this book. A must read. -- Abu Ashraf Masnun, programmer

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值