Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output Django Model as Table

I have a view definition that (attempts to) outputs a model as a table. This is what I have so far:

def output_table(request):
    output = My_Model()
    return render_to_response('outputtable.html', {'output': output})

Here's the HTML for outputtable.html:

<html>
<table>
    {{ output.as_table }}
</table>
</html>

What am I doing wrong? It doesn't work. Now, it's passing the model correctly, because if I change My_Model() to My_Model.objects.all() and then output it as simply {{ output }} then it shows me what I would see in the Django shell.

like image 563
Reznor Avatar asked Feb 17 '10 19:02

Reznor


People also ask

Is a Django model a table?

A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you're storing. Generally, each model maps to a single database table.

How to save data in Django models?

Saving changes to objects To save changes to an object that's already in the database, use save() . This performs an UPDATE SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() .

What is PK in Django?

pk is short for primary key, which is a unique identifier for each record in a database. Every Django model has a field which serves as its primary key, and whatever other name it has, it can also be referred to as "pk".


2 Answers

So what you need to do is the following:

1) add

from django.forms import ModelForm to your models.py

2) add

class My_Model_Form(ModelForm):  
           class Meta:  
               model = My_Model 

3) in your views.py, change output = My_Model() to output = My_Model_Form()

Now you are all set. So the trick is to inherit your Form from your original model.

like image 94
DrDee Avatar answered Oct 02 '22 23:10

DrDee


If you're just looking to output one specific model, change your template to something like

<tr>
  <td>Name:</td>
  <td>{{ output.name}}</td>
</tr>

for all the fields you care about. If this is something you want to be able to do for any arbitrary model in your app, take a look at this snippet. That would provide you with a fields collection to loop over.

like image 23
Tom Avatar answered Oct 03 '22 01:10

Tom