Search code examples
pythondjangoclassdjango-generic-viewscreate-view

Django function based view to class based view


I have this url is http://127.0.0.1:8000/upload/picturelist/1, which makes user_id = 1,

In my urls.py

url(r'^picturelist/(?P<user_id>\d+)$', views.pictureList),

In my view.py

def pictureList(request, user_id):
    if int(user_id) != request.user.id:
        raise PermissionDenied

How can I make this function based view to use createview?

class pictureList(CreateView):

Solution

  • You could do something like this:

    In urls.py: url(r'^picturelist/(?P<user_id>\d+)$', views.MakeItView.as_view()),

    In views.py:

    class MakeItView(CreateView):
        model = myModel
        template_name = 'whatever.html'
    
        def get_context_data(self, **kwargs):
            context = super(MakeItView, self).get_context_data(**kwargs)
            if int(self.kwargs['user_id']) != self.request.user.id:
                raise PermissionDenied
            return context