So I am an avid user of both ModelForms and the {{form.as_table}} template tag. This lets me have a generic form template that I can reuse without knowing my specific fields. Now I’d like to print that same model out exactly like I did for the form, but without the form fields. I have never come across a good way to do this. Anyone know of one?
Here is an example, to be more specific:
model:
class ExampleModel(models.Model):
info1 = models.TextField()
info2 = models.TextField()
form:
class ExampleForm(forms.ModelForm):
class Meta:
model = ExampleModel
view:
def example_form_view(request):
form = ExampleForm()
return render_to_response('form.html', locals(), context_instance=RequestContext(request))
def example_display_view(request):
model = ExampleModel.objects.get(id=1)
return render_to_response('model.html', locals(), context_instance=RequestContext(request))
To print out the form, I have a template that has:
<form action="." method="post">
{% csrf_token %}
<table>
{{ form.as_table }}
<tr>
<td></td>
<td><input type='submit' value="submit" /></td>
</tr>
</table>
</form>
And I’d also like to be able to have a generic template that includes this:
<table>
{{ model.as_table }}
</table>
and get the same layout as the form one, but without the form. Anyone know of any way to do this?
I apologize if this has been asked before, but I did a search and didn’t find anything. Although I wasn’t sure what to search for.
You could define an
as_tablemethod on your model (or a superclass if you want to reuse it in multiple models) such as: