(Django)当前用户在UpdateView中的有限ForeignKey选择

时间:2018-08-28 20:17:22

标签: python django

我最近能够弄清楚如何在CreateView中执行此操作,但是对于UpdateView却不起作用(这是在CreateView中如何执行此操作的原始文章:(Django) Limited ForeignKey choices by Current User

基本上,我需要它仅显示当前登录用户创建的Universe,但是默认情况下,它显示所有Universe。 当我尝试设置form_class并模仿CreatView的解决方案时,它会吐出一个配置错误的错误。

models.py

class Universe(models.Model):
    user = models.ForeignKey(User,related_name='universe',on_delete=models.CASCADE)
    name = models.CharField(max_length=100, unique=True)
    description = models.TextField(max_length=2000,blank=True,default="")    

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('universe:singleuniverse',kwargs={'pk': self.pk})

    class Meta:
        ordering = ['name']
        unique_together = ['user','name']

class Character(models.Model):
    user = models.ForeignKey(User,related_name='characters',on_delete=models.CASCADE)
    universe = models.ForeignKey("story_universe.Universe", on_delete=models.CASCADE)
    name = models.CharField(max_length=255,unique=True)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('character_developer:singlecharacter',kwargs={'pk': self.pk})

    class Meta():
        ordering = ['name']
        unique_together=['user','name']

views.py

class UpdateCharacter(LoginRequiredMixin,generic.UpdateView):
     model = Character
     fields = ('universe','name')
     template_name = 'character_developer/character_update_form.html'

更新 错误是:

错误:/ characters / update / 3 /配置不正确 UpdateCharacter缺少查询集。定义UpdateCharacter.model,UpdateCharacter.queryset或覆盖UpdateCharacter.get_queryset()。

这是出现错误的代码:

views.py:

class UpdateCharacter(LoginRequiredMixin,generic.UpdateView):
    template_name = 'character_developer/character_update_form.html'
    form_class = UpdateForm

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

forms.py

class UpdateForm(forms.ModelForm):
    def __init__(self,*args,**kwargs):
        user = kwargs.pop('user')
        super(UpdateForm,self).__init__(*args,**kwargs)
        self.fields['universe'].queryset = Universe.objects.filter(user=user)

    class Meta:
        model = Character
        fields = ('universe','name')

1 个答案:

答案 0 :(得分:2)

我相信您的views.py(几乎是CreateCharacter的确切扩展)中需要以下内容:

class UpdateCharacter(LoginRequiredMixin, generic.UpdateView):
    model = Character
    template_name ='character_developer/character_create.html'
    form_class = UpdateForm

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

    def form_valid(self,form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.save
        return super().form_valid(form)

我将对上述情况进行警告-确保请求对象中的用户实例是当前已登录用户的用户实例,并且具有足够的权限来更新其自己的用户-并且不能以某种方式代表他们发出请求。