Login

Tag "newforms"

Snippet List

assign fields dynamically in newforms

DynamicFieldSnippetForm demonstrates how to dynamically assign fields in newforms. 1. weight is a required static field 2. height is an optional dynamic field This example uses `request_height` as an optional keyword argument to declare whether the `height` field should be added to the form, but it's just there for demonstration purposes. If you decide to use a keyword argument in your code, be sure to pop it off (as demonstrated in the code) or you'll get an *unexpected keyword argument* error.

  • newforms
  • dynamic
  • fields
Read More

Getting dynamic model choices in newforms

This is an excerpt from the form code used on this site; the tricky bit here is making the `choices` for the `language` field get filled in dynamically from `Language.objects.all()` on each form instantiation, so that new languages can be picked up automatically. It also adds a blank choice at the beginning so that users can't accidentally ignore the field and incorrectly end up with whatever Language was first in the list. If you use this, always remember that you have to call the superclass `__init__` _before_ you set your dynamic choices, and that you need to accept `*args` and `**kwargs` so you can pass them to it. In theory, `ModelChoiceField` will solve this, but it still seems to be a bit buggy.

  • newforms
  • models
Read More

MultipleChoiceCommaField

MultipleChoiceCommaField - CheckboxSelectMultiple value sequence as a single string, comma-separated. Since I frequently want to store multiple-selected choice items as a single field in the model, I found it convenient to write a custom field class. The code uses the comma as a separator, but it could be easily generalized to use any delimiter.

  • newforms
  • checkbox
  • multiple
  • choice
  • selection
Read More

108 snippets posted so far.