我一直在看这篇文章:how to populate dropdown list in Django from a foreignkey model我正在寻找下一步。这是我的模特:
class customer(models.Model):
custid = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
email = models.EmailField(max_length=245)
address = models.CharField(max_length=50)
state = models.CharField(max_length=2)
zip = models.CharField(max_length=5)
phone = models.CharField(max_length=13)
class job(models.Model):
jobid = models.AutoField(primary_key=True)
custid = models.ForeignKey('customer')
description = models.TextField()
address = models.CharField(max_length=50)
state = models.CharField(max_length=2)
zip = models.CharField(max_length=5)
这是我的表格:
class JobForm(ModelForm):
class Meta:
model = job
exclude = ['jobid']
以下是我对此页面的看法:
def receivables(request):
"""Renders the receivables page."""
assert isinstance(request, HttpRequest)
job_list = job.objects.all()
cus_list = customer.objects.all()
if request.method == 'POST':
jobForm = JobForm(request.POST)
if jobForm.is_valid():
jobForm.save()
return HttpResponseRedirect('/receivables/')
else:
jobForm = JobForm()
context = RequestContext(request, {
'customers':cus_list,
'jobs':job_list,
'job_form':jobForm
})
return render(
request,
'app/receivables.html',
context
)
我的问题是,每当我在模板中调用{{ jobs.custid }}
时,我都会看到一个如下所示的下拉框:
我希望使用客户视图中的'name'
字段填充这些选项。有什么想法吗?
答案 0 :(得分:0)
为您的客户模型添加__str__
(对于Python2.x __unicode__
)方法:
class customer(models.Model):
custid = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
email = models.EmailField(max_length=245)
address = models.CharField(max_length=50)
state = models.CharField(max_length=2)
zip = models.CharField(max_length=5)
phone = models.CharField(max_length=13)
def __str__(self): # __unicode__ for python2.x
return self.name