AttributeError: module has no attribute - python

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.

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

Related

AttributeError: module 'django.db.models' has no attribute 'Models'

When I'm trying to migrate a new app onto the server i get this error
AttributeError: module 'django.db.models' has no attribute 'Models'- in terminal
I'm using PyCharm. I am very fresh to Django and web development so any tips will help. Thanks!
from django.db import models
# Create your models here.
class product(models.Model):
item = models.Textfiels()
description = models.Textfields()
price = models.Textfields()
There's no such class django.db.models.TextFields but this works for me on any recent version :
from django.db import models
class product(models.Model):
item = models.TextFiel()
description = models.TextField()
price = models.TextField()
You made 2 typos : the correct name is TextField and you typed Textfields (Python is case sensitive)
I suspect you didn't setup correctly your project under PyCharm. When correctly setup, it shows warnings on misspelled names (names underlined with red dots with default setting).
There's another variation to this question and that is in the form of:
AttributeError: module 'django.contrib.auth' has no attribute 'models'
As far as I can tell this is typically caused by conflicting imports or improperly imported files. Another cause could be changes to Django's updates but I'm not sure about that as I didn't find any documentation that changed that aspect of the Django library.
Short term solution to this is as follows:
from django.contrib.auth import models
class MyClass(models.User): """ """
This will allow you to at least test your runserver command and website on a browser of your choosing.
I'm still trying to figure out any other solutions to this problem that can be a fix for individually importing the 'auth' module itself.
At the time of this writing I'm using Django 2.2.6 whereas Django 2.2.7 is out and 2.2.8 is on the way to be released.
I'm not sure if this is the solution , but when I had this problem it was because in my admin.py file I had
from django.contrib import admin
from meetings.models import Meeting, Room
admin.site.register(Meeting, Room)
But changing it to solved the issue
from django.contrib import admin
# Register your models here.
from meetings.models import Meeting, Room
admin.site.register(Meeting)
admin.site.register(Room)

Django: Key (slug)=(*) already exists

I'm pretty new to Django and python and I'd like to learn more about how to populating my Postgres database.
Here is my current model: models.py
from django.template.defaultfilters import slugify
class Skill(models.Model):
name = models.TextField()
slug = models.TextField(unique = True)
def __unicode__(self):
return "%s" % self.name
and my views: views.py
r = r.json()
try:
Skills = r['data']['skills']
except:
pass
for skill in Skills:
skill = Skill.objects.create(name=skill['name'],slug=slugify(skill['name']))
I'm getting the error:
Exception Type: IntegrityError
DETAIL: Key (slug)=(systems-engineering) already exists.
I've been reading a similar post although still haven't been able to solve my problem. objects.create() will shows an error when the object already exists in the database, but I was getting error with the code above. Could "unique = True" be causing the error? and how do you fix this?
Follow up
My problem is simpler than I thought. I was able to run psql interactive terminal and see my data populating. I wasn't able to see it on the admin site because I missed out registering the models on admin.py
When you provide unique=True, the field will be unique throughout the table. Hence, when you try to add a data which is already in DB, it will raise an error. See this official doc for more details

Why does doing Django query cause: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet?

I'm working on a Django 1.8.2 project.
This project has multiple Django applications.
Application app_a has class MyClassA as follows:
class MyClassA(models.Model):
name = models.CharField(max_length=50, null=True, blank=True)
#staticmethod
def my_static_method():
ret_val = MyClassA.objects.filter()
return "World"
Application app_b has class MyClassB as follows:
class MyClassB(models.Model):
name = models.CharField(max_length=50, null=False, blank=False)
def my_method(self, arg1=MyClassA.my_static_method()):
return "Hello"
When I run manage.py test, it works fine.
However, then I change MyClassA.my_static_method() to the following:
#staticmethod
def my_static_method():
ret_val = MyClassA.objects.filter(name=None)
return "World"
When I do that, and then run manage.py test, it fails with the following error:
File "my-virtual-env/lib/python2.7/site-packages/django/apps/registry.py", line 131, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
Why is this happening? How do I fix this?
The only change that I made is adding the filter value name=None.
In Django you must not run queries at import time. (See here for details.)
Because default argument values in Python are evaluated when the function is defined (as opposed to when it is called), your MyClassB.my_method() definition is calling MyClassA.my_static_method(), which attempts to run a query.
Why did you see an error in one version of your code and not the other? One of them is evaluating the query (i.e. trying to access the database) and one isn't, for whatever reason. It's your responsibility to make sure that nothing you do at import time tries to access the database.
If your goal is for that default argument to be evaluated on each call, the standard idiom in Python is:
def my_method(self, arg1=None):
if arg1 is None:
arg1 = MyClassA.my_static_method()
In this case you will get an error only if you make a mistake in the manager function. I tried the same and it worked for me. but I got the same error when I made an error in the filter() .like MyClassA.objects.filter(a_field_not_in_the_model=None).
I think you have to re check your original code. check if your model is ok.

AttributeError: 'module' object has no attribute 'iglob'

Strange error. I'm just trying to get the models right in my DB, but fail at the very first. Here is my glob.models:
from django.db import models
class Status(models.Model):
status_name = models.CharField(max_length=50)
status_description = models.CharField(max_length=100, blank=True, null=True)
def __str__(self):
return self.status_name
When I try to run syncd, I get:
AttributeError: 'module' object has no attribute 'iglob'
Your models are in glob.models - I assume the app name is glob. Is it possible that you may have made a typo somewhere - iglob instead of glob?
The code you pasted has no mention of the word iglob. I suggest you do a project wide search for iglob and see if it's meant to be glob.
Maybe your variable name is almost the same as the imported module name. You can try to use import some_module as name to avoid this issue.

Two self reference field in same db model mongoengine

I have a db models like following:
class Image(mongoengine.Document):
project = mongoengine.ReferenceField('Project', required=True,
reverse_delete_rule=mongoengine.CASCADE)
next = mongoengine.ReferenceField('self', required=False)
prev = mongoengine.ReferenceField('self', required=False)
name = mongoengine.StringField(unique_with='project', required=True)
created_on = mongoengine.DateTimeField(default=datetime.utcnow())
There are two fields referring back to same model.
Just to test the validity I removed one of them and then tried to save an Image object, it worked, but when both next and prev are in the dbmodel, in this case while saving an image object I am getting a error that:
ValidationError: None is not a valid ObjectId.
How to resolve this issue?
Does mongoengine does not support to have two self referring dbfields?
Any help would be really appreciated.
got the error.
next
is an inbuilt function, which should not be kept as a dbfield.
replacing it with any other variable which is not an inbuilt property will work.

Categories