Django Profile不使用UserModel保存其他字段

时间:2019-01-23 18:29:51

标签: django python-3.x django-models django-forms django-views

我正在尝试建立一个具有针对学生,讲师和其他人的不同配置文件的学校系统,我可以通过创建自定义userModel来实现,但是,我无法从中保存其他信息(头像,学期等)创建学生个人资料时的表单。 它是保存在studentProfile模型中的唯一user_id。

我正在使用django信号发布此数据,以及使用通用createView呈现到屏幕上。

我尝试了不同的方法来解决此问题,但仍然没有保存其他字段

我的模型。py

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)

这是我的表格。py

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__"

这是我的views.py

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

urls.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"),
]

1 个答案:

答案 0 :(得分:1)

RegisterForm中,保存方法中的一行如下:

profile_form = ProfileForm(self.request.POST, instance=self.request.user.StudentProfile)

也许您正在ProfileForm中寻找到self.cleaned_data的数据:

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,它是表单,而不是视图。

此外,您应该查看FormSets

另一方面,我可以看到您正在尝试这样做。

我的建议是像往常一样注册用户(User模型,仅电子邮件,用户名,密码),然后在成功注册后,重定向到您可以/必须自定义个人资料的页面(页面包含一个ProfileForm来收集配置文件数据并创建相应的StudentProfile),此时,您已经在request.user中拥有相关的用户实例。