Silwest
Silwest

Reputation: 1620

Django form - filter foreignkey in model

Let's assume that we have 2 models:

class Entry(models.Model):
    number = models.IntegerField(blank=True, null=True, verbose_name="#")
    product = models.ForeignKey(Application, blank=True, null=True, verbose_name='Application')

class Application(models.Model):
    name = models.CharField(max_number=100)
    defaultCalendar = models.ForeignKey(Calendar)
class Calendar(models.Model):
    name = models.CharField(max_number=100)

And form:

class EntryForm(ModelForm):

class Meta:
    model = Entry
    fields = {'product ', 'number'}

1) In the documentation we can read that using fields we can change the ordering of the model, however in this example it doesn't work :(

2) Is there a way to filter product in my Form ? In the views with model I can do that this way

def somefunction(request, val1, val2):
    products = Application.objects.filter(defaultCalendar=request.user.get_profile().defaultCalendar)

get_profile is a function which returns profile of the user.

Anyway to do that in Form? The filter argument must be connected with usere who executed the function.

Thanks in advance

Upvotes: 0

Views: 118

Answers (1)

Alvaro
Alvaro

Reputation: 12037

1) it doesn't work because "fields" should be a list:

fields = ['product ', 'number', ]

2)

You can use:

form.fields["product"].queryset = your_queryset

Upvotes: 4

Related Questions