我正在构建一个 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 中处理这种重复的最佳方法是什么?
Ĵ