Django - MultiValueField实现

时间:2012-03-23 08:13:14

标签: python django django-forms

我需要一个MultiWidgets,它将HTML呈现为MultiValueField:

<div class="formfield_trailer">
  <div class="formfield_title">My Family</div>
  <select label="My Family" name="family_biodata[]" id="id_my_family_0">
    <option value="0">Select One</option>
    <option value="F">Father</option>
    <option value="M">Mother</option>
  </select>
  <input type="text" size="5" class="family" label="My Parents" id="id_my_family" name="family_biodata[]">
  <input type="checkbox" label="My Family" name="family_biodata[]" id="id_my_family_2">
  <p><a>Add More<br><br></a></p>    
</div>

提前致谢。另外,我可以帮助我找到关于此的详细教程链接,因为我是新手,Django文档没有详细说明。

1 个答案:

答案 0 :(得分:5)

这是一个说明MultiValueField示例的项目:

https://github.com/justinlilly/django_multiwidget_demo

以下是该项目来源的相关位:

# fields
from django.forms import fields
from djnycapp.widgets import AutoCompleteWidget
from django.contrib.auth.models import User

class UserAutoCompleteField(fields.MultiValueField):
    widget = AutoCompleteWidget

    def __init__(self, *args, **kwargs):
        """
        Have to pass a list of field types to the constructor, else we
        won't get any data to our compress method.
        """
        all_fields = (
            fields.CharField(),
            fields.CharField(),
            )
        super(UserAutoCompleteField, self).__init__(all_fields, *args, **kwargs)

    def compress(self, data_list):
        """
        Takes the values from the MultiWidget and passes them as a
        list to this function. This function needs to compress the
        list into a single object to save.
        """
        if data_list:
            return User.objects.get(id=data_list[0])
        return None