简体   繁体   English

我可以在views.py中使用类方法吗?

[英]Can I use class method in views.py?

Now my code is like: 现在我的代码是这样的:

def use_item(request):
    itemname = request.get('value')
    if itemname == 'item1':
        #do something
    if itemname == 'item2':
        #do something else

Can I do it in the following way? 我可以通过以下方式做到吗?

views.py views.py

class use_item():
    def use_item(self,request):
        itemname = request.get('value')
        use = getattr(self,itemname) # say itemname is 'item1'
        use()

    def item1(self,request):
        #do something

    def item2(self,request):
        #do something else

I've tried the second method but it seems that I was not doing it right. 我尝试了第二种方法,但似乎我做的不正确。 And the reason I want to do it in this way is that I hope to group the methods that they'd be more organized. 我之所以要这样做,是因为我希望对方法进行分组,使它们更加有条理。

the actual code 实际代码

#views.py
class use_item():
    def useitem(self,request):
        itemname = request.POST.get('value') 
        use = getattr(self,itemname)
        use()
    def jelly(self,request,topic_id):
        t = topic.objects.get(id=topic_id)
        t.top = True
        t.time_topped = datetime.datetime.now()
        t.save()

#urls.py
    url(r'^use/item/(?P<topic_id>\d+)/$', 'use_item.use_item', name='use_item'),

If you want to have a better organization of your code, and reuse some code accross different views, instead of pasting it where you need, you may use the Django class based views : 如果您想更好地组织代码,并在不同的视图之间重用一些代码,而不是将其粘贴到所需的位置,则可以使用基于Django类的视图

# views.py
from django.views import View

class use_item(View):

    def get(self, request, *args, **kwargs):
        itemname = request.POST.get('value')
        use = getattr(self,itemname)
        use()

    def item1(self,request):
        #do something

    def item2(self,request):
        #do something else

# urls.py
from package.views import use_item

urlpatterns = [
    # [...]
    url(r'^use/item/(?P<topic_id>\d+)/$', use_item.as_view(), name='use_item'),
    # [...]
]

But, if at some point you need to call item1() or item2() from another view (is it the reason you mentioned the other view jelly ?), you will see that it is not possible. 但是,如果在某个时候需要从另一个视图调用item1()item2() (这是您提到另一个视图jelly的原因吗?),您将看到不可能。

One solution could be moving the common methods in another class and make sure your views inherit it. 一种解决方案是将通用方法移到另一个类中,并确保您的视图继承它。 This is often called mixins in django world. 在django世界中,这通常称为mixins

# views.py
from django.views import View

class ItemsRelatedLMixin:
    def item1(self, request):
        #do something

    def item2(self, request):
        #do something else

class use_item(ItemsRelatedLMixin, View):

    def get(self, request, *args, **kwargs):
        itemname = request.POST.get('value')
        use = getattr(self,itemname)
        use()

class jelly(ItemsRelatedLMixin, View):

    def get(self, request, topic_id):
        t = topic.objects.get(id=topic_id)
        t.top = True
        t.time_topped = datetime.datetime.now()
        t.save()

Now, your views jelly and use_item call the common methods. 现在,您的视图jellyuse_item调用了常用方法。 Of course you can define new methods in a view to make them available only from that view. 当然,您可以在视图中定义新方法,以使其仅在该视图中可用。 You could also create class members to store values you use often etc. Keep in mind that each request received by Django will trigger creation of a new instance of your view class (you can't keep data stored between 2 requests in class members). 您还可以创建类成员来存储您经常使用的值等。请记住,Django收到的每个请求都将触发创建视图类的新实例(您不能将数据存储在类成员中的两个请求之间)。

In Django, view functions are usually organized in modules and not in classes. 在Django中,视图函数通常按模块而非类进行组织。

To keep things organized, use more than one views module: views.py , foo_views.py , bar_views.py , or: views/__init__.py , views/foo.py , views/bar.py . 为了使事情井井有条,请使用多个视图模块: views.pyfoo_views.pybar_views.py或: views/__init__.pyviews/foo.pyviews/bar.py

You need to provide the view in the signature of the class. 您需要在类的签名中提供视图。 ie: 即:

from django.views import [your_View_name] 

Then provide the same view in class definition; 然后在类定义中提供相同的视图;

class use_item(your_View_name):
    def useitem(self,request):
        itemname = request.POST.get('value') 
        use = getattr(self,itemname)
        use()

If you are defining your class for the same view, 如果您要为同一视图定义课程,

class use_item(self):
    def useitem(self,request):
        itemname = request.POST.get('value') 
        use = getattr(self,itemname)
        use()

You may refer Django docs on Class-Based-View for more in-depth knowledge. 您可以参考基于类的视图上的Django文档以获取更深入的知识。

UPDATE: 更新:

When you are calling your function useitem you need to use the instance of your class as follows: 调用函数useitem ,需要按如下方式使用类的实例:

user_instance = views.use_item()       //Create instance of your class
user_instance.useritem()               //call your function using above instance 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Django:当我使用基于类的视图时,如何在views.py 中获得“pk”? - Django: How Can I get 'pk' in views.py when I use class based views? 我可以将2个模型放在Django Views.py的单个类中吗? - Can I put 2 models in a single class in Django Views.py? 我可以使用views.py 文件来实际发送电子邮件吗? - Can i use the views.py file to actually send emails? 如何创建函数是views.py,以便views.py中的所有函数都可以使用它 - How to create a function is views.py so that all the functions inside the views.py can use it 我在 Django 中的 views.py 中的 Product 类的 changeStock 方法有问题 - I have an issue with the changeStock method of a Product class in views.py in Django 如何在Django的views.py中的一个类下显示模型和表单? - How can I display a model and a form under one class in views.py in Django? 我怎样才能为views.py编写更好的代码 - How can i write better Code for the views.py 如何在Django中从views.py中导入变量? - How can I import variables out of views.py in Django? 如何在 views.py 中创建 Django model? - How can I create a Django model in views.py? In Django views.py I create a session in method A and try to read it in class B. Error: attribute session not defined in class B - In Django views.py I create a session in method A and try to read it in class B. Error: attribute session not defined in class B
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM