在Django中扩展了User模型之后,如何创建ModelForm? [英] After extending the User model in django, how do you create a ModelForm?

查看:95
本文介绍了在Django中扩展了User模型之后,如何创建ModelForm?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I extended the User model in django to include several other variables, such as location, and employer. Now I'm trying to create a form that has the following fields:

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

我创建了一个模型表单:

I have created a 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

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

So, my question is, how can I create a ModelForm that has access to all of the fields, whether they are from the User model or the UserProfile model?

希望这是有道理的.我很乐意澄清是否有任何问题.

Hope this makes sense. I'll be happy to clarify if there are any questions.

推荐答案

您可以创建两个模型表单(一个用于User,一个用于UserProfile),或者创建一个包含所有字段的自定义表单,并在您的视图中进行分派. /p>

You can either create two model forms (one for User and one for UserProfile) or create a custom form with all your fields and dispatch them in your view.

from django import forms

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

这篇关于在Django中扩展了User模型之后,如何创建ModelForm?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆