删除 Django 中的用户特定内容

delete user specific content in django

我有具有用户特定内容的用户。我设法只在侧面显示特定于用户的数据,但是当用户想要删除某些内容时,他只需插入一个随机 ID 即可删除任何用户的所有内容。如何防止用户删除其他用户内容?

查看

class TodoView( LoginRequiredMixin, FormView ):
  form_class = TodoListForm
  success_url = reverse_lazy( 'todo' )
  template_name = 'todolist.html'

  def get_context_data( self, **kwargs ):
    trainee = Trainee.objects.get( user = self.request.user )
    context = super( TodoView, self ).get_context_data( **kwargs )
    context['learningobjective'] = LearningObjective.objects.filter( trainee = trainee.id )
    context['todolist'] = TodoList.objects.filter( trainee = trainee.id )
    return context

  def get_form_kwargs( self ):
    kwargs = super( TodoView , self ).get_form_kwargs()
    kwargs['user'] = self.request.user
    return kwargs

  def form_valid( self, form ):
    self.object = form.save( commit = False )
    if self.request.user.is_authenticated():
      self.object.trainee = Trainee.objects.get( user = self.request.user )
    self.object.save()
    form.save_m2m()
    return super( TodoView, self ).form_valid( form )

class DeleteTodo( LoginRequiredMixin, DeleteView ):
  model = TodoList
  success_url = reverse_lazy( 'todo' )
  template_name = 'deleteobject.html'

形式

class TodoListForm( ModelForm ):
  class Meta:
    model = TodoList
    fields = ( 'learning_objective', 'task', 'levy_date', 'priority', )

  def __init__( self, user, *args, **kwargs ):
    trainee = Trainee.objects.get( user = user )
    super( TodoListForm, self ).__init__( *args, **kwargs )
    self.fields['learning_objective'].queryset = LearningObjective.objects.filter( trainee = trainee.id )

您可以将简单的验证放入您的 DeleteTodo 视图中:

class DeleteTodo( LoginRequiredMixin, DeleteView ):
  model = TodoList
  success_url = reverse_lazy( 'todo' )
  template_name = 'deleteobject.html'

  def get_object(self):
    obj = super(DeleteTodo, self).get_object()
    if obj.trainee.user != self.request.user:
      return None # or raise Http404
    return obj

您还可以将查询集(通过 get_queryset 方法)指定到您的删除视图中,该视图将仅过滤用户对象。