我想創建一個單表格,它使管理員能夠創建具有擴展配置文件的新用戶。請注意,我不想使用管理員和註冊應用程序。 我用UserProfile模型擴展了用戶。我已閱讀所有與擴展用戶配置文件相關的文檔。但是,我真的不知道如何保存這些信息。 我編寫了這個問題下面的Django形式:在Django中創建添加用戶表
class CreateUserForm(forms.Form):
username = forms.CharField(max_length=30)
first_name = forms.CharField()
last_name = forms.CharField()
password1=forms.CharField(max_length=30,widget=forms.PasswordInput()) #render_value=False
password2=forms.CharField(max_length=30,widget=forms.PasswordInput())
email=forms.EmailField(required=False)
title = forms.ChoiceField(choices=TITLE_CHOICES)
def clean_username(self): # check if username dos not exist before
try:
User.objects.get(username=self.cleaned_data['username']) #get user from user model
except User.DoesNotExist :
return self.cleaned_data['username']
raise forms.ValidationError("this user exist already")
def clean(self): # check if password 1 and password2 match each other
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:#check if both pass first validation
if self.cleaned_data['password1'] != self.cleaned_data['password2']: # check if they match each other
raise forms.ValidationError("passwords dont match each other")
return self.cleaned_data
def save(self): # create new user
new_user=User.objects.create_user(username=self.cleaned_data['username'],
first_name=self.cleaned_data['first_name'],
last_name=self.cleaned_data['last_name'],
password=self.cleaned_data['password1'],
email=self.cleaned_data['email'],
)
return new_user
,可以嗎?但是它在first_name和last_name中給了我一個錯誤。 django在save()方法中並不指望first_name和last_name。
我不確定您是否可以通過普通窗體訪問'save'方法。它在模型中可用,當然,https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method – super9