Django admin forms - using a different/unconventional widget for a field

65 views
Skip to first unread message

filias

unread,
Sep 3, 2012, 8:13:21 AM9/3/12
to django...@googlegroups.com
Hi,

I have a DateTimeField in my model but I want to show with a CheckboxInput.

We have a DateTime field in the model because we want to save the datetime when the instance was cancelled but we dont want the user to see that and just check or uncheck the cancellation checkbox.

I already overrode the save method of the form to transform the boolean of the checkbox into datetime.now() but I also need the vice-versa: to show the checkbox checked or unchecked according to the presence or not of a date.

How can I do that?

Thanks in advance.

zayatzz

unread,
Sep 3, 2012, 9:28:29 AM9/3/12
to django...@googlegroups.com
In form, that displays the checkbox do something like this:
def __init__(self, *args, **kwargs):
    super(FormName, self).(*args, **kwargs)
    if self.instance and self.instance.checkboxfieldname != None: #we check if this form has instance and if checkbox :
        attrs = {'checked':'checked'}
    else:
        attrs = {}
    self.fields['checkboxfieldname'] = forms.BooleanField(widget = forms.CheckboxInput(attrs = attrs))

should work.
alan

filias

unread,
Sep 3, 2012, 10:40:03 AM9/3/12
to django...@googlegroups.com
Perfect!

Thanks a lot alan :)

zayatzz

unread,
Sep 3, 2012, 1:44:07 PM9/3/12
to django...@googlegroups.com
No problem man! just trying to help just like i have been helped by others here :)

alan
Reply all
Reply to author
Forward
0 new messages