Obtaining ID of form in a formset - django

I need a way to set the id of the div that contains each form in a formset to a value that contains a number that is representative of the index of that form.
eg. I want the 2nd form to have a parent div that looks like this
<div id="1"> #id could even be "id_form-1-id".
form
</div>
I've found that {{form.id}} produces the following:
<input type="hidden" name="form-3-id" id="id_form-3-id">
Is there a way that I can extract just the id value (i.e. id_form-3-id) from this string using a template tag?
For reasons that I won't get into, a forloop.counter counter won't reliably return an index as some forms within the formset can be created outside of the typical formset for loop.
Thanks!

You can use auto_id:
{{form.id.auto_id}}

Related

Passing the complete Object Instance, NOT just the object id, from a Django template to view

I am trying to pass full object instances from my django template to my view as the values associated with checkbox inputs. When I try to do so, I only get the object's unicode method representation and am thus unable to access any of the object's particular fields in my view.
Is there either a way to pass the actual object from the template to the view or, instead, a way to use that unicode representation in the view to access the actual object and its corresponding fields?
I don't want to use 'publication.id' as my checkbox value because I can't guarantee the ids will never change.
Current code:
mytemplate.html
<form method="get" action="processData">
{% for publication in mydata %}
<input type="checkbox" name="item-selection" value="{{publication}}">
{% endfor % }
view.py
items = request.GET.getlist('item-selection')
for x in items:
print x # this prints the unicode mehtod's return value
x.datafield1 # I want to access each object's data
No, this can't possibly work: sending data from the browser to the view is done via HTTP post, and you can only post data, you can't post objects.
But you've said the solution yourself: use the IDs. Who cares if the IDs change? All that matters is that you get the ID as it currently is.
<input type="checkbox" name="item-selection" value="{{publication.id}}"><label>{{ publication.name }}</label>
...
item_ids = request.GET.getlist('item-selection')
items = Item.objects.filter(id__in=item_ids)

rounding django input field makes it dissapear

I have a decimal field in my form.
The input displays values like: 60.00
I want it to display: 60
I have tried:
{% load humanize %}
{{ form.amount|floatformat }}
I have also tried changing my form field to an integer:
class AmountInfoForm(forms.ModelForm):
amount = forms.IntegerField()
class Meta:
model = Customer
fields = ('amount',)
This causes the field to disappear.
What am I doing wrong?
I am afraid I see that you are applying floatformat to an input element and not to a valid numeric value. As a consequence, it fails to show and thus Django prefers not to show anything at all.
You could try this workaround then:
First of all, please try printing your form this way:
{{ form.as_table }}
If you look at the source code, you could see that, for example, the input for the field called name is displayed this way:
<input id="id_name" name="name" maxlength="25">
As a consequence, you can emulate this behaviour doing the following in your django template:
<input id="id_{{form.amount.label}}" name="{{form.amount.label}}" maxlength="25" value={{form.amount.value|floatformat:0}}>
Overall,the secret is to apply floatfomat to form.amount.value instead of form.amount.
Hope it works for you!

Django forms: checkboxes are displayed without value

I'm unable to save my form (a ModelForm) properly, since django displays checkboxes without a value (I would expect value="true" on every fields, both checked than unchecked... but that's not the case).
When I submit the form, no data is received in the POST!
The following is a piece o my template:
<div>
{{form.displayAge.label_tag}}
{{form.displayAge}}
{{form.displayAge.errors}}
</div>
{{form.displayAge}} is rendered in this way:
<input checked="checked" type="checkbox" name="displayAge" id="id_displayAge">
BUT... since it has no value, checking/unchecking the checkbox is helpless! What should I do?
I would like to avoid typing form fields by hand!
No, there is no need for a value field. If the checkbox is checked, the browser will submit "on" as the value by default if none is supplied.
If you're not getting this value in your view, something else is wrong. Note that since you're using Django forms, you shouldn't be checking request.POST manually anyway: use form.cleaned_data.

Django Form Field Problems with Cloudinary's CloudinaryImage Class

I've got a Django form that is displaying a ClearableFileInput for a CloudinaryImage (from Cloudinary). Things are working great, except when I display the form field, I get a mangled href in the anchor element:
Currently: <cloudinary.CloudinaryImage object at 0x10b3f4ad0> <input type="checkbox" name="logo-clear" id="logo-clear_id" /> <label for="logo-clear_id">Clear</label><br />Change: <input id="id_logo" type="file" name="logo" class="span4" />
Here is the template code I am using:
<div class="fieldWrapper">
<label for="id_logo"><h3>{{ form.logo.label }}:</h3></label>
{{ form.logo|add_class:"span4" }}
<p>{{ form.logo.help_text }}</p>
</div>
The add_class part come from django-widget-tweaks. I've taken the add_class part out with no change in the output.
Here is my form definition:
class OrganizationFormTheme(forms.ModelForm):
pass
class Meta:
fields = ('logo',)
model = Organization
It looks like Django is having problems with the CloudinaryImage's url function. I suspect it is looking for a simple property rather than a function.
Any suggestions on how to handle this? Should I subclass CloudinaryImage and rewrite the url function somehow?
Indeed there was a conflict between the url function and the url property.
We've changed the function to be build_url instead of url.
In addition, you can specify transformation parameters as the url_options parameter when calling the constructor of CloudinaryImage. Then you can use the url property for getting the full Cloudinary URL.
The fix is available in the latest release of the Python library: http://pypi.python.org/pypi/cloudinary

Django ChoiceField get currently selected

I have a simple ChoiceField and want to access the 'selected' item during my template rendering.
Lets say the form gets show again (due to error in one of the fields), is there a way to do something like:
<h1> The options you selected before was # {{ MyForm.delivery_method.selected }} </h1>
(.selected() is not working..)
Thanks !
#Yuji suggested bund_choice_field.data, however that will return value which is not visible to user (used in value="backend-value"). In your situation you probably want literal value visible to user (<option>literal value</option>). I think there is no easy way to get literal value from choice field in template. So I use template filter which does that:
#register.filter(name='choiceval')
def choiceval(boundfield):
"""
Get literal value from field's choices. Empty value is returned if value is
not selected or invalid.
Important: choices values must be unicode strings.
choices=[(u'1', 'One'), (u'2', 'Two')
"""
value = boundfield.data or None
if value is None:
return u''
return dict(boundfield.field.choices).get(value, u'')
In template it will look like this:
<h1> The options you selected before was # {{ form.delivery_method|choiceval }} </h1>
UPDATE: I forgot to mention an important thing, that you will need to use unicode in choice values. This is because data returned from form is always in unicode. So dict(choices).get(value) wont work if integers where used in choices.
It would be accessed by {{ myform.delivery_method.data }}
<h1> The options you selected before was # {{ MyForm.delivery_method.data }} </h1>