我试图一次提交2个表单,以便在Django中创建我的学生用户。我一直在苦苦挣扎一段时间,但我想我终于要结束如何一次管理2个表单供我的用户注册。但是当我从我的视图中填写数据时,我收到错误:
[Errno 22] Invalid argument: "C:\\Users\\danny\\Desktop\\Projects\\bachelor_thesis\\eve\\templates\\{'form1': <UserForm bound=False, valid=Unknown, fields=(username;email;first_name;last_name;password)>, 'form2': <StudentForm bound=False, valid=Unknown, fields=(phone;student_ID;photo)>}"
以下是我的文件:
@csrf_protect
def student_register(request):
if request.method == 'POST':
form1 = UserForm(request.POST, prefix="user")
form2 = StudentForm(request.POST, prefix="profile")
if form1.is_valid() and form2.is_valid():
# create initial entry for user
username = form1.cleaned_data["username"]
password = form1.cleaned_data["password"]
new_user = User.objects.create_user(username, password)
new_user.save()
# create entry for UserProfile (extension of new_user object)
profile = form2.save(commit=False)
profile.user = new_user
profile.save()
return HttpResponseRedirect("index")
else:
form1 = UserForm(prefix="user")
form2 = StudentForm(prefix="profile")
c = {
'form1': form1,
'form2': form2,
}
c.update(request)
return render(request, "student_signup_form.html", c)
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('username', 'email', 'first_name', 'last_name', 'password')
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ('phone', 'student_ID', 'photo')
class User(AbstractUser):
pass
class Student(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
student_ID = models.CharField(unique=True, max_length=14,
validators=[RegexValidator(regex='^.{14}$',
message='The ID needs to be 14 characters long.')])
photo = models.ImageField(upload_to='students_images')
phone = models.CharField(max_length=15, )
def __str__(self):
return self.user.username
@receiver(post_save, sender=User)
def create_user_student(sender, instance, created, **kwargs):
if created:
Student.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_student(sender, instance, **kwargs):
instance.profile.save()
另外,当我打开注册表时,密码是可见的。另外,如何添加确认密码字段?谢谢。 这是追溯:https://pastebin.com/b90muPZY 这个问题困扰了我一段时间。