0

我想从模型中获取对象值。尝试 get() 方法后,我无法使其工作。我收到以下错误。我有一个向用户显示地点名称的页面,所以如果用户看到他喜欢的地点,他会继续填写表格。在表格中,我想自动从另一个地方获取地点的名称模型,我不希望用户填写地点的名称。以下是我的代码

       NameError at /welcome/

       global name 'name' is not defined

楷模

 class Fin(models.Model):
      user=models.ForeignKey(User)
      name=models.CharField(max_length=100)

      def __unicode__(self):
          return self.user


 class Place(models.Model):
      user=models.ForeignKey(User)
      mall=models.ForeignKey(Fin)
      full_name=models.CharField(max_length=100)
      e_mail=models.EmailField(max_length=100)
      phone_no=models.CharField(max_length=100)
      pub_date=models.DateTimeField()

      def __unicode__(self):
          return self.full_name
      class Meta:
         ordering=['-pub_date']

  class PlaceForm(ModelForm):
       class Meta:
         model=Place
         fields=('full_name','e_mail','phone_no')
         exclude=('user','pub_date','mall')

意见:

   def place_me(request):
       if request.method=="POST":
          form=PlaceForm(request.POST)
          if form.is_valid():
             data=form.cleaned_data
             newbooks=Place(
                 user=request.user,
                 pub_date=datetime.datetime.now(),
                 mall=Fin.objects.get(name),
                 full_name=data['full_name'],
                 e_mail=data['e_mail'],
                 phone_no=data['phone_no'])
             newbooks.save()
             return HttpResponse('Thanks for choosing themall, we will contact you as soon as possible. Go grab a beer :)')
         else:
            return HttpResponse('Some fields are not filled correctly')
     else:
        return render_to_response('buuk.html',{'PlaceForm':PlaceForm},context_instance=RequestContext(request))
4

1 回答 1

2

这一行mall=Fin.objects.get(name)您没有name在视图中的任何位置声明变量place_me,因此它是未定义的。

你传递参数的方式.get也是错误的,它必须是这样的:

mall=Fin.objects.get(name='any name')
# or you can do
mall=Fin.objects.get(user=request.user)
于 2012-12-30T22:27:07.947 回答