我正在构建一个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处理这种重复的最佳方法是什么?
Ĵ
答案 0 :(得分:4)
如果可以显示404而不是403,则可以执行此操作:
movie = get_object_or_404(Movie, slug=slug, user=request.user)
答案 1 :(得分:2)
为什么不创建简单的函数来代替复制相同的代码?
def get_movie(slug, user):
movie = get_object_or_404(Movie, slug=slug)
if movie.user != user:
raise Http403
return movie