3

我正在构建一个 Web 应用程序,我发现在检查 request.user 是否与创建电影的用户匹配时有很多复制。电影对用户有一个 FK,因此只有创建特定电影的用户才能对其执行适当的操作。

@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.

我在 Ruby on Rails 方面有很强的背景,我们只需在控制器上使用 before_filter :find_user 以避免重复。Django 中处理这种重复的最佳方法是什么?

Ĵ

4

2 回答 2

4

如果可以显示 404 而不是 403 你可以这样做:

movie = get_object_or_404(Movie, slug=slug, user=request.user)
于 2012-11-24T23:06:03.810 回答
2

为什么不创建一个简单的函数来代替复制相同的代码呢?

def get_movie(slug, user):
    movie = get_object_or_404(Movie, slug=slug)
    if movie.user != user:
        raise Http403
    return movie
于 2012-11-24T23:15:56.430 回答