two modelForm fields to a one model Field

19 views
Skip to first unread message

Leandro Severino

unread,
Sep 1, 2015, 4:26:42 PM9/1/15
to Django users
Hi,

  In my first post, I have a simple question:

  Its possible a modelForm have two fields for a one model Field ? 

  My codes:


 In my models:

   class MyClass(models.Model):
           COMMON_AMENITIES_CHOICES = (('A', 'Aditional'),
                                                        ('C', 'Commom'))

           type = models.CharField(u'type', max_length=1, choices=COMMON_AMENITIES_CHOICES )

           name = moldes.CharField(max_length=250)



With a default form I have this:

class MyClassForm(forms.Form):
    from .models import MyClass

    COMMON_AMENITIES_CHOICES = tuple(Amenitie.objects.filter(
        type_amenitie='C').values_list('id', 'name'))
    ADITIONAL_AMENITIES_CHOICES = tuple(Amenitie.objects.filter(
        type_amenitie='A').values_list('id', 'name'))

    common_amenitie = forms.MultipleChoiceField(
        choices=COMMON_AMENITIES_CHOICES,
        label=u'Common Amenities'
    )
    aditional_amenitie = forms.MultipleChoiceField(
        choices=ADITIONAL_AMENITIES_CHOICES,
        label=u'Common Amenities'
    )


  My question:

  Its possible implements this with a modelForm? 

  -- Leandro.

James Schneider

unread,
Sep 1, 2015, 8:08:33 PM9/1/15
to django...@googlegroups.com
Yes, although your model does not appear to be setup in an ideal
manner, which is probably why your form is not coming out the way you
intended. You have no way to store what values the user would pick
even if the form was correct.

You probably need to set up something like this:


class MyClass(models.Model):
COMMON_AMENITIES_CHOICES = (('A', 'Aditional'), ('C', 'Commom'))

type = models.CharField(u'type', max_length=1,
choices=COMMON_AMENITIES_CHOICES )

name = moldes.CharField(max_length=250)

common_amenities = models.ManyToManyField(Amenitie,
limit_choices_to={'type_amenitie': 'C'},
related_name='myclass_common_set')
additional_amenities = models.ManyToManyField(Amenitie,
limit_choices_to={'type_amenitie': 'A'},
related_name='myclass_additional_set')


See here for the reference for the ManyToManyField options:
https://docs.djangoproject.com/en/1.8/ref/models/fields/#manytomanyfield

At this point, you may not even need to define a model form (if you
are using Class Based Views). The one generated should be close to the
regular form you outlined above, although you might if you need
additional validation (ie disallow picking additional amenities
without picking common amenities, etc.) or if you need to override the
widgets used in the form rendering.

-James

Leandro Severino

unread,
Sep 2, 2015, 8:13:10 AM9/2/15
to Django users
 Thanks James.
 
Reply all
Reply to author
Forward
0 new messages