Search code examples
djangomany-to-manyrelation

Django How to create M2M relation with User table


I would like to create M2M relation with User table but it does not work.

This is my code:

from django.contrib.auth.models import User
# Create your models here.

class projects(models.Model):

    project_name = models.CharField(verbose_name=" ", max_length=250, blank=True, null=True)
    description = models.CharField(verbose_name=" ", max_length=500, blank=True, null=True)
    create_date = models.DateField(verbose_name='', auto_now_add=True, null=True, blank=True,
        help_text="")
    start_date = models.DateField(verbose_name='', null=True, blank=True,
        help_text="")
    end_date   = models.DateField(verbose_name='', null=True, blank=True,help_text="")
    url = models.CharField(max_length=50)
    user = models.ManyToManyField('User')

    def __unicode__(self):
        return u"%s" % (self.project_name)

Project table should have M2M with User table, but it causes the error:

django.core.management.base.CommandError: One or more models did not validate:
projects.projects: 'user' has an m2m relation with model User, which has either not been installed or is abstract.

What should I have to fix for this case?


Solution

  • You should add auth app name to the M2M field definition:

    user = models.ManyToManyField('auth.User')
    

    Or use the User model as is, without putting it into quotes:

    user = models.ManyToManyField(User)