Django - Immuting MultiValueField

I need MultiWidgets that renders HTML as the following as a 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>

      

Thanks in advance. Also, I can help someone for a detailed tutorial link as I'm a newbie and the Django Document doesn't specify much.

+3


source to share


1 answer


Here's a project illustrating a MultiValueField example:

https://github.com/justinlilly/django_multiwidget_demo



Here's the relevant bit from that project source:

# 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

      

+5


source







All Articles