我使用Django框架为学校创建了学校数据库内联网应用。我正在尝试让老师在“老师”帐户中更新注册学生的评估。我已经使用ForeignKey关系将学生帐户与评估模型相关联,但是我似乎正在得到这个
ValueError at /Teacher/Grade9_classA_teacher/Grd9_ClsA_math_Term_1_assesment1_createview2b2371fd-7e64-413a-adcd-43c8b68cd9d3/
Cannot assign "<QuerySet [<Grade_9_Student: account1>]>": "Grade_9_models_math_Term1_assesment_1.user_Name" must be a "Account" instance.
我不知道这意味着什么,请有人帮助解决我的问题。 这是我的评估模型代码
from admin_app.models import Account
#Assessment models
class Grade_9_models_math_Term1_assessment_1(models.Model):
user_Name=models.ForeignKey(Account, on_delete=models.CASCADE, default=None, max_length=250, blank=True, null=True)
T1_A1_Maths_Title=models.CharField(max_length=50, blank=True, null=True)
T1_A1_Maths_Desc=models.CharField(max_length=100, blank=True, null=True)
T1_A1_Maths_is_Test=models.BooleanField(default=False)
T1_A1_Maths_Marks=models.IntegerField(blank=True, null=True, default=0)
T1_A1_Maths_OutOfMarks=models.IntegerField(blank=True, null=True, default=0)
T1_A1_Maths_DatePosted=models.DateTimeField(verbose_name='date posted', auto_now_add=False, null=True, blank=True)
这是我的评估表格代码 #Forms.py
from Student.student_views.Grade9_std_views.Grade9_models import Term_11_math_assesment, Grade_9_Student
#Term 1
#Maths assesment 1
class Grd9_ClsA_math_Term_1_assesment1_form(ModelForm):
T1_A1_Maths_is_Test=forms.BooleanField(widget=forms.CheckboxInput)
class Meta:
model=Grade_9_models_math_Term1_assesment_1
fields=['T1_A1_Maths_Title', 'T1_A1_Maths_Desc', 'T1_A1_Maths_is_Test', 'T1_A1_Maths_Marks', 'T1_A1_Maths_OutOfMarks', 'T1_A1_Maths_DatePosted']
这是我的主要用户型号代码
from django.db import models
from django.urls import reverse
import uuid
# Create your models here.
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
#from Teacher.Teacher_views.Grade9_views.Grd9_assesment_models import Grade_9_models_math_Term1_assesment_1
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, password=None):
if not email:
raise ValueError("email is not pressent")
if not username:
raise ValueError("username is not pressent")
user=self.model(
email=self.normalize_email(email),
username=username
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password):
user=self.create_user(
email=self.normalize_email(email),
password=password,
username=username
)
user.is_admin=True
user.is_staff=True
user.is_superuser=True
user.save(using=self._db)
return user
class Account(AbstractBaseUser):
#Identification details
id=models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
email=models.EmailField(verbose_name="email", max_length=60, unique=True)
username=models.CharField(max_length=30, unique=True)
date_joined=models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login=models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin=models.BooleanField(default=False)
is_active=models.BooleanField(default=True)
is_staff=models.BooleanField(default=False)
is_superuser=models.BooleanField(default=False)
#Code test
USERNAME_FIELD='username'
REQUIRED_FIELDS=['email',]
def get_absolute_url(self):
return reverse('headmin:Grade_9_Teacher_list_details', args=[str(self.id)])
objects=MyAccountManager()
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
def __str__(self):
return self.username
#Student models
class Grade_9_Student(Account):
#T1_A1_Maths_Marks=models.ForeignKey(Grade_9_models_math_Term1_assesment_1, null=True, blank=True, on_delete=models.CASCADE)
Grade_9_student_classA_A=models.BooleanField(default=False)
Grd9_ClsA_std_profile_picture=models.ImageField(upload_to='Student/Grade9/Grd9ClassA/Grd9ClsAProPic/')
first_name=models.CharField(max_length=30)
last_name=models.CharField(max_length=30)
phone_no=models.CharField(max_length=11, blank=True, null=True)
date_of_birth=models.DateField(blank=True, null=True)
full_name=models.CharField(max_length=100)
Resident=models.CharField(max_length=100)
#views.py
这是我用来尝试将Grade_9_models_math_Term1_assesssment_1附加到
的功能代码。def Grd9_ClsA_math_Term_1_assesment1_createview(request, pk):
std=Grade_9_Student.objects.filter(id=pk)
if request.method=='POST':
form=Grd9_ClsA_math_Term_1_assesment1_form(request.POST, request.FILES)
if form.is_valid():
instance=form.save(commit=False)
instance.T1_A1_Maths_Title=std
instance.save()
return redirect('Teacher:Grade_9_students_clsA_lists')
else:
form=Grd9_ClsA_math_Term_1_assesment1_form()
return render(request, 'Grade9Teach/Tgrd9A/Upload_assesments_subjects/upload_assesments.html', {'form':form})
这是我的网址代码
urlpatterns=[
path('Grade9_classA_teacher/', include(([
path('', Grd9_ClsA_Teach_view.Grade9_classA_teacher, name='Grade9_classA_teacher'),
path('searchResult_view_grd9_A/', Grd9_ClsA_Teach_view.searchResult_view_grd9_A.as_view(), name='searchResult_view_grd9_A'),
#Term 1 assesments
#MATH
path('Grd9_ClsA_math_Term_1_assesment1_view<uuid:pk>/', Grd9_ClsA_assesment_views.Grd9_ClsA_math_Term_1_assesment1_view.as_view(), name='Grd9_ClsA_math_Term_1_assesment1_view'),
path('Grd9_ClsA_math_Term_1_assesment1_view<int:pk>/', Grd9_ClsA_assesment_views.Grd9_ClsA_math_Term_1_assesment1_view.as_view(), name='Grd9_ClsA_math_Term_1_assesment1_view'),
path('Grd9_ClsA_math_Term_1_assesment1_createview<uuid:pk>/', Grd9_ClsA_assesment_views.Grd9_ClsA_math_Term_1_assesment1_createview, name='Grd9_ClsA_math_Term_1_assesment1_createview'),
], 'Teacher'))),
]
#网络浏览器 ValueError
Cannot assign "<QuerySet [<Grade_9_Student: account1>]>": "Grade_9_models_math_Term1_assesment_1.user_Name" must be a "Account" instance.
#控制台日志
System check identified no issues (0 silenced).
July 10, 2020 - 14:35:09
Django version 3.0.3, using settings 'SchoolDatabaseTrial.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Internal Server Error: /Teacher/Grade9_classA_teacher/Grd9_ClsA_math_Term_1_assesment1_createview2b2371fd-7e64-413a-adcd-43c8b68cd9d3/
Traceback (most recent call last):
File "C:\Users\Yuri\Envs\core\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Yuri\Envs\core\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Yuri\Envs\core\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Yuri\SchoolDatabaseTrial\Teacher\Teacher_views\Grade9_views\Grd9_ClsA_views\Grd9_ClsA_std\Grd_9_Marks_forms_and_views\Grd9_ClsA_assesment_views.py", line 71, in Grd9_ClsA_math_Term_1_assesment1_createview
instance.user_Name=Grade_9_Student.objects.filter(id=pk)
File "C:\Users\Yuri\Envs\core\lib\site-packages\django\db\models\fields\related_descriptors.py", line 219, in __set__
self.field.remote_field.model._meta.object_name,
ValueError: Cannot assign "<QuerySet [<Grade_9_Student: account1>]>": "Grade_9_models_math_Term1_assesment_1.user_Name" must be a "Account" instance.
[10/Jul/2020 14:35:15] "POST /Teacher/Grade9_classA_teacher/Grd9_ClsA_math_Term_1_assesment1_createview2b2371fd-7e64-413a-adcd-43c8b68cd9d3/ HTTP/1.1" 500 81054
请帮助我,如何解决我的问题?
答案 0 :(得分:1)
您的代码示例与您的追溯不同。在回溯中,您具有:
instance.user_Name=Grade_9_Student.objects.filter(id=pk)
因为使用的是filter()
,所以您试图将其中包含单个Account实例的QuerySet分配给需要Account实例的字段。您可以将其更改为以下之一:
# Recommended since you're querying by a unique PK value
instance.user_Name=Grade_9_Student.objects.get(id=pk)
# The same as above, but with extra steps
instance.user_Name=Grade_9_Student.objects.filter(id=pk).first()