You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django自定义User模型:学生注册对象无法持久化至数据库求助

Hey there! Let's figure out why your custom User model isn't saving to the database. I've gone through your code and spotted a few key issues that are likely causing this problem:


1. Syntax Error in Form Meta Fields

Look at your StudentNewRegistrationForm Meta class:

fields = ['title','username', 'first_name', 'last_name','email' 'password1', 'password2']

There's no comma after 'email', so Django reads this as a single invalid field name 'emailpassword1'. This breaks the form's field mapping to your User model, causing validation to fail silently (or uncaught) and preventing the save.

Fix: Add a comma after 'email':

fields = ['title','username', 'first_name', 'last_name','email', 'password1', 'password2']

2. Incorrect Password Handling in the Save Method

Your password logic has two critical issues:

  • user.set_password() doesn't return a value, so assigning it to user.password1 or user.password2 does nothing useful.
  • You don't need to call set_password twice for password1 and password2—you should first validate the two passwords match, then set the password once.

Fix: Add a password validation clean method, and simplify the save logic:

def clean_password2(self):
    password1 = self.cleaned_data.get("password1")
    password2 = self.cleaned_data.get("password2")
    if password1 and password2 and password1 != password2:
        raise forms.ValidationError("Passwords do not match")
    return password2

def save(self, commit=True):
    user = super().save(commit=False)
    # Set password correctly (set_password handles hashing)
    user.set_password(self.cleaned_data["password1"])
    if commit:
        user.save()
    return user

3. Redundant Field Definitions in the ModelForm

You're manually defining fields like title, username, and first_name that the ModelForm would automatically generate from your User model. Then you overwrite the title field again in __init__, which creates unnecessary confusion.

Fix: Remove the redundant top-level field definitions, and define the password fields explicitly (since they aren't part of the User model):

class StudentNewRegistrationForm(forms.ModelForm):
    # Only define fields not present in your User model
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ['title', 'username', 'first_name', 'last_name', 'email']

    # Keep the clean_password2 and save methods from above

4. Ensure Your View Validates the Form

Even with a fixed form, if your view doesn't check form.is_valid() before saving, the data won't persist. Make sure your view logic looks something like this:

def student_new_registration(request):
    if request.method == 'POST':
        form = StudentNewRegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            # Add redirect or success message here
            return redirect('success_page')
    else:
        # Populate form from session data
        candidate = request.session.get('candidate', {})
        initial_data = {
            'title': candidate.get('salutation'),
            'first_name': candidate.get('firstname'),
            'last_name': candidate.get('lastname'),
            'email': candidate.get('email'),
            'username': candidate.get('username'),
        }
        form = StudentNewRegistrationForm(initial=initial_data)
    
    # Check for form errors to debug
    print(form.errors)
    return render(request, 'registration_template.html', {'form': form})

Quick Additional Checks

  • Double-check you've run migrations for your custom User model:
    python manage.py makemigrations
    python manage.py migrate
    
  • In your template, add {{ form.errors }} to see any validation errors you might be missing.

内容的提问来源于stack exchange,提问作者somesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 10:03:23