如果 UserProfile 存在于另一个 modelForm 中作为默认值,如何从 UserProfile 中获取值
我已经定义了 UerProfile,并且需要为 MyForm 获取电话数据
class UserProfile(models.Model):
...
phone = models.CharField(max_length=20, blank=True)
class CustomModel(models.Model):
...
phone = models.CharField(max_length=20)
class MyForm(forms.ModelForm):
class Meta:
model = CustomModel
exclude = ['some_fields_but_not_phone',]
现在我需要从 UserProfile 中获取电话数据(如果已设置),以便在 {{ form.phone }} 字段中预填充值。然后用户可以在提交表单时更改它或保持原样。
I have UerProfile defined and need to take phone data for MyForm
class UserProfile(models.Model):
...
phone = models.CharField(max_length=20, blank=True)
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种解决方案(尽管可能不是最优雅的)是将字典中的数据绑定到视图中的 MyForm 对象。
更多信息在这里: https://docs.djangoproject.com/en/1.3/ ref/forms/api/
仅在设置了“phone”的情况下填充此字段从这里开始是非常简单的。
One solution, though maybe not the most elegant, is to bind data from a dictionary to your MyForm object in your view.
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.