Django many-to-many show human-readable forms

I have these models:

CURSES=(('python','Python'),('django','Django'),...)
class Asig(models.Model):
    ...
    name = models.CharField(max_length=100, choices=CURSES)

class Profesor(AbstractUser):
    ...
    asigs = models.ManyToManyField(Asig)

Then, when I render the form using ModelForm, the many-to-many field shows itself with the string 'python' instead of 'Python', also when I look at the rendered html code, the multiselect parameters look like this:

<option value='1'>python</option>

instead

<option value='python'>Python</option> 
+4
source share
1 answer

If you want to use the "Python" value in the model __str__method, then you should use self.get_name_display()instead self.name:

class Asig(models.Model):
    ...
    name = models.CharField(max_length=100, choices=CURSES)

    def __str__(self):  
        # use @python_2_unicode_compatible or define __unicode__ if using Python 2
        return self.get_name_display()

You cannot easily change the many-to-many field to use value='python'instead of value='1'(primary key). It works the way many-to-many work.

+3

Source: https://habr.com/ru/post/1675263/


All Articles