Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRYing up Django views request.user object

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

like image 214
tdelam Avatar asked Jun 28 '26 17:06

tdelam


1 Answers

If it is ok to show a 404 instead of 403 you could do this:

movie = get_object_or_404(Movie, slug=slug, user=request.user)
like image 125
relekang Avatar answered Jun 30 '26 08:06

relekang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!