Django: Filtering a ModelForm field

So something what should be so relatively easy can turn out to be quite hard when you don’t know where to go for the answer. Generally the #django channel on IRC is an awesome help, but this morning I felt invisible so I can too keep digging. Finally I found my answer in code from another project.

Here’s the situation. I’m creating a budget system. When you add or import transactions from your bank, you need to tell it what bank account the transactions are associated with. I have the following models: Bank, BankAccount, Transaction. Transaction has a foreign key to BankAccount.

I have a ModelForm name AddTransactionForm. The problem was that when I went to add a transaction, it would show me all the accounts of other users. I needed to somehow filter the queryset that was applied to the account foreign key. I couldn’t find this anywhere in the docs, and like I mentioned, no one was even acknowledging me in IRC, which is rare. I finally found something similar I did for HouseSheet.com. Here was is my “fixed” form class:

class AddTransactionForm(ModelForm):
  def __init__(self, user, *args, **kwargs):
    super(AddTransactionForm, self).__init__(*args, **kwargs)
    self.fields['account'] = forms.ModelChoiceField(queryset=BankAccount.objects.filter(user=user))

  class Meta:
    model = Transaction
    exclude = ('envelope',)

So now, when I call this, I just need to pass in the the logged in user to show only that user’s accounts like so:
form = ImportForm(user=request.user)

I think my biggest problem with this was I haven’t yet mastered the python language so I wasn’t sure how to pass in the user object I need to filter on.

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

March 10, 2009 · Dustin · 13 Comments
Tags:  · Posted in: Programming & Internet

  • Fernando

    If the field is already defined (in the Model as a ForeignKey) you can directly use:

    self.fields['account'].queryset = BankAccount.objects.filter(user=user)

  • http://www.nerdydork.com Dustin

    That’s a bit of a shortcut. Thanks Fernando.

  • farout

    Hi Dustin,

    I think housesheet rocks – great job!. I am a newbie to Django. In a former life I used datagrids in asp.net so when I saw this – it is perfect for a project that I would like to try to do.

    Are you using jqgrid to do this? If not, what did you use? I apologize if I am asking for the secret sauce. I hope I am not. You have a lot going on with the housesheet. It was one of the best apps that I have seen for the web (django or RoR). I too am switching from rails to django. The admin function is too awesome.

    Any chance I can have the source code (not for commercial use but as a tool for me to learn). I am tired of the Django blog/social media tutorials.

    Thanks, Farida

  • farout

    Not sure if email came though

  • http://www.propeller.com/member/timelessrides/ Daniel

    I found this while stumbling the web looking for php info. I’m quite unhappy with php/MySQL and looking for an alternative. A friend suggested Ruby on Rails, and while googling I found Django. It looks liek you can still use SQl statements with this, which means I could slowly learn the programming and incorporate it slowly?

  • http://www.inin.com whitey@Call Center Software

    I’m just starting to learn ruby on rails too. Among other languages (ruby is a framework), Ruby can do quite a bit all at once. I have not tried #django but seeing this post has me interested.

  • http://www.badcreditloancenter.com Daniel@Bad Credit Loans

    Whitey Ruby is good buy Django gives you much more ability IMO once you learn the ropes.

  • http://leon-huang.com/ Leon Huang@Singapore Photographer

    Hmmm looks like Ruby on Rails is really quite cool.

  • http://aviary.com/artists/gregorlily Stacy H

    Thanks for the tip, it really helped alot

  • http://www.thekellerboard.com Keller Tx

    Php.net is great for php too. LOL @ your title…nerdy dork…awesome!

  • http://www.herkules.us/lifts Jenny@ Lift Tables

    Whitney…

    My vote is for Ruby on rails too. It is not as hard to learn the code as some people suggest. It has so much flexibility compared to other options.

  • http://texas-car-insurances.blogspot.com/ Mustana@Texas Car Insurance

    Why Rails?? I think every developer wants to speed up the development process at the same reducing error occurrence. Rails provide fast and easy development with quality results. If quality is retained but the speed is increased multifold you don’t need to think over it but just go for it, here comes RoR.

  • http://www.healthclubhut.com/ John Johnson

    Thats great as long as your bank doesn’t sink like the rest seem to be, ;-)