表单中的Django数组值

时间:2021-02-07 19:32:57

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!

标签值是用户选择的ID。我能够从request.POST对象中获取值,一切都很好。问题是用户必须选择ATLEAST一个标签。我想以Django形式进行验证,但我不确定django形式提供什么样的表单字段值?通常我使用CharField,DateField等。但是存在什么来获取数组值?然后我可以为它提供一个干净的功能。谢谢!

1 个解决方案

#1


4  

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

试试django.forms.MultipleChoiceField()。请参阅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()

#1


4  

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

试试django.forms.MultipleChoiceField()。请参阅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()