I am building a web application and I finding there is a lot of replication in checking that the request.user matches the user who created the movie. Movie has a FK to the user so only users who created the specific movie can perform the appropriate actions on them.
@login_required
def edit_movie(request, slug, template_name="movies/edit_movie.html"):
movie = get_object_or_404(Movie, slug=slug)
if movie.user != request.user:
raise HttpResponseForbidden
# Rest of code omitted for brevity.
@login_required
def edit_screener(request, slug, template_name="movies/edit_screener.html"):
movie = get_object_or_404(Movie, slug=slug)
movie_media = movie.moviemedia_set.get(movie_type='screener')
if movie.user != request.user:
raise HttpResponseForbidden()
# Rest of code omitted for brevity.
@login_required
def dashboard(request, template_name='movies/dashboard.html'):
movies = Movie.objects.active().filter(
user=request.user).order_by('-created_at')
# Rest of code omitted for brevity.
I have a strong background in Ruby on Rails and we simply would use a before_filter :find_user on the controller so it avoided the duplication. What is the best way in Django to handle this sort duplication?
J
If it is ok to show a 404 instead of 403 you could do this: