0

So first of all I admit I use CBV in django and I don't fully understand it.

I have a delete view implemented with CBV - I am trying to pass extra parameter uri (this parameter is a current URL from where delete have been called, this way after delete will get performed user will return to the same place from where he started.)

This is my url.py

url(r'^category/delete/(?P<pk>\d+)/(?P<uri>\S+)/$', item.views.CategoryDelete.as_view(),
    name='category_delete',),

and this is my view.py I am inheriting delete view functionality

class CategoryDelete(DeleteView):
    model = Category
    success_url = reverse_lazy(uri)

    def delete(self, uri, request, *args, **kwargs):
        try:
            return super(CategoryDelete, self).delete(
                request, *args, **kwargs
            )
        except models.ProtectedError as e:

            return HttpResponse(json.dumps(escape(e)))

Current code obviously gives me an error that uri is not defined. So the question is how to transfer additional parameter into the View class if I want to use success_url ? Or there is a better way?

1 Answer 1

1

Trying to set success_url will not work, because it is processed when the module is loaded, not when the request is handled. Override get_success_url instead.

You can access positional and keyword arguments from the url from self.args and self.kwargs respectively.

def get_success_url(self):
    return reverse(self.kwargs['uri'])
Sign up to request clarification or add additional context in comments.

5 Comments

thanks I thought I cant do it since since I have to create instance first. When I try your code I am getting this error: Exception Type: NoReverseMatch Exception Value: Reverse for 'uri' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Should I also do some changes in my url.py ?
If you are using reverse, the uri should be the name of the url pattern. If it's not a url pattern name, then you shouldn't be using reverse at all. Note that it's more common to include the next url as a GET parameter e.g. ?next=/home/, rather than in the url itself.
I need whole URL since I am using filter so my users works only with data they have filtered ,and filter parameters are inside URL if I use reverse I will loose the filter values I assume
That's right, reverse would not return GET parameters.
Ok so I learned a great deal by investigating this topic and came to conclusion to eliminate CBV all together as unnecessary complexity. I will try to stick to FBV views only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.