Я новичок в django, у меня есть пользовательская модель с дополнительным статусом и названиями моделей. Пока я сделал часть базы данных, как я могу создать регистрационную форму для модели пользователя cutom с полями Foreignkey.
Код класса моей модели:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.contrib.auth.models import AbstractUser
class Title(models.Model):
value = models.CharField(max_length=100, null=True, blank=True)
class Meta:
db_table = 'title'
class Status(models.Model):
value = models.CharField(max_length=100, null=True, blank=True)
class Meta:
db_table = 'status'
class User(AbstractUser):
filenumber = models.CharField(max_length=9, null=True, blank=True)
personalemail = forms.EmailField(required=True)
intakeyear = models.IntegerField(null=True, blank=True)
title = models.ForeignKey(Title, on_delete=models.CASCADE, null=True, blank=True)
status = models.ForeignKey(Status, on_delete=models.CASCADE, null=True, blank=True)
Мои настройки.py:
AUTH_USER_MODEL = 'student.User'# changes built-in user model to ours
Как создать поля формы регистрации пользователя, например
Имя, Фамилия, Должность, Статус, Электронная почта, Персональная почта, Пароль, Подтверждение пароля. Я добавил дополнительные поля в заголовок и статус модели пользователя (поля Foreignkey) и номер файла, intakeyear, personalemail
Мой файл form.py:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.forms import ModelForm
from student.models import User
from student.models import Title, Statu
class StudentNewRegistrationForm(forms.ModelForm):
title = forms.CharField(required=True)
intakeyear = forms.IntegerField(required=True)
email = forms.EmailField(required=True)
personalemail = forms.EmailField(required=True)
status = forms.CharField(required=True)
def __init__(self, *args, **kwargs):
super(StudentNewRegistrationForm, self).__init__(*args, **kwargs)
title = [('', 'Choose a title')]
title.extend(Title.objects.values_list('id', 'value'))
self.fields['title'] = forms.ChoiceField(choices=title)
status = [('', 'Choose a status')]
status.extend(Status.objects.values_list('id', 'value'))
self.fields['status'] = forms.ChoiceField(choices=status)
class Meta:
model = User
fields = ['username','first_name','last_name','email','password1',
'password2''title','status','intakeyear','personalemail'
]
def save(self, commit=True):
user = super(StudentNewRegistrationForm, self).save(commit=False)
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.email = self.cleaned_data['email']
user.personalemail = self.cleaned_data['email']
user.title = self.cleaned_data['title']
user.intakeyear = self.cleaned_data['intakeyear']
user.status = self.cleaned_data['status']
user.password1 = self.cleaned_data['password1']
user.password2 = self.cleaned_data['password2']
if commit:
user.save()
return user
views.py:
from django.shortcuts import render, redirect
from django.urls import reverse
from django.contrib.auth.models import User
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.decorators import login_required
from .forms import StudentNewRegistrationForm
def student_new_registration(request):
if request.method == 'POST':
form = StudentNewRegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect(reverse('student:home'))
else:
form = StudentNewRegistrationForm()
args = {'form': form}
return render(request, 'student/studentnewregistrationform.html', args)
studentnewregistrationform.html:
{% extends 'base.html' %}
{% block head %}
<title>Student Registration  Form</title>
{% endblock %}
{% block body %}
<div class="container">
<form method="post">
{% csrf_token %}
<div class="row">
<div class="col-sm-4">
<h3> Student Registration Form</h3>
</div>
</div>
<br>
<div class="row">
<div class="col-sm-2">{{ form.title.label }}</div>
<div class="col-sm-3">{{ form.title }}</div>
<div class="col-sm-4">{{ form.title.errors }}</div>
</div>
<br>
<div class="row">
<div class="col-sm-2">{{ form.firstname.label }}</div>
<div class="col-sm-3">{{ form.firstname }}</div>
<div class="col-sm-4">{{ form.firstname.errors }}</div>
</div>
<br>
<div class="row">
<div class="col-sm-2">{{ form.lastname.label }}</div>
<div class="col-sm-3">{{ form.lastname }}</div>
<div class="col-sm-4">{{ form.lastname.errors }}</div>
</div>
<br>
<div class="row">
<div class="col-sm-2">{{ form.email.label }}</div>
<div class="col-sm-3">{{ form.email }}</div>
<div class="col-sm-4">{{ form.email.errors }}</div>
</div>
<br>
<div class="row">
<div class="col-sm-2">{{ form.personalemail.label }}</div>
<div class="col-sm-3">{{ form.personalemail }}</div>
<div class="col-sm-4">{{ form.personalemail.errors }}</div>
</div>
<br>
<br>
<div class="row">
<div class="col-sm-2">{{ form.intakeyear.label }}</div>
<div class="col-sm-3">{{ form.intakeyear }}</div>
<div class="col-sm-4">{{ form.intakeyear.errors }}</div>
</div>
<br>
<div class="row">
<div class="col-sm-2"><label for="{{ form.password1.label }}">Password</label></div>
<div class="col-sm-3">{{ form.password1 }}</div>
<div class="col-sm-4">{{ form.password1.errors }}</div>
</div>
<br>
<div class="row">
<div class="col-sm-2"><label for="{{ form.password2.id_for_label }}">ConfirmPassword</label></div>
<div class="col-sm-3">{{ form.password2 }}</div>
<div class="col-sm-4">{{ form.password2.errors }}</div>
</div>
<br><br>
<div class="row">
<div class="col-sm-2 col-sm-offset-2"> <input type="submit" name="submit" value="Submit" class="btn btn-primary"/></div>
<div class="col-sm-2"></div>
</div>
</form>
</div>
{% endblock %}
Здесь я загрузил данные для моделей статусов и названий, таких как выпадающий список, сейчас я не знаю, где я ошибся, я получаю ошибку
ValueError at /student/studentnewregistration/
Cannot assign "'100000002'": "User.title" must be a "Title" instance.
Помогите кому-нибудь Спасибо заранее