Django array value in form

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

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

Tag values ​​are an identifier for what the user has selected. I can get the values ​​from the request.POST object, and everything is fine. The problem is that the user needs to select one of the ATLEAST tags. And I want to do validation in a Django form, but I'm not sure what value of the form field I need to provide in the django form? I usually use CharField , DateField , etc. But what exists to get the value of an array? And then I can give it a clean function. Thanks!

+6
source share
1 answer

Try django.forms.MultipleChoiceField() . See 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 you want to do this, turn the 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() 
+4
source

Source: https://habr.com/ru/post/921582/


All Articles