Django 1.6将自定义字段添加到User模型

时间:2014-04-24 10:38:20

标签: python django

我有以下

简档/ models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    university = models.CharField(max_length=200, choices=UNIVERSITY, null=True)

简档/ views.py

class UserForm(ModelForm):
    class Meta:
        model = UserProfile
        fields = ('username', 'first_name', 'last_name', 'email', 'university')

我向南跑,数据库是最新的,但我仍然收到此错误

django.core.exceptions.FieldError: Unknown field(s) (first_name, username, email, last_name) specified for UserProfile

我猜这与表的链接方式有关。在我的UserProfile表中,我有 id,user_id和university 列,其中包含适当的数据。

3 个答案:

答案 0 :(得分:0)

ModelForm只能为单个模型生成表单字段,在本例中为UserProfile。元类中的fields属性指定要显示的表单字段。在这种情况下,字段first_nameusernameemaillast_name未定义。您必须在表单上手动定义它们,并更改保存方法以保存User对象:

class UserForm(forms.ModelForm):
    username = forms.CharField(max_length=100)
    email = forms.EmailField()
    ...

    class Meta:
        model = UserProfile
        fields = ('username', 'first_name', 'last_name', 'email', 'university')

    def save(self, commit=True):
        # save user and profile

答案 1 :(得分:0)

ModelForm只能生成单个模型的字段(Meta类中指定的字段)

Django有一个带有相关模型字段的表单的方法是内联formset:
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets

例如

# forms.py
UserProfileFormSet = inlineformset_factory(User, UserProfile, max_num=1)

# views.py
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404, render_to_response
from .forms import UserProfileFormSet

def myview(request, user_id):
    user = get_object_or_404(User, pk=user_id)
    formset = UserProfileFormSet(request.POST or None, instance=user)
    if formset.is_valid():
        formset.save()
        # ...redirect here
    return render_to_response("my_template.html", {
        "formset": formset,
    })

答案 2 :(得分:0)

我最后通过substituting a custom User model解决了这个问题。这允许我在一个名为profiles_users的表中设置所有用户字段并具有额外的字段。

有一些自定义设置,但我发现这种方法比扩展用户基类更具流动性。

相关问题