views:

77

answers:

1

I need create the following relationship:

One "Rule" can have many users, but one user can be only one rule.

Using ForeignKey and a ModelForm, I get a select box to select just ONE user, but I want to select many users. It's not a ManyToMany relationship because one user never can be more than one rule.

Here are my model definitions:

class User(models.Model):
    name = models.CharField(_(u'Nome do usuário'), max_length=20)
    password = models.CharField(_('Senha'), max_length=20)
    active = models.BooleanField(default=True)

    def __unicode__(self):
        return self.name

class Rule(models.Model):
    ACTIONS = (
        ('liberate', 'Liberar'),
        ('block', 'Bloquear'),
    )

    users = models.ForeignKey(User)
    description = models.CharField(_(u'Descrição'), max_length=30)
    extensions = models.TextField(_(u'Extensões'), blank=True)
    words = models.TextField(_(u'Palavras'), blank=True)
    domains = models.TextField(_(u'Domínios'), blank=True)
    time = models.TimeField(_(u'Horário'))
    action = models.CharField(_(u'Ação'), max_length=8, choices=ACTIONS)

Have some way of to do ir using a ModelForm?

+1  A: 

One "Rule" can have many users, but one user can be only one rule.

To do this you need to move your foreign key into User. That way User A, B, and C could all choose Rule 1 but User A could never select two foreign keys to Rules since there is only one field.

To represent this a form look at inline formsets documentation.

Jason Christa
Quite correct, no matter how much I dislike inline formsets.
Gabriel Hurley