Django表单:如何在下拉列表中仅显示与用户关联的对象

时间:2018-11-26 09:49:17

标签: django django-forms django-views django-shell

我是一所兽医医院,有宠物课和唱片课。每只宠物可以有很多记录,即每次去医院都会得到新的记录。

此刻,我的表单显示了与我的应用关联的所有宠物(请查看https://i.stack.imgur.com/8j7V8.png)。

我只希望显示用户注册的宠物(鲍勃为什么要把陌生人的猫带到兽医那里?)

查看以添加记录:

@login_required(login_url="/accounts/login/")
def record_create(request):
    #this line retrieves Pets only belonging to the user logged in
    pets = Pet.objects.filter(author=request.user)
    if request.method == 'POST':
        form = forms.CreateRecord(request.POST, request.FILES)
        print(form)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.author = request.user
            instance.save()
            return redirect('records')
    else:
        form = forms.CreateRecord()
    return render(request, 'records/record_create.html', {'form': form,})

forms.py

class CreateRecord(forms.ModelForm):
    class Meta:
        model = models.Record
        fields = ['feedID', 'amountLeftOver', 'amountDispensed', 'additionalInfo', 'selectPet']

models.py

class Pet(models.Model):
    petName = models.CharField(max_length=100, default='My Pet')
    petImage = models.ImageField(default='default.png', blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, default=None)

    def __str__(self):
        return self.petName

class Record(models.Model):
    feedID = models.AutoField(primary_key=True)
    dateTime = models.DateTimeField(auto_now_add=True)
    amountLeftOver = models.IntegerField(default='0')
    amountDispensed = models.IntegerField(default='0')
    additionalInfo = models.TextField(default=" ")
    selectPet = models.ForeignKey(Pet, on_delete=models.CASCADE)
    author = models.ForeignKey(User, on_delete=models.CASCADE, default=None)

如何获取selectPet下拉列表,以仅显示Bob的已注册宠物?

感谢您的时间!

1 个答案:

答案 0 :(得分:0)

您可以覆盖表单的__init__()方法以传递额外的参数,在这种情况下,您可以传递用户实例,并为下拉小部件设置查询集。

(不确定您如何将Pet模型与User模型相关联,以下示例假定您具有外键)

class CreateRecord(forms.ModelForm):

    class Meta:
        model = models.record
        fields = ['feedID', 'amountLeftOver', 'amountDispensed', 'additionalInfo', 'selectPet']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        user = self.kwargs.get('user')
        if user:
            self.fields['selectPet'].queryset = user.pet_set.all()