2016-12-01 7 views
0

私はモデル '予定'を持っています。そのクラスの患者は組み込みのUserモデルに関連付けられています。私はそのクラスのモデルフォームを作成しました。同じフォームの中から別のクラス(フィールド患者のユーザ)のオブジェクトをインスタンス化することは可能ですか?フォーム内のユーザーモデルのフィールドにアクセスできません。これはどうすればできますか?私は以下のように、このモデルのためのModelFormを作成している子クラスのModelFormから親クラスオブジェクトを作成

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) 

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(), 
     } 

答えて

1

私はHospitalCreateAppointmentFormでユーザーオブジェクトをインスタンス化の背後にあることを確認目的ではないと思います。しかし、本当に必要な場合に備えて、ユーザーモデルをフォームファイルにインポートする必要があります。たとえば、あなたのHospitalCreateAppointmentFor

from django.contrib.auth.models import User 

などのインポートユーザーモジュール、forms.pyにある場合そして、あなたは次のようにフィールドにアクセスすることができます。

User._meta.fields 
+0

予定が予約されるたびに、私はことをしたいということがあり、それをインスタンス化の背後にある理由患者がサイト上のユーザになり、彼の予約状況を確認することができます。 – blueChair

関連する問題