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!
Related
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}}
For some reason I use a custom HTML-code for displaying the form. My form's input get the initial value (date), and shows the same form after submittion.
But after submit, input has no previously selected value (just empty).
I use {{ Form.Fileld.value|date:"Y-m-d" }} in the temlate to get initial and submitted values.
It seems that initial and submitted values are in different formats: "datetime" for initial values and "string" after submit.
Here is my simple test:
Form
class ShowStartEndDateForm(forms.Form):
start_date = forms.DateField(initial=date.today().replace(day=1),
label="Start",
widget=forms.DateInput(format='%Y-%m-%d'),
input_formats=['%Y-%m-%d'])
...
View
if request.method == 'POST':
form_date = ShowStartEndDateForm(request.POST)
if form_date.is_valid():
form_was_submitted = True
cd = form_date.cleaned_data
operator = cd['operators']
days=[]
for day in range(0,(cd['end_date']-cd['start_date']).days+1):
days.append(cd['start_date']+relativedelta(days=+day))
else:
form_date = ShowStartEndDateForm()
return render_to_response('epay.html', locals(),
context_instance=RequestContext(request))
Template
<!- HTML FORM here
|classname is my custom template filter.
-->
Date1: {{ form_date.start_date.value|date:"Y-m-d" }} \
({{ form_date.start_date.value|classname }})
Date2: {{ form_date.start_date.value }}
First call in browser:
Date1: 2013-10-01 (date)
Date2: 1 October 2013
After form submit:
Date1: (unicode)
Date2: 2013-10-01
What am I doing wrong? What is the proper way to access form's field initial and submitted values?
Thnak you.
You're question is a bit confusing (you should add some more of your actual code), but I know from experience that when mixing between formats, its a good convention to just do it all in one place. So instead of specifying the format on the client side like you do, specify it all on the form itself and then everything would (should) be in-sync.
class ShowStartEndDateForm(forms.Form):
start_date = forms.DateField(initial=date.today().replace(day=1),
label="Start",
widget=DateInput(format='%Y-%m-%d'),
input_formats=['%Y-%m-%d'])
i.e. you tell the the DateInput widget what form to take and you tell input_formats (for the field itself) what formats to expect (you can add more than one). Also, if you are using some sort of datepicker you of course need to make sure it is also using the right format.
Edit
I replicated this and everything was fine:
In [1]: from test.forms import *
In [2]: f = ShowStartEndDateForm()
In [3]: print f
<tr>
<th><label for="id_start_date">Start:</label></th>
<td><input id="id_start_date" name="start_date" type="text" value="2013-10-01" /></td>
</tr>
(of course I changed the indentation here so you could see it more clearly)
I am using for loop in my template and for different id of each record i am using arrays
{% for item in product %}
<div class="register_div">
<p><label for="id[{{ item.id }}]">{{ item.Name }} </label> <input type="text" name="custom[{{item.id}}]"/></p>
</div>
{% endfor %}
Now when in my views i want to save this data to my database.But firstly i checked that whether my array return something or not.So i just try print that as.
q = upload_form.data['custom[]']
or
q = upload_form.data['custom']
but it gives me this error
"Key 'custom[]' **OR** key custom not found in <QueryDict: {u'custom[2]': [u's'], u'custom[1]': [u'a'], u'price': [u''], u'title': [u''], u'customatt': [u'', u''], u'csrfmiddlewaretoken': [u'up4Ipd5L13Efk14MI3ia2FRYScMwMJLz']}>"
but if i print this
q = upload_form.data['custom[1]']
then it display the value of array 1.
so please suggest me a better way to do this how i can display all values inside my array in views.py
As upload_form.data is a dictionary, the key 'custom[]' simply doesn't exist. Try something like:
custom_values = {}
for key, value in in upload_form.data.items():
if key.startswith('custom'):
custom_values[key]=value
The dictionary custom_values holds now all your 'custom' form values.
This is not an answer to question, but:
You are not posting an array, but different inputs whose name looks like accessing array. e.g. you are posting different input variables named custom[1], custom[2] etc. But custom is not an array, you will have to access inputs as custom[1] etc.
I'm not sure you want this or not!
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
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>