Django配置文件未使用UserModel保存其他字段
我正在尝试创建一个学校系统,该系统为学生、讲师和其他人提供不同的配置文件,我可以通过创建自定义用户模型来实现这一点,但是,在创建时,我无法将表单中的其他信息(化身、学期等)保存到学生配置文件中。 它是唯一保存在studentProfile模型中的用户id 我使用django信号发布这些数据,并使用通用createView渲染到屏幕上 我尝试了不同的方法来解决这个问题,但仍然没有保存其他领域 我的模特Django配置文件未使用UserModel保存其他字段,django,python-3.x,django-models,django-forms,django-views,Django,Python 3.x,Django Models,Django Forms,Django Views,我正在尝试创建一个学校系统,该系统为学生、讲师和其他人提供不同的配置文件,我可以通过创建自定义用户模型来实现这一点,但是,在创建时,我无法将表单中的其他信息(化身、学期等)保存到学生配置文件中。 它是唯一保存在studentProfile模型中的用户id 我使用django信号发布这些数据,并使用通用createView渲染到屏幕上 我尝试了不同的方法来解决这个问题,但仍然没有保存其他领域 我的模特 class StudentProfile(models.Model): user = m
class StudentProfile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
semester = models.ForeignKey(SemesterData, on_delete=models.SET_NULL, null=True)
dept_name = models.ForeignKey(DepartmentData, on_delete=models.SET_NULL, null=True)
avatar = models.ImageField(upload_to='avatars/', null=True, blank=True)
def __str__(self):
return self.user.first_name
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
if instance.admin:
pass
else:
data = StudentProfile.semester
HttpResponse(data)
StudentProfile.objects.create(user=instance)
这是我的表格
class UserAdminCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
user_type = forms.ChoiceField(choices=User.USER_TYPE_CHOICES,widget=forms.Select)
# user_type = forms.Select(attrs={'class': 'form-control'})
class Meta:
model = User
fields = ('user_id', 'first_name','last_name','user_type',)
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserAdminCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserAdminChangeForm(forms.ModelForm):
"""A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
"""
password = ReadOnlyPasswordHashField()
class Meta:
model = User
fields = ('user_id','first_name','last_name', 'password', 'active', 'admin')
def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]
class LoginForm(forms.Form):
user_id = forms.CharField(label="User Id", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Enter Matric Num or Student Id'}))
password = forms.CharField(widget=forms.PasswordInput)
class RegisterForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': 'form-control'}))
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput(attrs={'class': 'form-control'}))
# user_type = forms.ChoiceField(choices=User.USER_TYPE_CHOICES, widget=forms.Select(attrs={'class': 'form-control'}), label="Select One", initial=User.USER_TYPE_CHOICES[1])
class Meta:
model = User
fields = ('user_id', 'first_name', 'last_name',)
widgets = {
'user_id': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Matric Num or Student Id '}),
'first_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter First Name'}),
'last_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Last Name'}),
# 'first_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Department Name'}),
}
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super().save(commit=False)
# user = super(UserAdminCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
user.user_type = 1
if commit:
user.save()
profile_form = ProfileForm(self.request.POST, instance=self.request.user.profile)
profile_form.save()
return user
class ProfileForm(forms.ModelForm):
dept_name = forms.ModelChoiceField(queryset=DepartmentData.objects.all(), empty_label="Select One",
widget=forms.Select(attrs={'class': 'form-control'}), label="Select One")
semester = forms.ModelChoiceField(queryset=SemesterData.objects.all(), empty_label="Select One",
widget=forms.Select(attrs={'class': 'form-control'}), label="Select One")
avatar = forms.ImageField()
class Meta:
model = StudentProfile
fields = "__all__"
这是我的观点
class RegisterView(CreateView):
form_class = RegisterForm
template_name = 'accounts/student/signup.html'
success_url = '/login'
def get_context_data(self, **kwargs):
# app = settings.CONFIG
table = FacultyTable(FacultyData.objects.all())
RequestConfig(self.request, paginate={'per_page': 10}).configure(table)
context = super(RegisterView, self).get_context_data(**kwargs)
context['app'] = settings.CONFIG
context['faculty'] = table
context['profile'] = ProfileForm
return context
url.py
app_name = 'account'
urlpatterns = [
path('register', RegisterView.as_view(), name ="signup"),
path('register/student', RegisterView.as_view(), name="signup_student"),
# path('signup', views.signup_view, name ="signup"),
path('', LoginView.as_view(), name="login"),
path('login', views.login_view, name ="login"),
path('logout', views.logout_view, name ="logout"),
]
您的
注册表中有一行类似于save方法中的以下内容:
profile_form = ProfileForm(self.request.POST, instance=self.request.user.StudentProfile)
也许您要在self.cleaned\u data
中查找ProfileForm
中的数据:
def save(self, commit=True):
# Save the provided password in hashed format
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
user.user_type = 1
if commit:
user.save()
# Extract your profile data from self.cleaned_data
profile_data = self.cleaned_data
profile_form = ProfileForm(profile_data)
profile_form.save()
return user
在该行中,self
指的是表单本身,因此没有属性request
,它是表单,而不是视图
另外,你应该考虑一下
另一方面,我可以看出你在这里试图这么做
我的建议是像往常一样注册一个用户(user
model,只需电子邮件、用户名、密码),然后在成功注册后,重定向到一个页面,您可以/必须自定义您的个人资料(一个包含ProfileForm
的页面,以收集个人资料数据并创建相应的StudentProfile
)此时,您已经在请求中拥有了相关的用户实例。user
您是对的,但是我试图通过立即执行所有操作来为管理员节省时间。有没有一种方法可以在注册用户后从另一个函数中获取这些字段?因此,它可能不是重定向,而是调用下一个函数。我知道,我只是更新了答案,以便向您展示一个可能的解决方案