views:

27

answers:

1

I am using a ModelForm to create a form, and I have gotten the initial values set for every field in the form except for the one that is a ManyToMany field.

I understand that I need to give it a list, but I can't get it to work. My code in my view right now is:

        userProfile = request.user.get_profile()
        employer = userProfile.employer
        bar_memberships = userProfile.barmembership.all()
        profileForm = ProfileForm(
            initial = {'employer': employer, 'barmembership' : bar_memberships})

But that doesn't work. Am I missing something here?

Per request in the comments, here's the relevant parts of my model:

# a class where bar memberships are held and handled.
class BarMembership(models.Model):
    barMembershipUUID = models.AutoField("a unique ID for each bar membership",
        primary_key=True)
    barMembership = USStateField("the two letter state abbreviation of a bar membership")

    def __unicode__(self):
        return self.get_barMembership_display()

    class Meta:
        verbose_name = "bar membership"
        db_table = "BarMembership"
        ordering = ["barMembership"]

And the user profile that's being extended:

# a class to extend the User class with the fields we need.
class UserProfile(models.Model):
    userProfileUUID = models.AutoField("a unique ID for each user profile",
        primary_key=True)
    user = models.ForeignKey(User,
        verbose_name="the user this model extends",
        unique=True)
    employer = models.CharField("the user's employer",
        max_length=100,
        blank=True)
    barmembership = models.ManyToManyField(BarMembership,
        verbose_name="the bar memberships held by the user",
        blank=True,
        null=True)

Hope this helps.

A: 

OK, I finally figured this out. Good lord, sometimes the solutions are way too easy.

I need to be doing:

profileForm = ProfileForm(instance = userProfile)

I made that change, and now everything works.

mlissner