#25306: Should be an easier way to restrict the choices for a ForeignKey
-------------------------------+--------------------------------------
     Reporter:  CuriousG102    |                    Owner:  nobody
         Type:  New feature    |                   Status:  new
    Component:  contrib.admin  |                  Version:  1.8
     Severity:  Normal         |               Resolution:
     Keywords:                 |             Triage Stage:  Unreviewed
    Has patch:  0              |      Needs documentation:  0
  Needs tests:  0              |  Patch needs improvement:  0
Easy pickings:  0              |                    UI/UX:  0
-------------------------------+--------------------------------------

Comment (by CuriousG102):

 Anyone who googles this and finds themselves in the same rut, here's a
 useful stopgap. Override the ModelAdmin's form with a form subclassed off
 of this.


 {{{
 class LimitChoicesBaseForm(ModelForm):
     limit_choices_methods = []

     def __init__(self, data=None, files=None, auto_id='id_%s',
 prefix=None,
                  initial=None, error_class=ErrorList, label_suffix=None,
                  empty_permitted=False, instance=None):
         super(LimitChoicesBaseForm, self).__init__(data=data, files=files,
 auto_id=auto_id, prefix=prefix,
                                                    initial=initial,
 error_class=error_class, label_suffix=label_suffix,
 empty_permitted=empty_permitted, instance=instance)
         for method in self.limit_choices_methods:
             formfield = self.fields[method['field_name']]
             if hasattr(formfield, 'queryset'):
                 filter_q_object = method['method'](instance)
                 formfield.queryset =
 formfield.queryset.filter(filter_q_object)
 }}}

--
Ticket URL: <https://code.djangoproject.com/ticket/25306#comment:3>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-updates+unsubscr...@googlegroups.com.
To post to this group, send email to django-updates@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/069.3f1ed0945aabf9bae505773e183393a8%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to