我正在使用ModelForm來創建表單,並且我已經獲取了爲表單中的每個字段(除了ManyToMany字段之外的其他字段)設置的初始值。如何爲django中的ManyToMany字段設置初始值?
據我所知,我需要給它一個清單,但我不能得到它的工作。我現在在我看來的代碼是:
userProfile = request.user.get_profile()
employer = userProfile.employer
bar_memberships = userProfile.barmembership.all()
profileForm = ProfileForm(
initial = {'employer': employer, 'barmembership' : bar_memberships})
但這並不奏效。我在這裏錯過了什麼嗎?
每請求的意見,這是我的模型的相關部分:
# 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"]
,這就是正在擴展的用戶配置文件:
# 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)
希望這有助於。
告訴我們你的模型。 – 2010-03-25 02:19:43