Snippet List
This is a ModelChoiceField where the choices are rendered in optiongroups
(this is already posible with a normal Choicefield)
For this to work properly the queryset you supply should already be ordered
the way you want (i.e. by the group_by_field first, then any sub-ordering)
This is a ModelChoiceField where the choices are rendered in optiongroups
(this is already posible with a normal Choicefield)
For this to work properly the queryset you supply should already be ordered
the way you want (i.e. by the group_by_field first, then any sub-ordering)
See [related blog article](http://anentropic.wordpress.com/2010/03/23/django-optiongroups-for-your-modelchoice-field/)
- modelchoicefield
- optiongroup
Example view code:
lazy_field_options = {
'field_name_that_is_m2m': {
'queryset': YourRelatedModel.objects.filter(groups=request.user.groups.all()),
},
'field_name_that_is_fk': {
'queryset': YourOtherRelatedModel.objects.filter(slug=request_slug),
},
}
modelform = YourModelForm(jpic_field_options=lazy_field_options)
# after the modelform has called for parent __init__, it will set
# options for each field if possible.
- hack
- form
- queryset
- modelchoicefield
- modelform
- modelmultiplechoicefield
This replaces the html select box for a foreign key field with a link to that object's own admin page. The foreign key field (obviously) is readonly.
This is shamelessly based upon the [Readonly admin fields](http://www.djangosnippets.org/snippets/937/) snippet. However, that snippet didn't work for me with ForeignKey fields.
from foo.bar import ModelLinkAdminFields
class MyModelAdmin(ModelLinkAdminFields, admin.ModelAdmin):
modellink = ('field1', 'field2',)
- admin
- field
- widget
- readonly
- modelchoicefield
**The problem**
ModelChoiceField always uses __unicode__ or __str__ to fill the labels. I needed to dynamically select which field to use for the labels.
**The solution**
My approach copies a lot from [this blog](http://oebfare.com/blog/2008/feb/23/overriding-modelchoicefield-labels/) with some modifications to make it more dynamic.
There are some proposals to fix on this [Ticket #4620](
http://code.djangoproject.com/ticket/4620)
**How to use**
Include the code on your forms.py (or whatever you are using) and use the CustomChoiceField with the extra argument label_field instead of ModelChoiceField.
Hope it helps someone.
- newforms
- forms
- modelchoicefield
- modelform
ModelChoiceField allows you to use filtered queries to simplify your forms. This is great for adding objects but can fall down when you edit an existing object and the original query no longer contains the referenced field (e.g. I like to use an "active" field in several objects).
The fix is simply to include an extra param: Q(pk=object_id). You have to do this in the __init__ method to get the object_id.
A nice thing about this is that it works for ModelForms as well as custom Forms.
- newforms
- modelchoicefield
- modelform
6 snippets posted so far.