Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django many-to-many show human-readable in form

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 'python' string instead 'Python', also, when I look the rendered html coded the multiselect options look like:

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

instead of

<option value='python'>Python</option> 
like image 676
adrian oviedo Avatar asked Apr 20 '17 14:04

adrian oviedo


People also ask

How do I create a many-to-many relationship in Django?

To define a many-to-many relationship, use ManyToManyField . What follows are examples of operations that can be performed using the Python API facilities. You can't associate it with a Publication until it's been saved: >>> a1.

How does many-to-many field work in Django?

A ManyToMany field is used when a model needs to reference multiple instances of another model. Use cases include: A user needs to assign multiple categories to a blog post. A user wants to add multiple blog posts to a publication.

How fetch data from many-to-many field in Django?

A ManyToManyField in Django is a field that allows multiple objects to be stored. This is useful and applicable for things such as shopping carts, where a user can buy multiple products. To add an item to a ManyToManyField, we can use the add() function.

What is through in Django models?

The through attribute/field is the way you customize the intermediary table, the one that Django creates itself, that one is what the through field is changing.


1 Answers

If you want to use the value 'Python' in the model's __str__, method, then you should use self.get_name_display() instead of 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 can't easily change many-to-many field to use value='python' instead of value='1' (the primary key). That's just the way many-to-many fields work.

like image 56
Alasdair Avatar answered Oct 19 '22 17:10

Alasdair