简单来说,Django 通用视图是什么?

发布于 2024-08-24 19:22:19 字数 357 浏览 8 评论 0原文

本页的前两段解释了通用视图应该让我的生活更轻松,不那么单调,并使我对女性更有吸引力(最后一段是我编造的):

https://docs.djangoproject.com/en/1.4/topics/generic-views/

我全力以赴改进我的生活,但是通用视图实际上做了什么?似乎有很多流行语被抛出,但它们所带来的困惑比它们所解释的还要多。

通用视图是否类似于 Ruby on Rails 中的脚手架?简介中的最后一个要点似乎表明了这一点。这是一个准确的说法吗?

The first two paragraphs of this page explain that generic views are supposed to make my life easier, less monotonous, and make me more attractive to women (I made up that last one):

https://docs.djangoproject.com/en/1.4/topics/generic-views/

I'm all for improving my life, but what do generic views actually do? It seems like lots of buzzwords are being thrown around, which confuse more than they explain.

Are generic views similar to scaffolding in Ruby on Rails? The last bullet point in the intro seems to indicate this. Is that an accurate statement?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

吐个泡泡 2024-08-31 19:22:20

Django 通用视图只是视图函数(常规的旧 Python 函数),它们执行 Web 应用程序中非常常见的操作。

根据您正在构建的应用程序的类型,它们可以使您免于编写大量非常简单的视图。

例如,direct_to_template 通用视图仅使用 RequestContext 呈现模板(这意味着模板可以访问有关请求的信息,例如当前用户等)。

举一个简单的例子,您可以从这样编写:

# urls.py
url('^some-url/

到这样:

# urls.py
url('^some-url/

对于常见操作,例如“显示模型列表”或“将模型添加到数据库”,还有更复杂的通用视图。

另外,因为通用视图只是函数,所以当您需要与通用情况稍有不同的东西时,您可以在自己的视图函数中调用它们来完成“大部分工作”。

, some_view) # views.py def some_view(request): return render_to_response('template_name.html', context_instance=RequestContext(request))

到这样:


对于常见操作,例如“显示模型列表”或“将模型添加到数据库”,还有更复杂的通用视图。

另外,因为通用视图只是函数,所以当您需要与通用情况稍有不同的东西时,您可以在自己的视图函数中调用它们来完成“大部分工作”。

, direct_to_template, {'template': 'template_name.html'}) # views.py doesn't need any code for this view anymore

对于常见操作,例如“显示模型列表”或“将模型添加到数据库”,还有更复杂的通用视图。

另外,因为通用视图只是函数,所以当您需要与通用情况稍有不同的东西时,您可以在自己的视图函数中调用它们来完成“大部分工作”。

, some_view) # views.py def some_view(request): return render_to_response('template_name.html', context_instance=RequestContext(request))

到这样:

对于常见操作,例如“显示模型列表”或“将模型添加到数据库”,还有更复杂的通用视图。

另外,因为通用视图只是函数,所以当您需要与通用情况稍有不同的东西时,您可以在自己的视图函数中调用它们来完成“大部分工作”。

Django generic views are just view functions (regular old python functions) that do things that are very common in web applications.

Depending on the type of app you are building, they can save you from writing a lot of very simple views.

For example, the direct_to_template generic view simply renders a template with the RequestContext (which means the template has access to information on the request, like the current user, etc).

As a simple example, you can go from writing things like this:

# urls.py
url('^some-url/

To just this:

# urls.py
url('^some-url/

There are also more complicated generic views for common actions such as "showing a list of models", or "adding a model to the db".

Also, because generic views are just functions, you can call them within your own view functions to do "most of the work", when you need something that is a bit different from the generic cases.

, some_view) # views.py def some_view(request): return render_to_response('template_name.html', context_instance=RequestContext(request))

To just this:


There are also more complicated generic views for common actions such as "showing a list of models", or "adding a model to the db".

Also, because generic views are just functions, you can call them within your own view functions to do "most of the work", when you need something that is a bit different from the generic cases.

, direct_to_template, {'template': 'template_name.html'}) # views.py doesn't need any code for this view anymore

There are also more complicated generic views for common actions such as "showing a list of models", or "adding a model to the db".

Also, because generic views are just functions, you can call them within your own view functions to do "most of the work", when you need something that is a bit different from the generic cases.

, some_view) # views.py def some_view(request): return render_to_response('template_name.html', context_instance=RequestContext(request))

To just this:

There are also more complicated generic views for common actions such as "showing a list of models", or "adding a model to the db".

Also, because generic views are just functions, you can call them within your own view functions to do "most of the work", when you need something that is a bit different from the generic cases.

陌伤ぢ 2024-08-31 19:22:20

通用视图允许您编写更短的代码。

Compare:

from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response, get_object_or_404, redirect
from myapp.models import Context

def edit(request, item_id):
    object = get_object_or_404(Context, pk=item_id)

    if request.method == 'POST':
        form = ContextForm(request.POST, instance=object)
        if form.is_valid():
            form.save()
            return redirect('myapp-context-index')
    else:
        form = ContextForm(instance=object)

    return render_to_response("myapp/context/edit.html", {'object': object, 'form': form})

with:

from django.core import urlresolvers
from django.views.generic.create_update import update_object
from myapp.models import Context

def edit(request, item_id):    
    return update_object(request,
        object_id=item_id,              
        form_class=ContextForm,            
        template_name="myapp/context/edit.html",
        post_save_redirect=urlresolvers.reverse("myapp-context-index")
    )

就像你的正常视图一样,它们只是正常的函数。如果您愿意,可以在 URLconf 中完全配置视图,通过我发现上面的用法更清晰一些。

作为奖励,您还可以获得:

  • 登录身份验证检查(通过 login_required=True
  • 来自 django.contrib.messages 的成功状态消息。
  • 检查错误的代码更少。
  • 当您提供 model 参数而不是 form_class 时,默认的 ModelForm

template_name 默认值为“appname/model_form.html”,但这对我来说有点太多了。


这是他们共享的表单类:

class ContextForm(forms.ModelForm): 
    """The form for a context"""
    class Meta:
        model = Context
        exclude = ('collection',)

    def save(self, commit=True):
        """Overwritten save to force collection_id to a value"""
        model = super(ContextForm, self).save(commit=False)
        model.collection_id = 1
        if commit:
            model.save()
        return model

Generic views allow you to write much shorter code.

Compare:

from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response, get_object_or_404, redirect
from myapp.models import Context

def edit(request, item_id):
    object = get_object_or_404(Context, pk=item_id)

    if request.method == 'POST':
        form = ContextForm(request.POST, instance=object)
        if form.is_valid():
            form.save()
            return redirect('myapp-context-index')
    else:
        form = ContextForm(instance=object)

    return render_to_response("myapp/context/edit.html", {'object': object, 'form': form})

with:

from django.core import urlresolvers
from django.views.generic.create_update import update_object
from myapp.models import Context

def edit(request, item_id):    
    return update_object(request,
        object_id=item_id,              
        form_class=ContextForm,            
        template_name="myapp/context/edit.html",
        post_save_redirect=urlresolvers.reverse("myapp-context-index")
    )

Like your normal views, they are just normal functions. It is possible to configure the view completely in the URLconf if you like, through I find this usage above a bit more clear.

As a BONUS, you also get:

  • Login authentication checks (pass login_required=True)
  • Success status message from django.contrib.messages.
  • Less code to check for errors.
  • A default ModelForm when you provide a model parameter instead of form_class.

The template_name has a default of "appname/model_form.html", but that's a bit too much for me.


Here is the form class they both share:

class ContextForm(forms.ModelForm): 
    """The form for a context"""
    class Meta:
        model = Context
        exclude = ('collection',)

    def save(self, commit=True):
        """Overwritten save to force collection_id to a value"""
        model = super(ContextForm, self).save(commit=False)
        model.collection_id = 1
        if commit:
            model.save()
        return model
故人的歌 2024-08-31 19:22:20

回答你的第二个问题:不,通用视图与 RoR 中的脚手架无关。顾名思义,脚手架类似于代码生成。通用视图是另一回事。

我对通用视图的主要用途是作为非常基本的 render_to_response 函数的更高级别替换。这就是您如何使用render_to_response编写一个简单的视图:

def my_view(request):
    return render_to_response('my_template.html')

但这非常基本!例如,模板将无权访问请求上下文,除非您显式传递它。

因此,我更喜欢使用通用视图:

def my_view(request):
    return direct_to_template(request, template='my_template.html')

现在请求上下文将被传递!这只是一个开始。例如,当您想要显示列表或详细视图时,通用视图会派上用场。他们将管理查询数据库、向用户发送消息等。

因此,通用视图是高级函数,可帮助您从视图创建响应。

To answer your second question: no, generic views are not related to scaffolding in RoR. Scaffolding, as the name indicates, is akin to code generation. Generic views are something else.

My main usage of generic view is as a higher level replacement of the very basic render_to_response functions. This is how you could write a simple view with render_to_response:

def my_view(request):
    return render_to_response('my_template.html')

But this is very basic! For example the template will not have access to the request context, unless you pass it on explicitly.

I thus prefer to use a generic view instead:

def my_view(request):
    return direct_to_template(request, template='my_template.html')

Now the request context will be passed on! And that's just a start. Generic views come in handy when you want to display lists, or detail views, for instance. They will manage querying the database, and messaging the user, among other.

So generic views are high level functions to help you creating a response from a view.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文