我有一个django项目,我有一个带有复选框的列表,选择和分配学生给老师。我在下面附上了我的代码-我没有得到任何错误,但它似乎并没有分配给学生的"学生";多对多领域在我的"老师";模型。
我有一个之前调用的GET函数来选择老师,然后它意味着提取GET记录并将学生分配给该老师。
任何想法?
Views.py
if 'assign_student' in request.POST:
form = StudentForm(request.POST)
selected = request.GET['select_teacher']
selected_teacher = Teacher.objects.all().filter(pk=selected)[0]
if form.is_valid():
student_selected = request.POST('assign_student')
student = Student.objects.all().filter(pk=student_selected)[0]
selected_teacher.students.add(student)
Template.html
<div class="student-list">
{% for instance in all_students %}
<div class="input-group" style="border-bottom: 1px solid;">
<div class="item-details">
<div class="form-check">
<form method="POST" class="form-group" name="assign_student">
{% csrf_token %}
<input onChange="this.form.submit()" class="form-check-input" type="checkbox" value={{ instance.pk }} id="flexCheckDefault" name="assign_student">
</form>
<p>
<b>{{ instance.fullname }}</b>
<br>
{{ instance.homeschool }} - {{ instance.schoolclass }} Class
</p>
</div>
</div>
</div>
{% endfor %}
</div>
Models.py
class Teacher(models.Model):
fullname = models.CharField(max_length=10000,verbose_name='Full Name')
firstname = models.CharField(max_length=10000,verbose_name='First Name')
lastname = models.CharField(max_length=10000,verbose_name='Last Name')
school = ForeignKey(School,on_delete=models.CASCADE,verbose_name='School')
creationuser = ForeignKey(CustomUser,on_delete=models.CASCADE)
students = models.ManyToManyField(Student)
class Role(models.TextChoices):
principal = 'principal'
classroomteacher = 'classroom teacher'
assistantprincipal = 'assistant principal'
role = models.CharField(
max_length=10000,
choices=Role.choices,
verbose_name='Role',
)
email = models.EmailField(verbose_name='Email Address')
def __str__(self):
return self.fullname
它不工作的原因是因为您使用过滤器等使用查询。因此,返回的是查询集而不是对象。您应该使用get_object_or_404()
.
此外,您是在为会话保存数据,而不是在数据库中。您应该使用students.save()
将其保存在DB中。
你可以这样做
from django.shortcuts import get_object_or_404
if 'assign_student' in request.POST:
form = StudentForm(request.POST)
selected = request.GET['select_teacher']
selected_teacher = get_object_or_404(Teacher, pk=selected)
if form.is_valid():
student_selected = request.POST('assign_student')
student = get_object_or_404(Student, pk=student_selected)
selected_teacher.students.add(student)
selected_teacher.save() #saving the teacher model object
selected_teacher.students.save() #saving the student model object
我真傻!
我修复了它,我试图得到一个"if form.is_valid()"当我没有张贴一个完整的形式-删除,一切都是现在工作。