98👍
This may help:
reason = form.cleaned_data['reason']
reason = dict(form.fields['reason'].choices)[reason]
171👍
See the docs on Model.get_FOO_display(). So, should be something like :
ContactForm.get_reason_display()
In a template, use like this:
{{ OBJNAME.get_FIELDNAME_display }}
- [Django]-Retrieving parameters from a URL
- [Django]-What is the best location to put templates in django project?
- [Django]-Django: Catching Integrity Error and showing a customized message using template
29👍
This the easiest way to do this: Model instance reference: Model.get_FOO_display()
You can use this function which will return the display name: ObjectName.get_FieldName_display()
Replace ObjectName
with your class name and FieldName
with the field of which you need to fetch the display name of.
- [Django]-How to handle request.GET with multiple variables for the same parameter in Django
- [Django]-Testing email sending in Django
- [Django]-Unittest Django: Mock external API, what is proper way?
- [Django]-Django.core.exceptions.ImproperlyConfigured: Error loading psycopg module: No module named psycopg
- [Django]-Do django db_index migrations run concurrently?
- [Django]-Django-taggit – how do I display the tags related to each record
4👍
Here is a way I came up with. There may be an easier way. I tested it using python manage.py shell
:
>>> cf = ContactForm({'reason': 'feature'})
>>> cf.is_valid()
True
>>> cf.fields['reason'].choices
[('feature', 'A feature')]
>>> for val in cf.fields['reason'].choices:
... if val[0] == cf.cleaned_data['reason']:
... print val[1]
... break
...
A feature
Note: This probably isn’t very Pythonic, but it demonstrates where the data you need can be found.
- [Django]-Allowing RabbitMQ-Server Connections
- [Django]-Django Admin Form for Many to many relationship
- [Django]-Is there a naming convention for Django apps
3👍
You can have your form like this:
#forms.py
CHOICES = [('feature', "A feature"), ("order", "An order")]
class ContactForm(forms.Form):
reason = forms.ChoiceField(choices=CHOICES,
widget=forms.RadioSelect)
Then this would give you what you want:
reason = dict(CHOICES)[form.cleaned_data["reason"]]
- [Django]-Update to Django 1.8 – AttributeError: django.test.TestCase has no attribute 'cls_atomics'
- [Django]-How do you dynamically hide form fields in Django?
- [Django]-Django The 'image' attribute has no file associated with it
3👍
OK. I know this is very old post, but reading it helped me a lot. And I think I have something to add.
The crux of the matter here is that the the model method.
ObjectName.get_FieldName_display()
does not work for forms.
If you have a form, that is not based on a model and that form has a choice field, how do you get the display value of a given choice.
Here is some code that might help you.
You can use this code to get the display value of a choice field from a posted form.
display_of_choice = dict(dateform.fields['fieldnane'].choices)[int(request.POST.get('fieldname'))]
the ‘int’ is there on the basis the choice selection was a integer. If the choice index was a string then you just remove the int(…)
- [Django]-How do I install psycopg2 for Python 3.x?
- [Django]-Django "login() takes exactly 1 argument (2 given)" error
- [Django]-Django model constraint for related objects
1👍
Im using @Andrés Torres Marroquín way, and I want share my implementation.
GOOD_CATEGORY_CHOICES = (
('paper', 'this is paper'),
('glass', 'this is glass'),
...
)
class Good(models.Model):
...
good_category = models.CharField(max_length=255, null=True, blank=False)
....
class GoodForm(ModelForm):
class Meta:
model = Good
...
good_category = forms.ChoiceField(required=True, choices=GOOD_CATEGORY_CHOICES)
...
def clean_good_category(self):
value = self.cleaned_data.get('good_category')
return dict(self.fields['good_category'].choices)[value]
And the result is this is paper
instead of paper
.
Hope this help
- [Django]-Django – getting Error "Reverse for 'detail' with no arguments not found. 1 pattern(s) tried:" when using {% url "music:fav" %}
- [Django]-Django 1.3.1 compilemessages. Error: sh: msgfmt: command not found
- [Django]-How to disable Django's CSRF validation?
1👍
confirm that Ardi’s and Paul’s response are best for forms and not models. Generalizing Ardi’s to any parameter:
class AnyForm(forms.Form):
def get_field_name_display(self, field_name):
return dict(self.fields[field_name].choices[self.cleaned_data[field_name]]
Or put this method in a separate class, and sub-class it in your form
class ChoiceFieldDisplayMixin:
def get_field_name_display(self, field_name):
return dict(self.fields[field_name].choices[self.cleaned_data[field_name]]
class AnyCustomForm(forms.Form, ChoiceFieldDisplayMixin):
choice_field_form = forms.ChoiceField(choices=[...])
Now call the same method for any Choice Field:
form_instance = AnyCustomForm()
form_instance.is_valid()
form_instance.get_field_name_display('choice_field_form')
- [Django]-Do I need Nginx with Gunicorn if I am not serving any static content?
- [Django]-Unresolved attribute reference 'objects' for class '' in PyCharm
- [Django]-How can I build multiple submit buttons django form?
0👍
I think maybe @webjunkie is right.
If you’re reading from the form from a POST then you would do
def contact_view(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
contact = form.save()
contact.reason = form.cleaned_data['reason']
contact.save()
- [Django]-Running a specific test case in Django when your app has a tests directory
- [Django]-Uninstall Django completely
- [Django]-What's the idiomatic Python equivalent to Django's 'regroup' template tag?