how to check if an object exists in the database and then insert it into a form in django
<p>I have the following model:<code>models.py</code></p>

<pre><code>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)
</code></pre>

<p>I have created a form using <code>ModelForm</code> like this:</p>

<pre><code>class IssueItemForm(ModelForm):

class Meta:
    model = IssuedItem
    fields = '__all__'
</code></pre>

<p>A dealer needs to check if a certificate Holder exists before issuing the item, My code for that looks like this;</p>

<pre><code>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)
</code></pre>

<p>Then I have templates <code>search.html</code> and <code>results.html</code></p>

<pre><code>&lt;form method="get" action="/search/"&gt;
&lt;input type="text" name="q" id="id_q" value="{{ query }}"/&gt;
&lt;input type="submit" value="Search" /&gt;
&lt;/form&gt;
</code></pre>

<p>In results.html I have</p>

<pre><code>{% if results %}
&lt;h3&gt;The Certificate number is valid&lt;/h3&gt;
&lt;h3&gt;To issues an item click the button below&lt;/h3&gt;
&lt;a href="{% url 'issueitem' %}"&gt;Issue A New Item&lt;/a&gt;

{% else %}
&lt;h3 class='error'&gt;Please enter a valid Certificate&lt;/h3&gt;
&lt;form method="get" action="/search/"&gt;
  &lt;input type="text" name="q" id="id_q" value="{{ query }}"/&gt;
  &lt;input type="submit" value="Search" /&gt;
&lt;/form&gt;

{% endif %}
</code></pre>

<p>The code works if there is a certificate in the database but if there is no match it throws an error like this:</p>

<p><a href="http://i.stack.imgur.com/CFkmW.png" rel="nofollow">error image</a></p>

<p>However I would like the error to be part of the code to tell the dealer that that number does not exist and that he should try another. Also when a certificate exists I would like it to be inserted into the holder field instead of fetching from the database like it is doing now. Where am i going wrong?</p>