[英]Create Parent Class object from child class's ModelForm
I have a Model 'Appointment'. 我有一个“约会”模特。 In that class patient is associated with built-in User model.I have made a modelform for that class.
在该类别中,患者与内置的用户模型相关联。我为该类别创建了一个模型形式。 Is it possible to instantiate an object of another class (User in field patient) from inside the same form.
是否可以从同一表单内部实例化另一类的对象(现场患者中的用户)。 I am not able to access User Model's field in the form.
我无法访问表单中的“用户模型”字段。 How can this be done ?
如何才能做到这一点 ?
class Appointment(models.Model):
doctor = models.ForeignKey(Doctor)
clinic = models.ForeignKey(Clinic, null=True, blank=True)
hospital = models.ForeignKey(Hospital, null=True, blank=True)
day = models.DateField()
time = models.TimeField()
patient = models.ForeignKey(User)
I have created a ModelForm for this model as below: 我为此模型创建了一个ModelForm,如下所示:
class HospitalCreateAppointmentForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(HospitalCreateAppointmentForm, self).__init__(*args, **kwargs)
for field in iter(self.fields):
self.fields[field].widget.attrs.update({
'class': 'form-control'
})
class Meta:
model = Appointment
fields = ['doctor','hospital','day','time','patient']
widgets = {
'day': forms.SelectDateWidget(),
}
I am not sure purpose behind instantiating user object in HospitalCreateAppointmentForm
. 我不确定在
HospitalCreateAppointmentForm
实例化用户对象的目的。 However, just in case you really need, you have to import User model in form file. 但是,如果万一您确实需要,则必须将用户模型导入表单文件。 For example if your
HospitalCreateAppointmentFor
is in forms.py
, import User module like 例如,如果
HospitalCreateAppointmentFor
位于forms.py
,则导入User模块,例如
from django.contrib.auth.models import User
And you can access field like: 您可以访问如下字段:
User._meta.fields
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.