Question

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):
Was it helpful?

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

OTHER TIPS

I've never used CreateView, but here's what I gather from reading the docs:

You could do it by defining form_valid:

view:

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()

Then the template would be at 'yourappname/yourmodelhere_form.html'.

See CreateView for an example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top