开发者

How to take value from UserProfile if it exist in another modelForm as default value

I have UerProfile defined and need to take phone data for MyForm

 class UserProfile(models.Model):
     ...
     phone = models.CharField(max_length=20, blank=True)


 开发者_StackOverflow中文版class CustomModel(models.Model):
     ...
     phone = models.CharField(max_length=20)


 class MyForm(forms.ModelForm):

     class Meta:
         model = CustomModel
         exclude = ['some_fields_but_not_phone',]

Now I need to take phone data from UserProfile if it is set, to be prepopulated value in {{ form.phone }} field. Then user can change it or leave it as is when he submit form.


One solution, though maybe not the most elegant, is to bind data from a dictionary to your MyForm object in your view.

data = {
    'field1': 'data'
    'field2': 'data'
    'phone': request.user.get_profile().phone
}
form = MyForm(data)

More info here: https://docs.djangoproject.com/en/1.3/ref/forms/api/

Only populating this field if 'phone' is set is pretty trivial from here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜