在进行“objects.get()”查询时,获取“全局名称未定义错误”

时间:2012-06-04 11:25:51

标签: python database django

我收到错误

  

全局名称'name'未定义...

代表subjects = Course...行。我想查询主题名称,以便我可以在主题模板中使用它们

模特

from django.db import models
from django.contrib.auth.models import User

class Course(models.Model):

name      = models.CharField(max_length = 100)
 stype      = models.CharField(max_length = 100)
 subject   = models.CharField(max_length = 100)
 location  = models.CharField(max_length = 100) 

class Teacher(models.Model):
 username      = models.ForeignKey(User,unique = True)
 address   = models.CharField(max_length = 200)
 city      = models.CharField(max_length = 50)   
 email_address = models.EmailField(max_length=75, unique = True)

class Student(models.Model):
 username      = models.ForeignKey(User,unique = True)
 address       = models.CharField(max_length = 200)
 city          = models.CharField(max_length = 50)   
 email_address = models.EmailField(max_length=75, unique = True)


class Attendance(models.Model):

 course    = models.ForeignKey(Course,unique = True)
 student   = models.ForeignKey(Student,unique = True)
 teacher   = models.ForeignKey(Teacher,unique = True)
 date      = models.DateField(unique = True)
 status    = models.BooleanField(unique = True)
 created_at= models.DateTimeField(auto_now_add = True)
 updated_at= models.DateTimeField(auto_now = True)

 def subjects(request,username):
    user      = User.objects.get(username=username)
    subjects  = Course.objects.get(name = name)
    variables = RequestContext(request,{
        'username': username,
        'subject' : subject
  })   
    return render_to_response('subjects.html', variables)

2 个答案:

答案 0 :(得分:1)

subjects = Course.objects.get(name = name) name未定义。

您可以通过函数参数传递name username

def subjects(request,username, name):

或者用其他字符串代替name,例如:

subjects = Course.objects.get(name ="course_name")

答案 1 :(得分:0)

您在username中获得了def subjects(request,username):,但是......

subjects  = Course.objects.get(name = name)   ### name is not defined here...you have to get it from parameter just like username.