[Fixed]-Multi parameters in url django

1๐Ÿ‘

โœ…

You can perform this check by overriding the get_object() function of DetailView.

get_object() returns the object that the view is displaying. In your view, DetailView will perform object lookup by using the pk argument. Before this object retrieval process via pk, we will add a check to validate the value of point_id parameter in the url.

If point_id is valid, we call the super() method where normal object retrieval and validation by pk will occur. If point_id is invalid, we raise a Http404 exception.

from django.http import Http404

class MyView(DetailView):
    
    def get_object(self, queryset=None):
        point_id = self.kwargs.get('point_id')
        # write your logic to validate point_id here
        if not check_valid_point_id(point_id): # assumed 'check_valid_point_id' function validates point_id 
            raise Http404("Invalid point id") # raise 404 exception on invalid point_id
        return super(MyView, self).get_object(queryset) # call super() on valid point_id

Note: In the above code, i have assumed a check_valid_point_id() function which will take point_id as a argument will validate the point_id. You can add the logic for point_id validation in that function or write your own logic in the get_object() function itself.

๐Ÿ‘คRahul Gupta

0๐Ÿ‘

Django detail view expects to find only one url parameter. This is defined by the pk_url_kwarg of the DetailView (defaults to pk) or the slug_field and slug_url_kwarg (which defaults to slug).
In order to access any extra url parameters, you need to override the default DetailView methods. Which one, depends on what is affected by the extra url parameter. If the extra param affects the object that needs to be retrieved, then override the get_queryset method of the DetailView class. In there you can access parameters through the self.kwargs object.
If your url parameter is only needed as additional data to load (among maybe the primary object that is requested), then override the get_context_data method, the later can be overriden by the following way:

def get_context_data(self, **kwargs):
    context = super(YourClassView, self).get_context_data(**kwargs)
    # context now holds the context of your view, you can add extra data to
    # it with the following way:
    context['mydata'] = "Some data"
    # return the context
    return context

In the above example your pk will be available in the self.kwargs object.

๐Ÿ‘คpetkostas

Leave a comment