2

I have an awesome widget to display information, and I want to use it in a template but without using a form.

My template is used only to display info, there is no form to be submited. How can I render this widget in a template without using a form. I have to take into account that the widget is feed with some user data. Can I use a template tag for this?

thanks!

danielrvt
  • 10,177
  • 20
  • 80
  • 121

2 Answers2

3

The general way I would approach not using a form is to not use an object that's supposed to be in a form. Essentially, I'd create a django template with my widget's HTML code, and a Mixin (As I generally try to only use class based views) or a function that will produce the correct context parameters for the widget.

This keeps the HTML with the HTML, and the logic with the logic. If it's only used to display info, it need not be a widget.

Wherever you want the widget, make sure the mixin is called (functional) or mixed in (Class Based) in your view, and just {% include %} the widget template, and let the template renderer do it's job.

Alex Hart
  • 1,663
  • 12
  • 15
3

Implement the widget's render method in you custom Widget class.

render(self, name, value, attrs=None)

The render method is responsible for the html representation of the widget. E.g the render method of TextInput returns this piece of html:

>>> name = forms.TextInput(attrs={'size': 10, 'title': 'Your name',})
>>> name.render('name', 'A name')
  u'<input title="Your name" type="text" name="name" value="A name" size="10"/>'

You can then add the returned value of the render method to the context of a view.

def my_view(request):
   widget_html = MyCustomWidget.render(...)
   return render_to_response(..., {'widget_html': widget_html})

Now you can display the widget in your template using:

{{ widget_html }}

You could also write a templatetag as @ablm suggested.

thikonom
  • 4,219
  • 3
  • 26
  • 30