我想制作一个包含有关不同类型帐户信息的应用程序。
问题 我可以填写表格,但它不会接受输入并将其存储在要存储到的模型中。 用户表单,即此处的“帐户”模型填充了信息,但“学生”模型未从表单中获取任何输入。另外,我认为表单的cleaned_data的语法存在问题。
Models.py
from django.db import models
from django.core.validators import RegexValidator
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser)
username_regex = '^[a-zA-Z0-9+-]*$'
# Create your models here.
class AccountManager(BaseUserManager):
def create_account(self, username, email, password=None):
if not email:
raise ValueError('Users must have a email id')
account = self.model(
username = username,
email=self.normalize_email(email),
)
account.set_password(password)
account.save(using=self._db)
return account
def create_student(self,username, email, password=None):
account = self.create_account(
username = username,
email=email,
password=password,)
account.is_student = True
account.save(using=self._db)
return account
def create_teacher(self, username, email, password=None):
account = self.create_account(
username = username,
email=email,
password=password,)
account.is_teacher = True
account.save(using=self._db)
return account
def create_superuser(self, username, email, password=None):
account = self.create_student(
username = username,
email=email,
password=password,)
account.is_student = True
account.is_teacher = True
account.is_admin = True
account.is_staff = True
account.save(using=self._db)
return account
class Account(AbstractBaseUser):
username = models.CharField(max_length=60,
validators =[RegexValidator(regex = username_regex, message = 'Username must be alphanumeric',
code = 'Invalid_username')],
unique=True)
email = models.EmailField(verbose_name='Email Address',
max_length=255,
unique=True,
)
is_teacher = models.BooleanField(default=False)
is_student = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default = False)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
def __str__(self):
return self.username
def get_short_name(self):
return self.username
def has_perm(self,perm, obj=None):
return True
def has_module_perms(self,app_label):
return True
objects = AccountManager()
class Student(models.Model):
student = models.OneToOneField(Account, on_delete=models.CASCADE, primary_key=True)
first_name = models.CharField(max_length = 56)
second_name = models.CharField(max_length = 56)
address = models.CharField(max_length = 256)
#dob = models.DateField()
grade = models.CharField(max_length = 3)
def __str__(self):
return self.first_name + self.second_name
def name(self):
return self.first_name + self.second_name
class Teacher(models.Model):
teacher = models.OneToOneField(Account, on_delete=models.CASCADE, primary_key=True)
first_name = models.CharField(max_length = 56)
second_name = models.CharField(max_length = 56)
address = models.CharField(max_length = 256)
#dob = models.DateField()
qualification = models.CharField(max_length = 256)
def __str__(self):
return self.first_name + self.second_name
Forms.py
from django.contrib.auth import get_user_model
from django.db.models import Q
from django import forms
from django.db import transaction
from .models import Student,Teacher
#from django.contrib.auth import UserCreationForm
Account = get_user_model()
#User Creation form
class UserCreationForm(forms.ModelForm):
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput)
class Meta:
model = Account
fields = ('username','email')
def clean_password(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password2 and password1!=password2:
raise forms.ValidationError("Passwords donot match")
return password2
def save(self, commit=True):
user = super(UserCreationForm,self).save(commit=False)
user.email = self.cleaned_data['email']
user.set_password(self.cleaned_data['password1'])
if commit:
user.save()
return user
#for signup as student and register corrected
class StudentRegForm(UserCreationForm):
f_name = forms.CharField(max_length = 30)
s_name = forms.CharField(max_length = 30)
addr = forms.CharField(max_length = 30)
grade = forms.CharField(max_length = 30)
class meta(UserCreationForm.Meta):
model = Account
def save(self):
user = super().save(commit = False)
user.is_student = True
user.save()
student = Student.objects.create(student = user)
#filling Student Model
student.first_name = self.cleaned_data.get('f_name')
student.second_name = self.cleaned_data.get('s_name')
student.address = self.cleaned_data.get('addr')
student.grade = self.cleaned_data.get('grade')
return user
Views.py
#new view for registration
def std_signup_view(request, *args, **kwargs):
form = StudentRegForm()
if request.method == 'POST':
form = StudentRegForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/login')
context = {'form':form}
return render(request, "StudentLoginApp/register.html", context)
Registration.html
{% extends 'base.html' %}
{% block content %}
<h1>Register Student</h1>
{% include 'StudentLoginApp/form.html' with form=form %}
{% endblock %}
form.html
<form method="POST" action='.'>
{%csrf_token%}
{{form.as_p}}
<input type="submit" name="Register">
</form>
student_login.html
{% block content %}
<h1>Welcome Student</h1>
<h2><p>Hello {{account_obj.student.first_name}}</p></h2> Your Email Address is {{account_obj.email}}
<br>
<b>Address: </b>{{account_obj.student.address}}
<br>
{{account_obj.student}}
{% endblock %}
对不起,如果我提供了太多信息。我不知道如何在堆栈溢出中发布问题,对于编程和编程我都是陌生的。还要忽略缩进(如果在任何地方都出错)。