Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make a choices field in django with an editable "other" option?

Tags:

python

django

(
    ('one', 'One'),
    ('two', 'Two'),
    ('other', EDITABLE_HUMAN_READABLE_CHOICE),
)

So what I would like is a choices field with some common choices that are used frequently, but still be able to have the option of filling in a custom human readable value.

Is this possible or is there some better way of doing this that I am completely missing?

like image 447
RagglesX Avatar asked Sep 01 '10 00:09

RagglesX


People also ask

How do I make a field editable in Django?

To use editable in a field you must specify either of following settings: null=True and blank=True, so that your field doesn't give required error during model save.

How do I add a choice in Django?

Django Field Choices. According to documentation Field Choices are a sequence consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) …]) to use as choices for some field. For example, consider a field semester which can have options as { 1, 2, 3, 4, 5, 6 } only.

How do I add a field in Django?

To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB.

What is field in Django?

Fields in Django are the data types to store a particular type of data. For example, to store an integer, IntegerField would be used. These fields have in-built validation for a particular data type, that is you can not store “abc” in an IntegerField. Similarly, for other fields.


2 Answers

One way to do this would be to use a custom ModelForm for admin. This form can have two fields - one that accepts a set of predefined choices and another one that accepts arbitrary values. In the clean() method you can ensure that only one of these has been selected.

If you are particular about how the UI should look - say, radio buttons that allow you to choose either a pre-defined value xor enter a custom value, then you may have to come up with your own custom field.

like image 148
Manoj Govindan Avatar answered Nov 01 '22 21:11

Manoj Govindan


I quick solution I used:

  • used standard ModelChoice Fields
  • custom Form, which added a regular Input Field for every ModelChoice Field
  • custom JQuery which showed the regular Input Field only, when the last choice is selected
  • in the View, when I got POST data I parsed the POST array and created the Models
like image 25
Andre Bossard Avatar answered Nov 01 '22 19:11

Andre Bossard