Django book chapter 6: unable to import Book model - python

I am learning Django going through the online book, and am presently stuck at Chapter 6. In the Adding Your Models to the Admin Site section the reader is required to create a file named admin.py, within the books app, with this content:
from django.contrib import admin
from mysite.books.models import Publisher, Author, Book
admin.site.register(Publisher)
admin.site.register(Author)
admin.site.register(Book)
This is supposed to make these models available for editing at the admin site, but what I get is the following:
ImportError at /admin/ No module named books.models
In the Python command line I get a similar error:
>>> from mysite.books.models import Book
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named mysite.books.models
These are the contents of the models.py file:
from django.db import models
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()
def __unicode__(self):
return self.name
class Meta:
ordering = ['name']
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()
def __unicode__(self):
return self.title
I have strictly followed the instructions in the book to this point, thus I should have an exact copy of the code used. The file structure was created automatically by Django:
books
__init__.py
admin.py
models.py
tests.py
views.py
mysite
templates
__init__.py
settings.py
urls.py
views.py
wsgi.py
manage.py
What would be the correct way of importing the models file in the admin module?

This is pretty old book and some things are deprecated in current version of Django.
Try this import:
from books.models import Publisher, Author, Book
instead of:
from mysite.books.models import Publisher, Author, Book

Related

The model is not displayed in the django admin panel

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

ModuleNotFoundError: No module named 'rango'

I am trying to use Python shell to import a model, getting error:
ModuleNotFoundError: No module named 'rango'
I've also noticed in my urls.py i am getting 'Unresolved Import:
views'
I think my project structure might be the cause of both errors, I
used eclipse to create django project for the first time.
I have added rango app in the installed apps in setting, just as: 'rango',
HERE IS THE SCREEN FOR PROJECT STRUCTURE AND ERROR: https://imgur.com/a/WlfNzEN
views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
context_dict = {'boldmessage': "Crunchy, creamy, cookie, candy, cupcake!" }
return render(request, 'rango/index.html', context=context_dict)
models.py
from django.db import models
class Category(models.Model):
# Unique TRUE attr means the name must be unique - can be used as a primary key too!
name = models.CharField(max_length=128, unique=True)
def __str__(self):
return models.Model.__str__(self)
class Page(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
title = models.CharField(max_length=128)
url = models.URLField()
views = models.IntegerField(default=0)
def __str__(self):
return models.Model.__str__(self)
class user_session(models.Model):
userNAME = models.CharField(max_length=120, unique=True)
addToCarts = models.IntegerField(default=0)
def __str__(self):
# __unicode__ on Python 2
return self.headlin
if your urls.py are in the same folder with views.py you can try it
from . import views
but if the urls.py are in the Tango folder try
from ..rango import views
also can you try to rename you first Tango folder, here can came error
Tango/
Tango/
...
rongo/
Tango/
...
try to rename first Tango folder to be something like this
Projects/
Tango/
...
rongo/
Tango/
...

I am getting a module error in my django project

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

Abstract model error

I have problem about the abstract model in chapter "Adding Easy Admin Emails, Helpers, Sitemaps, and More" (the hello web app intermediate book)
here is my models.py code:
from django.contrib.auth.models import User
from django.db import models
class Timestamp(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Thing(Timestamp):
name = models.CharField(max_length=225)
class Thing(models.Model):
name = models.CharField(max_length=225)
description = models.TextField()
slug = models.SlugField(unique=True)
user = models.OneToOneField(User, blank=True, null=True)
def get_absolute_url(self):
return "/things/%s/" % self.slug
class Social(models.Model):
SOCIAL_TYPES = (
('twitter','Twitter'),
('facebook','Facebook'),
('pinterest','Pinterest'),
('instagram','Instagram'),
)
network = models.CharField(max_length=255, choices=SOCIAL_TYPES)
username = models.CharField(max_length=255)
thing = models.ForeignKey(Thing,related_name="social_accounts")
class Meta:
verbose_name_plural = "Social media links"
when I run
$python manage.py makemigrations
$python manage.py migrate
the error message shows:
/helloApp/venv/lib/python2.7/site-packages/django/db/models/base.py:309: RuntimeWarning: Model 'collection.thing' was already registered. Reloading models is not advised as it can lead to inconsistencies, most notably with related models.
new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
No changes detected
that does not show like in the book :
You are trying to add a non-nullable field 'added' to thing without a defaul,,,,,,,
any answer would very greatful thank you!

error in django called module not found

I made one project called mysite and I created using startapp called books.I made the admin site and it worked successfully. But when I tried to add models to my admin site the error occurred mentioning these things.
ImportError at /admin/
No module named books.models
Actually I created admin.py in books folder and then I wrote the following code.
from django.contrib import admin
from mysite.books.models import Publisher, Author, Book
admin.site.register(Publisher)
admin.site.register(Author)
admin.site.register(Book)
models.py:
from django.db import models
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()
def __unicode__(self):
return self.name
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()
def __unicode__(self):
return self.title
So, how to solve this problem?
try this instead..
from django.contrib import admin
from models import Publisher, Author, Book
admin.site.register(Publisher)
admin.site.register(Author)
admin.site.register(Book)
I'd try
from books.models import Publisher, Author, Book
...
if books is the name of your app

Categories