python-如何检查数据库中是否存在对象,然后将其插入到Django的表单中
作者:互联网
我有以下模型:models.py
name = models.CharField(max_length=100, blank=False, null=False)
serial_number = models.CharField(max_length=100, blank=False, null=False)
make = models.CharField(max_length=100, blank=False, null=False)
model = models.CharField(max_length=100, blank=False, null=False)
color= models.CharField(max_length=100, blank=False, null=False)
date_acquired = models.DateTimeField(auto_created=True)
acquired_from = models.CharField(max_length=100, choices=ACQUIRED_FROM)
holder = models.ForeignKey(CertificateHolder, blank=False,)
dealer_license = models.ForeignKey(Dealer, blank=False)
我已经使用ModelForm创建了一个表单,如下所示:
class IssueItemForm(ModelForm):
class Meta:
model = IssuedItem
fields = '__all__'
经销商需要在签发物品之前检查是否存在证书持有人,我的代码如下所示;
views.py:
def search(request):
try:
query = request.GET.get('q')
results = 0
except ValueError:
query = None
results = None
if query:
results = CertificateHolder.objects.get(cert_no=query)
context = RequestContext(request)
return render_to_response('core/results.html', {"results": results, }, context_instance=context)
然后我有模板search.html和results.html
<form method="get" action="/search/">
<input type="text" name="q" id="id_q" value="{{ query }}"/>
<input type="submit" value="Search" />
</form>
在results.html我有
{% if results %}
<h3>The Certificate number is valid</h3>
<h3>To issues an item click the button below</h3>
<a href="{% url 'issueitem' %}">Issue A New Item</a>
{% else %}
<h3 class='error'>Please enter a valid Certificate</h3>
<form method="get" action="/search/">
<input type="text" name="q" id="id_q" value="{{ query }}"/>
<input type="submit" value="Search" />
</form>
{% endif %}
如果数据库中有证书,则该代码有效,但是如果不匹配,则会引发如下错误:
但是,我希望该错误成为代码的一部分,以告诉经销商该号码不存在,他应该尝试另一个.另外,当证书存在时,我希望将其插入到holder字段中,而不是像现在那样从数据库中获取证书.我要去哪里错了?
解决方法:
您还必须捕获DidNotExist错误.将if查询改为try try块:
try:
result = CertificateHolder.objects.get(cert_no=query)
except DoesNotExist:
pass
标签:django-forms,python,django,django-models 来源: https://codeday.me/bug/20191119/2032247.html