Is there before_filter in django as in rails?
Is there any feature available in django so that we can combine some filtering on all actions in the view of django, li开发者_开发知识库ke before_filter: is available in rails.
I'm still learning Rails but from what I've observed so far python decorators also seem to be used in Django in a very similar way to the before_filter in Rails.
Here's one example of it's usage in authenticating users: https://docs.djangoproject.com/en/1.2/topics/auth/#the-login-required-decorator
No. before_, around_ and after_ filter concepts aren't present in Django, but it isn't hard to write your own functions to do the same thing. There are also signals and generic views that might accomplish what you're needing to do.
decorators
can be used for this. your decorator can be the before_filter or after_filter depending on how whether it calls the decorated function first or last.
here is an example
@question_required
def show(request, question_id):
return HttpResponse(f'you are looking at {question_id}')
Here we have decorated the show function with question_required
and want it to act as a before_filter. so we will define the decorator like this:
def question_required(func):
def containing_func(*args, **kwargs):
request = args[0]
question_id = kwargs['question_id']
try:
question = Question.objects.get(pk=question_id)
except Exception as e:
raise e
return func(*args, **kwargs)
return containing_func
As you can see above the decorator is first checking for the question to exist in the db. If it exists it calls the actual show
function or it raises an exception.
In this way it acts like a before filter does in rails.
精彩评论