Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django list of ids as a form field

My apologizes if this question was somewhere before, but I could not find anything.

So, the question is really simple: is these any django native formfield that mimics the behavior of request.POST.getlist('something')?

In my UI, user creates a list of objects that he wants to save, and these objects are represented as a list of hidden inputs with the same name:

<input type="hidden" name="cc" value="1045">
<input type="hidden" name="cc" value="1055">
<input type="hidden" name="cc" value="1046">

request.POST.getlist does exactly what I need, but I don't want to work with the request directly, I want do to it through the form.

like image 981
dragoon Avatar asked Nov 25 '25 06:11

dragoon


1 Answers

Thanks for the comment. Yes I found that ModelChoiceField is used to ManyToMany fields in models. On the form side, it is represented as MultipleChoiceField/TypedMultipleChoiceField.

So I decided to subclass this field and override validate methods.

class NotValidatedMultipleChoiceFiled(forms.TypedMultipleChoiceField):
    """Field that do not validate if the field values are in self.choices"""

    def to_python(self, value):
        """Override checking method"""
        return map(self.coerce, value)

    def validate(self, value):
        """Nothing to do here"""
        pass
like image 83
dragoon Avatar answered Nov 27 '25 22:11

dragoon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!