Django 2.2版
我在Django中有模型
class Class_teacher(models.Model):
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
empid = models.CharField(max_length=10)
standard = models.IntegerField()
division = models.CharField(max_length=1)
subject = models.CharField(max_length=200)
email = models.EmailField(max_length=30)
def __str__(self):
return self.first_name + ' -- ' + str(self.school)
class Student(models.Model):
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
classteacher = models.ForeignKey('Class_teacher', on_delete=models.CASCADE, )
reg_id = models.CharField(max_length=15)
parent_first_name = models.CharField(max_length=200)
parent_second_name = models.CharField(max_length=200)
email = models.EmailField(max_length=100)
def __str__(self):
return self.first_name + ' ' + self.last_name
添加学生的视图
class StudentCreate(LoginRequiredMixin, CreateView):
login_url = '/signin/'
model = Student
fields = ['first_name', 'last_name', 'parent_first_name','parent_second_name', 'email', 'reg_id']
success_url = '/dashboard/'
该网络应用具有以下登录功能,
def signin(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect('../dashboard/')
else:
return HttpResponse("Your account was inactive.")
else:
return HttpResponse("Invalid login details given")
else:
return render(request, 'webapp/login.html')
def dashboard(request):
email = request.user.email
if Class_teacher.objects.filter(email__iexact=email).count() == 1:
students = Student.objects.values('classteacher')
context = { 'students' : students}
return render(request, 'webapp/dashboard.html',context)
dashboard.html模板
{% if students %}
<ol>
{% for student in students %}
<li>{{student.first_name}} {{student.last_name}}</li>
{% endfor %}
</ol>
{% else %}
<h3>No Students Added</h3>
{% endif %}
{% endblock %}
我使用了students = Student.objects.values('classteacher')
,但是它没有提供学生姓名,只显示有序的列表编号。
我有两个要求
class StudentCreate(LoginRequiredMixin, CreateView):
login_url = '/signin/'
model = Student
fields = ['first_name', 'last_name', 'parent_first_name','parent_second_name', 'email', 'reg_id' , 'classteacher']
success_url = '/dashboard/'
我对studentadd视图的要求是,应将学生添加到各自已登录的老师下方,而无需通过表格提供老师的价值
答案 0 :(得分:1)
您的filtered学生有误。
尝试一下:
def dashboard(request):
email = request.user.email
class_teacher = Class_teacher.objects.get(email=email)
students = Student.objects.filter(classteacher=class_teacher)
return render(request, 'webapp/dashboard.html', {'students': students})