自定义管理员创建表单

时间:2014-10-31 04:34:32

标签: django django-admin

所以在我的模型中,我有一个特定的配置文件,它与一个更一般的配置文件有一对一的关系,与django用户模型有一对一的关系。我希望能够在django admin中填写一个表单并创建所有三个模型的实例,并且已经建立了关系。

我没有过多地讨论django管理员,所以我不完全确定如何让它工作。这是我失败的尝试:

class CreateSpecializedProfileAdminForm(forms.ModelForm):

    class Meta:
        exclude = ['profile']

    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    email = forms.EmailField(max_length=30)
    password = forms.CharField(max_length=30)
    confirm_password = forms.CharField(max_length=30)

    def clean(self):
        password = self.cleaned_data['password']
        confirm_password = self.cleaned_data['confirm_password']
        if len(self.cleaned_data['password']) < 6:
            raise forms.ValidationError('Password must be at least 6 characters.')
        if password != confirm_password:
            raise forms.ValidationError('Passwords must match.')
        return super(CreateSpecializedProfileAdminForm, self).clean()

    def save(self, commit=True):
        from django.contrib.auth.models import User
        first = self.cleaned_data['first_name']
        last = self.cleaned_data['last_name']
        email = self.cleaned_data['email']
        password = self.cleaned_data['password']
        user = User.objects.create_user(email, email, password)
        user.first_name = first
        user.last_name = last
        user.save()
        profile = UserProfile()
        profile.user_auth = user
        profile.save()
        specialized_profile = SpecializedProfile()
        specialized_profile.profile = profile
        specialized_profile.save()
        return specialized_profile

class SpecializedProfileAdmin(admin.ModelAdmin):

form = CreateSpecializedProfileAdminForm

admin.site.register(SpecializedProfile, SpecializedProfileAdmin)

1 个答案:

答案 0 :(得分:0)

https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form

删除class Meta并将exclude = ['profile']移至ModelAdmin

class SpecializedProfileAdmin(admin.ModelAdmin):
    exclude = ['profile']
    form = CreateSpecializedProfileAdminForm