Reputation: 33
I am currently using django 3.2 and when I try to print the models data in the views it throws the following error
My views look like this
from django.shortcuts import render, HttpResponse, redirect
from django.contrib.auth.decorators import login_required
from user.models import Student
@login_required
def home(request):
user = request.user
student_user = Student.objects.all()
student_users = []
for user in student_user:
student_users.append(user.User.username)
stu_user = request.user.username
student_list_set = set(student_users)
if stu_user in student_list_set:
data = Student.objects.filter(User=request.user)
print(data.Name)
params = {
'data':student,
}
return render(request, 'dashboard/student/dashboard.html', params)
When I try to print the print the data.name. It throws the following error
AttributeError at /
'QuerySet' object has no attribute 'Name'
My models.py file looks like this
class Student(models.Model):
User = models.ForeignKey(User, on_delete=models.CASCADE)
Name = models.CharField(max_length=50)
Profile = models.ImageField(upload_to = upload_student_profile_to, default =
'defaults/student_profile.png')
class_choices = (('1','1'), ('2','2'), ('3','3'), ('4','4'),('5','5'),('6','6'),('7','7'),('8','8'),
('9','9'),('10','10'))
Class = models.CharField(max_length=100, choices=class_choices)
section_choices = (('A','A'),('B','B'),('C','C'),('D','D'),('E','E'))
Section = models.CharField(max_length=100, choices=section_choices)
Roll = models.IntegerField(blank=True)
Number = models.IntegerField(blank=True)
is_banned = models.BooleanField(default=False)
def __str__(self):
return self.Name + " of " + self.Class
Upvotes: 0
Views: 327
Reputation: 962
If it can only exist one student per user, the simplier way of doing it is like this:
student = Student.objects.get(User=request.user)
print(student.name)
Check this post to understand when to user .get()
and when to use .filter()
.
Upvotes: 0
Reputation: 5580
data variable is a queryset, not a Student object, so you should access like a list.
If you are sure that
data = Student.objects.filter(User=request.user)
returns one element you can print like this:
print(data[0].Name)
Upvotes: 1