shiva
shiva

Reputation: 2770

How to get django models field value from model object in template tags

Models.py:

class Discussion(models.Model):
    version = models.TextField(blank=True)
    team = models.TextField(blank=True)
    project = models.TextField(blank=True)
    notes = models.TextField(db_column='Notes', blank=True) # Field name made lowercase.
    s = models.TextField(blank=True)
    send_mail_to = models.TextField(blank=True)
    send_mail_cc = models.TextField(blank=True)
    date = models.DateTimeField(null=True, blank=True)

    class Meta:
        db_table = u'discussion'

views.py:

 p=Discussion.objects.filter(version=m2)
 return render_to_response('report/t2',{"p":p})

Template(html):

 <tr>
      <td width="20%" class="scratchblackfont12">Release Name :</td>
      <td><div style="overflow:auto"><input name="Release Name (if any ):" autocomplete="on" type="text" class="scratchsearchfield" elname="defaultFocus" id="r1" value="{{p.version}}"  READONLY multiline="true" ></div>
      </td>
    </tr>

But the template displays Nothing.Please help me to solve this problem.I want to get the model field value from model object in template.

Upvotes: 6

Views: 9824

Answers (2)

rolling stone
rolling stone

Reputation: 13016

That's because the p that you're sending to your view is a QuerySet, not an object instance. Try the following:

{% for p_object in p %}
<tr>
    <td width="20%" class="scratchblackfont12">Release Name :</td>
    <td><div style="overflow:auto"><input name="Release Name (if any ):" autocomplete="on" type="text" class="scratchsearchfield" elname="defaultFocus" id="r1" value="{{p_object.version}}"  READONLY multiline="true" ></div>
    </td>
</tr>
{% endfor %}

If you'd like to send a specific p object instance you'd have to do the following in your view:

p = Discussion.objects.get(version=m2)

but note that get will throw an error if the query returns more than a single object with version=m2.

Upvotes: 7

Brandon Taylor
Brandon Taylor

Reputation: 34553

In your view, you've referenced Discussion1, which isn't the name of your model (Discussion). It's also not obvious where the value of m2 gets assigned.

I would verify that:

objects = Discussion.objects.filter(version=m2)

returns objects from the shell. At the minimum, you'll get an empty list.

It helps us out a lot if you format your code properly, in addition to providing enough context so we can tell where things come from, what's what and so on, in order to provide answer.

Upvotes: 0

Related Questions