notGenius notGenius - 1 year ago 84
Python Question

Django - How to restrict foreign key choices in dropdown menu depending on datatime field

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.

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

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

class Net(models.Model):
date = models.DateTimeField(
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)

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

def net(request):
if request.method == 'POST':

form = NetForm(request.POST)

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

form = NetForm()

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

Thanks a lot!

Answer Source

You can filter it in the __init__

import datetime

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