After extending the User model in django, how do you create a ModelForm?

爷,独闯天下 提交于 2019-12-10 16:00:00

问题


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

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.


回答1:


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



回答2:


You can't. ModelForm expects all its fields to come from a single model. Create a child of Form and pull the field definitions from the models.



来源:https://stackoverflow.com/questions/2511759/after-extending-the-user-model-in-django-how-do-you-create-a-modelform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!