Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Foreign Key to_field

I have 2 models CustomUser and Magazine with random/unique slug fields. Now I want to create a third model (Article) with foreign keys to the slug field:

class CustomUser(AbstractBaseUser):
    slug = RandomSlugField(length=6, unique=True)
    ...

class Magazine(models.Model):
    slug = RandomSlugField(length=6, unique=True)
    name = models.CharField()

class Article(models.Model):
    magazine = models.ForeignKey(Magazine, to_field='slug')
    author = models.ForeignKey(settings.AUTH_USER_MODEL, to_field='slug')

But when I migrate the database to create the Article model, I get the following error:

django.core.exceptions.FieldDoesNotExist: CustomUser has no field named 'slug'

But CustomUser obviously has a field named 'slug'.

And for the Magazine model I don't get this error. Has anyone an idea what is going wrong?

I use this package for the slug field: https://github.com/mkrjhnsn/django-randomslugfield

EDIT: Here is the full CustomUser model:

class CustomUser(AbstractBaseUser, PermissionsMixin):
    slug = RandomSlugField(length=6, exclude_upper=True)
    username = models.CharField(
        _('username'), max_length=30,
        help_text=_('Required. 30 characters or fewer.'
                'Letters, digits and '
                '@/./+/-/_ only.'),
        validators=[
            validators.RegexValidator(r'^[\w.@+-]+$',
                                  _('Enter a valid username.'), 'invalid')
        ])
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)

    # email is our unique field for authentication
    email = models.EmailField(_('email address'), unique=True)

    is_staff = models.BooleanField(
        _('staff status'), default=False,
        help_text=_('Designates whether the user can log '
                    'into this admin site.')
        )
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_('Designates whether this user should be treated as '
                    'active. Unselect this instead of deleting accounts.')
        )
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    objects = UserManager()

    profile = models.OneToOneField('UserProfile', blank=True, null=True,
                               related_name='user_profile')

    image = models.ImageField(default='images/noimage.jpg',
                          upload_to=settings.PROFILE_IMAGE_PATH,
                          max_length=255)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']
like image 926
ilse2005 Avatar asked Jul 10 '15 23:07

ilse2005


1 Answers

delete the database, all migrations except init and try it

like image 58
Majety Saiabhinesh Avatar answered Oct 14 '22 05:10

Majety Saiabhinesh