Djangoでのユーザモデルを拡張した後、どのようにのModelFormを作成するのですか?

StackOverflow https://stackoverflow.com/questions/2511759

  •  22-09-2019
  •  | 
  •  

質問

Iは、位置、および雇用者のようないくつかの他の変数を含むようにジャンゴにUserモデルを拡張しました。今、私は、次のフィールドを持つフォームを作成しようとしています:

First name (from User)
Last name (from User)
Location (from UserProfile, which extends User via a foreign key)
Employer (also from UserProfile)

私はのModelFormを作成しています:

from django.forms import ModelForm
from django.contrib import auth
from alert.userHandling.models import UserProfile

class ProfileForm(ModelForm):
    class Meta:
#       model = auth.models.User # this gives me the User fields
        model = UserProfile # this gives me the UserProfile fields

だから、私の質問は、私は彼らがUserモデルやのUserProfileモデルからであるかどうか、すべてのフィールドへのアクセス権を持っているのModelFormを作成することができますか?

希望これは理にかなっています。何か質問がある場合、私は明確にさせていただきます。

役に立ちましたか?

解決

あなたはどちらかの2つのモデルのフォーム(ユーザー用とのUserProfileのための1)を作成したり、すべてのフィールドを持つカスタムフォームを作成し、あなたのビューでそれらを派遣することができます。

from django import forms

class ContactForm(forms.Form):
    first_name = forms.CharField()
    last_name = forms.CharField()
    location = forms.CharField()
    employer = forms.CharField()

他のヒント

あなたがすることはできません。 ModelFormは、そのすべてのフィールドを単一のモデルから来ることを期待しています。 Formの子を作成し、モデルからフィールド定義を引き出します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top