删除django中的用户特定内容

时间:2015-03-23 09:27:41

标签: django django-authentication django-class-based-views

我的用户具有用户特定内容。我设法只在侧面显示用户特定数据,但是当用户想要删除某些内容时,他只需插入一个随机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 )

1 个答案:

答案 0 :(得分:2)

您可以将简单验证放入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

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