如何在类基本视图中调用所有函数

时间:2019-04-25 06:49:49

标签: django python-3.x django-class-based-views

我是django的新手,到目前为止使用基于函数的视图。现在,我开始了基于类的基本视图,但是它们是如此令人困惑。像

class Newrecord(View):
    greeting="Hi" 
    def newPost(request):    
        deyCat = Category.objects.all() 
    def oldPost(request)
        deyold = OldCategory.objects.all() 


path('about/', Newrecord.as_view(greeting="G'day")),

现在如何从基于类的url访问这两个函数?还是我必须在课堂上实现何时执行哪个函数的逻辑?以及如何使用它们进行继承?

1 个答案:

答案 0 :(得分:1)

您可以通过http动词访问

class SoveView(View):

    def get(self, request):    
        return #somestuff

    def post(self, request)
        return #somestuff
path('about/' SomeView.as_view())

访问带有获取请求的about/ SomeView.get时将执行。 当带有about/ SomeView.post帖子的请求将被执行。

我认为您需要两个不同的类,因为您 有两个get端点,例如:

class NewPosts(View):
    def get(self, request):
        return #somestuff

class OldPosts(View):
    def get(self, request):
        return #somestuff

path('newposts/', NewPosts.as_view()),
path('oldposts/', OldPosts.as_view()),

如果NewPostsOldPosts具有某些常见行为,则可以创建一个 基类或一些辅助功能

class PostsMixin(View):
    def get(self, request):
        if request.user.username == 'fake':
         raise Exception()
        # do something


class NewPosts(PostsMixin):
    def get(self, request):
        super().get(request)
        return #somestuff

class OldPosts(PostsMixin):
    def get(self, request):
        super().get(request)
        return #somestuff

path('newposts/', NewPosts.as_view()),
path('oldposts/', OldPosts.as_view()),

一个简单的函数也可以代替基类工作

def common_stuff(request):
    if request.user.username == 'fake':
        raise Exception()
    # do something


class NewPosts(View):
    def get(self, request):
        common_stuff(request)
        return #somestuff

class OldPosts(View):
    def get(self, request):
        common_stuff(request)
        return #somestuff

path('newposts/', NewPosts.as_view()),
path('oldposts/', OldPosts.as_view()),

另一种方法可以使用相同的视图,但是将参数传递给该视图

class Posts(View):
    def get(self, request):
        type = request.GET.get('type', 'new') # get type query param, if is not present the default will be new
        if type == 'new': # /posts/?type=new
            result = Category.objects.all()
        elif type == 'old': #/posts/?type=old
            result = OldCategory.objects.all() 
        else:
            raise Http404() # just as example
        return #somestuff

path('posts/', NewPosts.as_view()),
class Posts(View):
    def get(self, request, type):
        if type == 'new': # /posts/?type=new
            result = Category.objects.all()
        elif type == 'old': #/posts/?type=old
            result = OldCategory.objects.all() 
        else:
            raise Http404() # just as example
        return #somestuff

path('posts/<str:type>/', NewPosts.as_view()),