Login

Tag "foreignkey"

Snippet List

Self-referencing Foreign Key Infinite Loop

Make sure we don't create an infinite loop with a self-referencing foreign key. Many times I have needed category models that reference themselves, providing a flexible way to make children categories, grandchildren categories, etc. If you chain the slugs (or even ids) there's a chance you could end up with an infinite loop. Assumes a required, unique slug field ('slug') and an optional self-referencing foreign key ('parent'). All_data doesn't give you the object's ID, so we will find it via the unique slug. If either is not present we pass -- if there's no parent chosen it's not a problem, and if there is no slug present the submission will fail on that validation instead. It is worth noting that if the user changes the slug field on submission AND picks a bad parent it will not be caught. Infinite loop cases: 1. A references A 2. A tries to reference B, which is currently referencing A

  • validator
  • foreignkey
Read More

Modify fields created by form_for_model

Using newforms you can create forms from existing models easily and automatically with either `form_for_model(class)` or `form_for_instance(instance)`. Usually the automagically generated form fields are sufficient; however, sometimes you need to restrict selections in a choice field. You can also set the default selection when instantiating the form. In this example, if `acct` is not contained in the 'account' field choices, the selection defaults to the first entry. This example is probably not good practice when using `form_for_instance` because the existing value 'selection' of the choice field is lost and must be reset manually (see above).

  • newforms
  • foreignkey
  • dropdown
  • choicefield
  • form_for_model
  • form_for_instance
Read More

ForeignKey dropdown selector

Most of the time when you want a dropdown selector based on a ForeignKey, you'll want to use [snippet #26](http://www.djangosnippets.org/snippets/26/) Here's an alternative approach, perhaps useful when you want to define choices once and reuse it in different views without overriding Form `__init__`.

  • dynamic
  • foreignkey
  • dropdown
  • choices
  • property
Read More

18 snippets posted so far.