基于Django函数的视图到基于类的视图

时间:2014-01-25 03:00:58

标签: python django class django-generic-views create-view

我的网址是http://127.0.0.1:8000/upload/picturelist/1,这使得user_id = 1,

在我的urls.py中

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

在我的view.py

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

如何使这个基于函数的视图使用createview?

class pictureList(CreateView):

2 个答案:

答案 0 :(得分:0)

我从未使用CreateView,但这是我从阅读文档中收集到的内容:

您可以通过定义form_valid

来实现

查看:

class pictureList(CreateView):
  model = YourModelHere
  fields = ['whatever','fields','you','want','edited']

  def form_valid(self, form):
    record = form.save(commit = False)

    # assuming the user id is associated 
    # to the model with fieldname user_id

    if (self.request.user == record.user_id):
      record.save()
      return HttpResponseRedirect(self.get_success_url())
    # not sure if this works:
    return self.form_invalid()

然后模板将在'yourappname/yourmodelhere_form.html'

有关示例,请参阅CreateView

答案 1 :(得分:0)

你可以这样做:

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

在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