Views.py
#For Student Registration
def StudentSignUp(request):
user_type = 'Student'
registered= False
if request.method == "POST":
logger_Form = loggerform(data = request.POST)
Student_Form = StudentForm(data = request.POST)
if logger_Form.is_valid() and Student_Form.is_valid():
user = logger_Form.save()
user.is_student = True
user.save()
profile = Student_Form.save(commit=False)
profile.user = user
profile.save()
registered = True
else:
print(logger_Form.errors,Student_Form.errors)
else:
logger_Form = loggerform()
Student_Form = StudentForm()
return render(request,'student_signup.html',{'logger_Form':loggerform,'Student_Form':StudentForm,'registered':registered,'user_type':user_type})
# FOR teacher Registration
def TeacherSignUp(request):
user_type = 'Teacher'
registered = False
if request.method == "POST":
logger_Form = loggerform(data = request.POST)
Teacher_Form = TeacherForm(data = request.POST)
if logger_Form.is_valid() and Teacher_Form.is_valid():
user = logger_Form.save()
user.is_teacher = True
user.save()
profile = Teacher_Form.save(commit=False)
profile.user = user
profile.save()
registered = True
else:
print(logger_Form.errors,Teacher_Form.errors)
else:
logger_Form = loggerform()
Teacher_Form = TeacherForm()
return render(request,'teach_signup.html',{'logger_Form':loggerform,'Teacher_Form':TeacherForm,'registered':registered,'user_type':user_type})
#List of all the students that teacher has added in their class
def class_students_list(request):
query = request.GET.get("q", None)
students = StudentsInClass.objects.filter(teacher = request.user.Teacher)
students_list = [x.student for x in students]
qs = Student.objects.all()
if query is not None:
qs = qs.filter(
Q(name__icontains=query)
)
qs_one = []
for x in qs:
if x in students_list:
qs_one.append(x)
else:
pass
context = {
"class_students_list": qs_one,
}
template = "class_students_list.html"
return render(request, template, context)
class ClassStudentsListView(LoginRequiredMixin,DetailView):
model = models.Teacher
template_name = "class_students_list.html"
context_object_name = "teacher"
型号.py
class logger(AbstractUser):
is_student = models.BooleanField(default=False)
is_teacher = models.BooleanField(default=False)
class Student(models.Model):
username = models.OneToOneField(logger,on_delete=models.CASCADE,primary_key=True,related_name='Student')
name=models.CharField(max_length=250)
roll_no = models.CharField(max_length=50)
email = models.EmailField(max_length=254)
def __str__(self):
return self.name
class Meta:
ordering = ['roll_no']
class Teacher(models.Model):
username = models.OneToOneField(logger,on_delete=models.CASCADE,primary_key=True,related_name='Teacher')
name = models.CharField(max_length=250)
subject_name = models.CharField(max_length=250)
email = models.EmailField(max_length=254)
class_students = models.ManyToManyField(Student,through="StudentsInClass")
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('teacher_detail',kwargs={'pk':self.pk})
class StudentsInClass(models.Model):
teacher = models.ForeignKey(Teacher,related_name="class_teacher",on_delete=models.CASCADE)
student = models.ForeignKey(Student,related_name="user_student_name",on_delete=models.CASCADE)
def __str__(self):
return self.student.name
class Meta:
unique_together = ('teacher','student')
forms.py
# User Login Form common for both student and teacher login
class loggerform(UserCreationForm):
class Meta():
model = logger
fields = ['username','password1','password2']
widgets = {
'username': forms.TextInput(attrs={'class':'answer'}),
'password1': forms.PasswordInput(attrs={'class':'answer'}),
'password2': forms.PasswordInput(attrs={'class':'answer'}),
}
# Teacher SignUp Form
class TeacherForm(forms.ModelForm):
class Meta():
model = Teacher
fields = ['name','subject_name','email']
widgets = {
'name': forms.TextInput(attrs={'class':'answer'}),
'subject_name': forms.TextInput(attrs={'class':'answer'}),
'email': forms.EmailInput(attrs={'class':'answer'}),
}
# Student SignUp Form
class StudentForm(forms.ModelForm):
class Meta():
model = Student
fields = ['name','roll_no','email']
widgets = {
'name': forms.TextInput(attrs={'class':'answer'}),
'roll_no': forms.NumberInput(attrs={'class':'answer'}),
'email': forms.EmailInput(attrs={'class':'answer'}),
}
class_students_list.html
{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="student-list">
<div class="container">
{% if class_students_list.count == 0 %}
<h1>No students in the class.</h1>
{% else %}
<form method='GET' action="{% url 'class_student_list' %}">
<p>Search Student: <input type='search' name='q' placeholder='Search'></p>
</form>
<div class="row">
{% for student in class_students_list %}
<div class="col-6 col-md-4">
<div class="student-box">
<div class="imgBx">
{% if student.student_profile_pic %}
{% else %}
{% if forloop.counter0|divisibleby:"2" %}
{% else %}
{% endif %}
{% endif %}
</div>
<div class="content">
<h3>{{ student.name }}</h3>
<p><i class="far fa-user"></i> Username: {{ student.user.username }}</p>
<p><i class="fal fa-user-tag"></i> Roll No.: {{ student.roll_no }}</p>
<p><i class="far fa-phone"></i> Phone: {{ student.phone }}</p>
<p><i class="far fa-envelope-open-text"></i> Email ID: {{ student.email }}</p>
<a href="#"><p class="add-button">View Marks Profile</p></a>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% endif %}
</div>
{% endblock %}
这是我得到的追踪:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/vinayak/Desktop/CS IA /src/IB_Portal/Portal/views.py", line 125, in class_students_list
students = StudentsInClass.objects.filter(teacher = request.user.Teacher)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/functional.py", line 241, in inner
return func(self._wrapped, *args)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 421, in __get__
raise self.RelatedObjectDoesNotExist(
Portal.models.logger.Teacher.RelatedObjectDoesNotExist: logger has no Teacher.
[28/Feb/2021 10:02:23] "GET /teacher/class_students_list HTTP/1.1" 500 67048
我已经发布了我的代码,上面我不知道为什么我一直在标题中出现错误,我似乎不明白,有人能帮我吗,我还在学校,是django的新手。任何形式的帮助都将不胜感激。任何能解决问题的人,请发布解决方案。非常感谢。
首先,在您的注册视图中,您编写profile.user = user
,而在您的模型中,此字段被命名为username
。将此行更改为profile.username = user
或更改字段名称。我建议使用该字段的名称,因为它目前没有意义。
由于非教师用户不应该访问该视图,您也应该将该限制添加到您的视图中(您可能会因为非教师用户访问该视图而出现错误)。一个简单的方法是使用user_passes_test
装饰器:
from django.contrib.auth.decorators import user_passes_test
def user_is_teacher(user):
return user.is_authenticated and user.is_teacher
@user_passes_test(user_is_teacher)
def class_students_list(request):
...
接下来,你对学生的筛选有点太复杂了。这可以通过ORM以更简单的方式完成。如果你使用ManyToManyField
,它会更容易。您可以将其添加到Student
型号或Teacher
型号中。因为从您的代码来看,Teacher
模型是稍后定义的,我们会在其中添加多对多字段。考虑到您已经有了一个建立这种关系的模型,我们将其保留为through
模型:
class Teacher(models.Model):
# Your other fields
students = models.ManyToManyField(Student, related_name="teachers", through="StudentsInClass")
现在在您看来:
@user_passes_test(user_is_teacher)
def class_students_list(request):
query = request.GET.get("q", None)
students = request.user.Teacher.students.all()
if query is not None:
students = students.filter(Q(name__icontains=query))
context = {
"class_students_list": students,
}
template = "class_students_list.html"
return render(request, template, context)