0
因此,在我的模型中,我有一個特定的配置文件,與具有與django用戶模型的一對一關係的更一般的配置文件具有一對一的關係。我希望能夠在django管理員中填寫一個表單,並創建所有三個模型的實例,並建立關係。自定義管理員創建表單
我還沒有搞亂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)