How do you set the initial value for a ManyToMany field in django?

独自空忆成欢 提交于 2019-12-20 04:56:18

问题


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.


回答1:


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.




回答2:


Although the answer by mlissner might work in some cases, I do not think it is what you want. The keyword "instance" is meant for updating an existing record.

Referring to your attempt to use the keyword "initial", just change the line to:

bar_memberships = userProfile.barmembership.all().values_list('pk', flat=True)

I have not tested this with your code, but I use something similar in my code and it works.



来源:https://stackoverflow.com/questions/2512421/how-do-you-set-the-initial-value-for-a-manytomany-field-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!