Django - How to restrict foreign key choices in dr

2020-05-07 06:37发布

问题:


I have form for adding data in database and I want to restrict foreign key choices in my dropdown menu. It have to be restricted on my finishDate field. If finishDate is date before today (eg. today is 21-08-2016 and finishDate is 30-06-2013), then I don't want to show foreign key value of that finishDate. What is the easiest way to do this? I am relative new at this, so I need help.

models.py

class Account(models.Model):
     startDate = models.DateField(verbose_name="Start")
     finishDate = models.DateField(verbose_name="Finish")

     def __str__(self):
         return 'A{}'.format(self.id)

 class Net(models.Model):
     date = models.DateTimeField(default=datetime.now())
     MB = models.IntegerField(validators=[MinValueValidator(1)],default=randint(100,2000))
     idAccount = models.ForeignKey(Account, on_delete=models.CASCADE, verbose_name="Account")

     def __str__(self):
         return 'Record {}'.format(self.datum)

forms.py

class NetForm(ModelForm):
     class Meta:
         model = Net
         fields = ['idAccount']

views.py

@login_required(login_url="/accounts/login/")
def net(request):
    if request.method == 'POST':

        form = NetForm(request.POST)

        if form.is_valid():
            internet = form.save()
            return HttpResponseRedirect('/')

    else:
        form = NetForm()

    return render(request, 'project/Net.html', {'form': form})

Thanks a lot!

回答1:

You can filter it in the __init__

import datetime

def NetForm(forms.ModelForm):
    #...fields
    def __init__(self, *args, **kwargs):
        super(NetForm, self).__init__(*args, **kwargs)
        # Now set the queryset...
        self.fields['idAccount'].queryset = Account.objects.filter(finishDate__gte=datetime.datetime.now())