Artem
Artem

Reputation: 35

AttributeError: module has no attribute

When I try to change function name "random_string" which is used in auth_code (variable in model class) to any other name it shows me the error in the command line: AttributeError: module 'users_data.models' has no attribute 'random_string'

from django.db import models
from django.utils.timezone import now
import random
from django.core.exceptions import ValidationError


def random_string():
    return int(random.randint(000000, 999999))


def validate_phone_number(phone):
    if len(phone) < 7:
        raise ValidationError('Phone number can not be less than 7 digits')


class Users(models.Model):
    phone = models.CharField(verbose_name='Phone', max_length=20, validators= 
                            [validate_phone_number])
    auth_code = models.IntegerField(verbose_name='Code', 
                                    default=random_string)
    get_in_date = models.DateTimeField(default=now, blank=False, 
                                       editable=False)

I have seen many posts which cover my problem but I didn't find any useful. I would appreciate any help.

Upvotes: 1

Views: 1941

Answers (1)

Jordan Kowal
Jordan Kowal

Reputation: 1594

The issue lies within your migrations files, as shown in this issue. Basically, when you generated your previous migration files, it was written that the default was value for a field was random_string.

Now, if you change that function name, your current code will work, but because your already-generated migration files use this function, they will raise an error as they cannot find that function anymore.

I dont know if simply updating the files to replace the name within them would be enough. Other solutions would be to reset the migrations (though it might come as a cost).

The link I've provided offers a script to fix that, but I haven't tested it myself

Upvotes: 1

Related Questions