Valor de matriz de Django en un formulario

I have the ability submit tags in a form. When the form is submitted, I see:

tags=['3','4','5']

The tag values are ID's for what the user has chosen. I am able to get the values from the request.POST object and everything is fine. Problem is that the user has to select ATLEAST one tag. And I want to do the validation in a Django form, but I'm not sure what kind of form field value to supply in the django form? Normally I use CharField, DateField, etc. But what exists to get the array value? And then I can supply a clean function for it. Thanks!

preguntado el 29 de julio de 12 a las 00:07

1 Respuestas

Trata django.forms.MultipleChoiceField(). Ver https://docs.djangoproject.com/en/dev/ref/forms/fields/#multiplechoicefield

known_tags = (
    (1, 'Choice 1'), (2, 'Choice 2'), (3, 'Choice 3'),
    (4, 'Choice 4'), (5, 'Choice 5'))

class MyForm(django.forms.Form):
    tags = django.forms.MultipleChoiceField(choices=known_tags, required=True)

EDIT 1:

If what you want to do is to turn a text field into an array...

class MyForm(django.forms.Form):
    tags = django.forms.CharField(required=True)

    def clean_tags(self):
        """Split the tags string on whitespace and return a list"""
        return self.cleaned_data['tags'].strip().split()

Respondido 29 Jul 12, 02:07

No, this would not work. I do not have a set of "Known tags". I have a table in the database, so the tags could be anything on that table. - KVISH

The choices tuple is just an example. You can pull the data from your db and build the list. Or, are you saying you allow users to enter text (rather than select from a list)? - Rob Cowie

Yeah, users are able to enter text... Because these values are from tags. - KVISH

Sorry @kalvish, I don't know what you mean. An example would help - Rob Cowie

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.