I am building a new django application and for some reason I am getting an error while i am trying access the models from the models.py file from the forms.py file.
Here is the error:
File "/Users/omarjandali/Desktop/MySplit/mysplit/general/forms.py", line 13, in <module>
from models import *
ModuleNotFoundError: No module named 'models'
Yet I have the general app added to the installed settings. and I have all the models saved. Why is it saying that the module is not there... I am going blank. I know it is a simple answer but for some reason I cant figure it out.
here is the forms.py file:
# all model imports related to this project
from models import *
class LoginForm(forms.Form):
username = forms.CharField(max_length=20)
password = forms.CharField(max_length=20, widget=forms.PasswordInput)
here is the models.py file:
from django.db import models
from django.contrib.auth.models import User, UserManager
from localflavor.us.models import USStateField, USZipCodeField
# the following is the users profile model
class Profile(models.Model):
# users basic info
user = models.ForeignKey(User, on_delete=models.CASCADE)
f_name = models.CharField(max_length=25, default='first')
l_name = models.CharField(max_length=25, default='last')
bio = models.CharField(max_length=220, default='bio')
# users location
street = models.CharField(max_length=200, default='street address')
city = models.CharField(max_length=100, default='city')
state = USStateField(default='CA')
zip_code = USZipCodeField(default=12345)
# users other profile info
phone = models.IntegerField(default="000-ooo-oooo")
dob = models.DateField(default='1950-01-01')
gender = models.CharField(max_length=5, default='Other')
# lob = industry/occupation
lob = models.CharField(max_length=40, default='occupation')
# dba = Company Name
dba = models.CharField(max_length=40, default='comapny')
account_type = models.CharField(max_length=20, default='INDIVIDUAL')
synapse_id = models.CharField(max_length=200, default='123456789')
created = models.DateTimeField(auto_now_add=True)
from .models import *
you need to provide the . for the path for same directory
also you can give absolute path
from app_name.models import *
from <app_name>.models import <class_name>
This will fix the problem. In your case, app_name is "mysplit" most probably
So, you need to import like this :
from mysplit import *
"*" because you are importing everything inside the models.py file
I hope this will resolve your issue
Related
I don't have the advertisement module displayed in the django admin panel. Here is the model code
from django.db import models
class Advertisement(models.Model):
title = models.CharField(max_length=1000, db_index=True)
description = models.CharField(max_length=1000, default='', verbose_name='description')
creates_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
price = models.FloatField(default=0, verbose_name="price")
views_count = models.IntegerField(default=1, verbose_name="views count")
status = models.ForeignKey('AdvertisementStatus', default=None, null=True, on_delete=models.CASCADE,
related_name='advertisements')
def __str__(self):
return self.title
class Meta:
db_table = 'advertisements'
ordering = ['title']
class AdvertisementStatus(models.Model):
name = models.CharField(max_length=100)
admin.py /
from django.contrib import admin
from .models import Advertisement
admin.site.register(Advertisement)
I was just taking a free course from YouTube. This was not the case in my other projects. Here I registered the application got the name in INSTALLED_APPS. Then I performed the creation of migrations and the migrations themselves. Then I tried to use the solution to the problem here , nothing helped. I didn't find a solution in Google search either.
127.0.0.1:8000/admin/
console
admins.py
The name of the file is admin.py not admins.py. Yes, that is a bit confusing since most module names in Django are plural. The rationale is probably that you define a (single) admin for the models defined.
Alternatively, you can probably force Django to import this with the AppConfig:
# app_name/apps.py
from django.apps import AppConfig
class AppConfig(AppConfig):
def ready(self):
# if admin definitions are not defined in admin.py
import app_name.admins # noqa
Here is my models.py file:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class CategoryList(models.Model):
Category = models.CharField(max_length=200)
Cat_Img = models.ImageField(upload_to='cat_media')
Active = models.BooleanField(default=True)
class ImgDetails(models.Model):
Img = models.ImageField(upload_to='media')
Category = models.ForeignKey(CategoryList, default=1, on_delete=models.SET_DEFAULT, null=False)
keywords = models.CharField(max_length=255)
UserDetail = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
Valid = models.BooleanField(default=False)
UploadDate = models.DateTimeField(auto_now_add=True)
I'm trying to add a foreign-key constraint on ImgDetails with CategoryList. It is throwing error
from cam_project.cam_app.models import CategoryList
ModuleNotFoundError: No module named 'cam_project.cam_app'
I tried importing from cam_project.cam_app.models import CategoryList but still no progress. Any suggestions would be appreciated.
If your models.py is in the cam_app you can just use:
from .models import CategoryList
or if you are importing another app's models.py, you should specify the app name as well:
from .app.models import Model
Be sure the directory that contains cam_project must be in the PYTHONPATH.
You can check it inspecting sys.path.
To add it you can:
export PYTHONPATH=<YOUR_DIR>:$PYTHONPATH
I don't think the error is in models.py. Your foreign-key constraint is working fine. It seems you are importing CategoryList in some other file(my best guess views.py) In django absolute import are relative to your manage.py. So I think you import should be
from cam_app.models import CategoryList
I somehow can not import my models from another app. I already looked it up and tried but does not work.
events/models.py
class Registration(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
team = models.CharField(max_length=50, blank=True)
date_created = models.DateTimeField(auto_now_add=True)
def save(self, *args, **kwargs):
payment = Payment.objects.create(registration=self)
super().save(*args, **kwargs)
When I run python manage.py makemigrations I get this.
Error
File "C:\Users\Rubber\ems\events\models.py", line 5, in <module>
from payments.models import Payment
File "C:\Users\Rubber\ems\payments\models.py", line 6, in <module>
from events.models import Registration
ImportError: cannot import name 'Registration'
payments/models.py
import uuid
from django.db import models
from django.utils import timezone
from events.models import Registration # THIS WONT WORK
def _create_uuid():
return uuid.uuid1()
def _get_uuid():
return _create_uuid()
class Payment(models.Model):
uuid = models.CharField(max_length=1, default=_get_uuid)
paid = models.BooleanField(default=False)
registration = models.ForeignKey(Registration, on_delete=models.CASCADE)
What am I doing wrong?
You have a circular import. In this case, you can avoid it by removing the Registration import and using the string instead:
class Payment(models.Model):
registration = models.ForeignKey('events.Registration', on_delete=models.CASCADE)
Another option would be to move the Payment.objects.create() code into a signal. Note that your current save() method creates a Payment every time the registration is saved, which might not be what you want.
I have these models below
# user profile models file
from ad.models import FavoriteAd
class UserProfile(models.Model):
def get_user_favorite_ad(self):
return FavoriteAd.objects.filter(fav_user=self)
# ad models file
from user_profile.models import UserProfile
class FavoriteAd(models.Model):
fav_user = models.ForeignKey(UserProfile, blank=False, on_delete=models.CASCADE)
I have tried using these but it give me the NameError UserProfile not found
# ad models files
class FavoriteAd(models.Model):
fav_user = models.ForeignKey('user_profile.UserProfile', blank=False, on_delete=models.CASCADE)
Also tried these as well still got error that model are not ready
# ad models files
from django.apps import apps
UserProfile = apps.get_model('user_profile', 'UserProfile')
class FavoriteAd(models.Model):
fav_user = models.ForeignKey(UserProfile, blank=False, on_delete=models.CASCADE)
You are using FavoriteAd inside get_user_favorite_ad method of
UserProfile model
Thats the reason you are unable to import it in FavoriteAd and this is causing circular import.
For fetching favorite ads of that user, Use favoritead_set to get related objects
# remove that import as well
# from ad.models import FavoriteAd
class UserProfile(models.Model):
def get_user_favorite_ad(self):
return self.favoritead_set.all()
When I try to migrate my code I get this error.
Here are my code and classes:
from django.db import models
from core.models import Event
class TicketType(models.Model):
name = models.CharField(max_length=45)
price = models.DecimalField(max_length=2, decimal_places=2, max_digits=2)
type = models.CharField(max_length=45)
amount = models.IntegerField()
event = models.ForeignKey(Event)
class Meta:
app_label = "core"
import datetime
from django.core.serializers import json
from django.db import models
from core.models import User
class Event(models.Model):
page_attribute = models.TextField()
name = models.TextField(max_length=128 , default="New Event")
description = models.TextField(default="")
type = models.TextField(max_length=16)
age_limit = models.IntegerField(default=0)
end_date = models.DateTimeField(default=datetime.datetime.now())
start_date = models.DateTimeField(default=datetime.datetime.now())
is_active = models.BooleanField(default=False)
user = models.ForeignKey(User)
ticket_type=models.ForeignKey('core.models.ticket_type.TicketType')
class Meta:
app_label = "core"
Here is the error I get:
CommandError: One or more models did not validate:
core.event: 'ticket_type' has a relation with model core.models.ticket_type.TicketType,
which has either not been installed or is abstract.
You're unnecessarily confusing yourself by having these in separate files within the same app.
But your issue is caused by the way you're referenced the target model. You don't use the full module path to the model: you just use 'app_name.ModelName'. So in your case it should be:
ticket_type=models.ForeignKey('core.TicketType')
Another issue can be when using multiple models in separate files missing statement like:
class Meta:
app_label = 'core_backend'
You can also get this error if there a bug in your models file that prevents it from loading properly. For example, in models.py
from third_party_module_i_havent_installed import some_method
I hit this error when I didn't put a third-party app in my INSTALLED_APPS setting yet.