How to get django model 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 solve this problem. I want to get the value of a model field from a model object in a template.

+6
source share
2 answers

This is because the p you submit to your view is a QuerySet, not an instance of an object. 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 want to send a specific instance of p , you will need to do the following in your view:

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

but note that get throws an error if the request returns more than one object with version = m2.

+6
source

In your opinion, you referred to Discussion1, which is not the name of your model (discussion). It is also not obvious where m2 is assigned.

I would make sure that:

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

returns objects from the shell. At a minimum, you will get an empty list.

It helps us a lot if you format your code correctly, in addition to providing sufficient context so that we can find out where things came from, etc., to give an answer.

0
source

Source: https://habr.com/ru/post/892965/


All Articles