I'm having some problems in changing the empty label for a form. I've read the documentation https://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.ModelChoiceField and some pages here on stackoverflow, but I still don't get it. In my models, I have a tuple of countiescounty_choices = (('county1', _('county1')),('county2', _('county2')),('county3', _('county3')))
and the modelcounty = models.CharField(max_length=30, blank=True, default='n/a',choices=county_choices,verbose_name=_('county'), help_text=_('County')) I want to be able to override the 9 '-' empty label with a string in my own choice and to be able to translate it. So I imported everything from models and tried in forms county = forms.ModelChoiceField(queryset=Users.objects.all(),empty_label=_("my_own_choice")) and it does not work. I send it the {{ form.county }} variable in my html, but after my own choice, I get a wierd string 'sdadsada dsadadas' instead of my list of counties. Can you help me with that? Do I need to put the tuple with counties within a queryset? What if I don't want to send it a queryset at all?
Create a model for the counties and syncdb. This way you can manipulate and access them with a queryset, same way you do with Users. i.e. queryset=Counties.objects.all().
Look at the ModelChoiceField documentation for more help.
Related
I need a help please.
So I wanted when I change the Internal Category (field name is categ_id) value to 500 final product,
and then the Routes field changes to :
Manufacture checked,
Make To Order checked,
Buy checked
and also the Value of Tracking field is changes as well to:
By Lots checked
How can I do that? Any suggestion ? Or my is it my question are not clear enough ?
Sorry for asking , I never done this before so yeah kind a confusing.
Here I got the picture the interface and the information about the field as well.
Routes field name
Tracking field name
Please anyone kindly to help me. I am so confused.
You could achieve this by using api onchange in Odoo 9.
#api.onchange('categ_id')
def onchange_categ_id(self):
for record in self:
# I prefer to check by id, but here I show how to check by string name in case you want it
if record.categ_id.name == '500 final product':
# because route_ids is many2many field,
# you need special commands to change the value
# here I use (6, _, ids) to set value.
# But before that, you have to get the ids of the routes you want from model stock.location.route
# (you could use search method to get the ids)
record.route_ids = [(6,0, list_of_id)]
record.tracking = 'lot'
...
You could refer to Odoo Doc to learn more about O2m and M2m commands
I am trying to add extra data to a form field in wtforms.
I have to create a text field which has an associated unit with it (eg - meter/sec). How do I add the meter/sec string to the form field?
Is there any way to pass a dictionary or something to add data to the field that i can access in the template?
There is a not very well known parameter, description= to the field constructor. Though it purports to be for help text, the framework itself doesn't care what you put in there (and indeed doesn't use it anywhere at all, other than passing it along.)
So you could do, for example:
class PhysicsForm(Form):
speed = TextField('Speed', description={'unit': 'meters/sec'})
distance = TextField('Distance', description={'unit': 'kilometers'})
Then you could use it in a jinja-style template something like:
{{ form.speed }} <label>{{ form.speed.description.unit }}</label>
footnote There was no real reason for using a dictionary as the value of description - it was merely to illustrate that you can put nearly any value in there, including containers which can hold many values.
I am trying to display ValuesQuerySet list to drop down list in django template page. I jus to filter special characters while displaying in drop down. I tried autoescape syntax but it doesn't work. Is anyother way to do this.
in views.py:
email_accounts = EmailAccount.objects.filter(user__user=self.request.user).values()
form.fields['account'].queryset = email_accounts.values_list('a_email')
Here the value should like [{'a_email': u'xx#gmail.com'}, {'a_email': u'yy#gmail.com'}, {'a_email': u'zzz#gmail.com'}].
In template page
{{ form.account }}
So it displayed like below in drop down list
(u'xx#gmail.com')
(u'yy#gmail.com')
(u'zz#gmail.com')
I need to remove (u') those special chars when displaying in to drop down list. How to do that? any one suggest me.
You shouldn't be using a ValuesQueryset at all here. The queryset parameter for a ModelChoiceField expects, not surprisingly, a standard queryset.
email_accounts = EmailAccount.objects.filter(user__user=self.request.user)
form.fields['account'].queryset = email_accounts
I have a form select box that has values corresponding to objects. The user selects an input and the form submits. I then want to take that value and retrieve the object that has an ID equivalent to the selected form value. However, when I try to do so, I'm getting an error like so:
int() argument must be a string or a number, not 'Cars'
Example:
if form.is_valid():
car = Car.objects.get(id=form.cleaned_data['id'])
I'm guessing the problem is that the returned value is a string and NOT an integer. In PHP this is SIMPLE. How do I typecast or use the returned form value to get an associated object?
Seems as though Django is not returning the value of the form element, but instead the user visible option name...
Form Class:
class CarForm(forms.ModelForm):
class Meta:
model = Car
Html Form:
<form action="">
<select name="id">
{% for car in cars %}
<option value="{{car.id}}">{{car.title}}</option>
{% endfor %}
</select>
</form>
The id field has to be an integer, or a string that can be converted to an integer.
Simple as that!
Somehow, your form.cleaned_data['id'] is returning a model called Cars
Ensure it returns a number if you want to pass it into get(id=
You can use ModelChoiceField instead of generating the select using HTML
in forms.py:
class CarSelectForm(forms.Form):
car = forms.ModelChoiceField(queryset=Car.objects.all(), empty_label=None)
in view.py:
if form.is_valid():
car = form.cleaned_data['car']
This is maybe a bad, but I think working answer. If anyone has a real solution, please post because I still need it.
(I'm using a modelformset, but just a modelform may work the same)
For me, the {{ form.id }} works on the page (puts the id) and comes back correctly in the POST data. However, somewhere along the line it gets converted (as Yuji said in his post) into the model object represented by that id and that is what is in cleaned_data.
In short, change
car = Car.objects.get(id=form.cleaned_data['id'])
to
car = form.cleaned_data['id']
I think it just looks like a string just because when you print or debug, it's using your str or unicode representation.
Repeat: This is almost certainly a side effect or bad way to do things. If I figure out a better way, I'll post it.
I have the same issue... so I tried the following:
ts_1 = form.cleaned_data['lista_trabajos']
ts_2 = request.POST['lista_trabajos']
print(ts_1) # this returns what user sees, ex: 1 - folders
print(ts_2) # this returns value from that option, in my case: 1
Unfortunately, I have been reading that by using raw POST data is not recommended. At the moment, I cannot figure out how to validate and get the raw POST data by using something similar to "clean_data".
You can read about this in: https://books.google.com.ar/books?id=8sU7DwAAQBAJ&pg=PA229&lpg=PA229&dq=form+cleaned_data+to+get+raw+post+data&source=bl&ots=RN9WKRaGJs&sig=QpSoPdI9YSHSNk0zAQIO8phSbOw&hl=es&sa=X&ved=0ahUKEwiBouHattnaAhULFZAKHUKmA4QQ6AEIRzAD#v=onepage&q=form%20cleaned_data%20to%20get%20raw%20post%20data&f=false
I have a Django Model with a text field. I would like to modify the content of the text field before it's presented to the user in Django Admin.
I was expecting to see signal equivalent of post_load but it doesn't seem to exist.
To be more specific:
I have a text field that takes user input. In this text field there is a read more separator. Text before the separator is going to go into introtext field, everything after goes into fulltext field.
At the same time, I only want to show the user 1 text field when they're editing the article.
My plan was to on_load read the data from introtext and fulltext field and combine them into fulltext textarea. On pre_save, I would split the text using the read more separator and store intro in introtext and remainder in fulltext.
So, before the form is displayed, I need to populate the fulltext field with
introtext + '<!--readmore-->' + fulltext
and I need to be able to do this for existing items.
Have a look into Providing your own form for the admin pages.
Once you have your own form, you can use the default param in the form to provide the initial value you want. See the docs on the Initial param for the form field. As this link will show you, it is possible to use a callable or a constant as your initial value.
There is no post_load because there is no load function.
Loading of the instance is done in init function, therefore the right answer is to use post_init signal.