4

我在 django 中扩展了 User 模型以包含其他几个变量,例如位置和雇主。现在我正在尝试创建一个包含以下字段的表单:

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

我创建了一个模型:

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

所以,我的问题是,如何创建一个可以访问所有字段的 ModelForm,无论它们来自 User 模型还是 UserProfile 模型?

希望这是有道理的。如果有任何问题,我会很乐意澄清。

4

2 回答 2

3

您可以创建两个模型表单(一个用于用户,一个用于 UserProfile)或创建一个包含所有字段的自定义表单并将它们发送到您的视图中。

from django import forms

class ContactForm(forms.Form):
    first_name = forms.CharField()
    last_name = forms.CharField()
    location = forms.CharField()
    employer = forms.CharField()
于 2010-03-24T22:10:36.880 回答
0

你不能。ModelForm期望它的所有字段都来自一个模型。创建一个子Form模型并从模型中提取字段定义。

于 2010-03-24T22:10:59.580 回答