New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Filter choices in model form #767
Comments
I'm not 100% but this looks like how I would expect it to work: https://forum.djangoproject.com/t/how-to-filter-the-choices-in-forms-select-widget/19974/4 |
I tried this and it didn't work, i can create a pr that we can debug together. Maybe i am doing something wrong |
I tried to do the leg-work and it is quite interesting actually. It seems to come down to a conscious choice by django: class ChoiceField(Field):
# ...
@choices.setter
def choices(self, value):
# Setting choices on the field also sets the choices on the widget.
# Note that the property setter for the widget will re-normalize.
self._choices = self.widget.choices = normalize_choices(value) The "field" that is meant here, according to my investigation, is the model-field because the stack-trace in question looks as follows (Comment from my side: This feels buggy and not intended, but maybe it is?!):
The callstack indicates that Baby buddy sets choices on the model field: Lines 237 to 247 in 2d1338a
How to get it to workHowever, independent from my finding above (or coming forth out it), this does the trick: Setting the "choices" not on the widget but on the form-field! class BottleFeedingForm(CoreModelForm, TaggableModelForm):
def save(self):
instance = super(BottleFeedingForm, self).save(commit=False)
instance.method = "bottle"
instance.end = instance.start
instance.save()
return instance
type = ChoiceField(
choices=(
("breast milk", _("Breast milk")),
("formula", _("Formula")),
("fortified breast milk", _("Fortified breast milk")),
),
)
class Meta:
model = models.Feeding
fields = ["child", "start", "type", "amount", "notes", "tags"]
widgets = {
"child": ChildRadioSelect,
"start": DateTimeInput(),
"notes": forms.Textarea(attrs={"rows": 5}),
} |
Bottle feeding, has an option of solid food which makes no sense :).
I would like to filter that option out for bottle feeding for specifically i have tried every option on the internet
https://forum.djangoproject.com/t/overriding-models-choices-in-form-init/15048
probably a few more.
before i build
FIlterablePillRadioSelect
I was wondering if you have a way to do this?I will be doing using this for a nursing form as well.
The text was updated successfully, but these errors were encountered: