ModuleNotFoundError: No module named 'musiclibrary.song' - python

There is an issue while importing model 'Artist' of my django app in views.py.
from musiclibrary.song.models import Artist
when I runserver it gives ModuleNotFoundError.
from django.shortcuts import render
from django.http import HttpResponse
from musiclibrary.song.models import Artist
def hello_world(request):
return HttpResponse("Hello World!")
def home(request):
return render(request, "home.html")
def artist(request):
artist_list = Artist.objects.all(). //// I have to make this line of code work
context = {'artist_list': artist_list}
return render(request, 'artist.html', context)
Models code:
from django.db import models
class Artist(models.Model):
name = models.CharField(max_length=250)
country = models.CharField(max_length=150)
birth_year = models.IntegerField()
genre = models.CharField(max_length=150)
class Song(models.Model):
Title = models.CharField(max_length=250)
release_date = models.IntegerField()
length = models.DateField()
artist = models.ForeignKey('Artist', on_delete=models.CASCADE)
Error log:
File "/Users/m.zcomputer/PycharmProjects/myFirstApp/musiclibrary/musiclibrary/views.py", line 4, in <module>
from musiclibrary.song.models import Artist
ModuleNotFoundError: No module named 'musiclibrary.song'
This is how my project is organized

You can go to:
PyCharm > Preferences > Project > Project Structure
Mark this module as Source
Like this
Apply > Ok
And try again.

you got that error bacause you don't import correctly.
from song.models import Artist
more :
when you want to import anything from your models.py or etc , you must import them from appname and your appname is song not musiclibrary.

Related

django: cant import models from global app

Trying to import models from different app in views.py:
from global.models import Global
Console raise an error:
from global.models import Global
^
SyntaxError: invalid syntax
I checked a lot of information, but cant find what iam doing wrong.
global.models.py
from django.db import models
# Create your models here.
class Global(models.Model):
phone = models.CharField(max_length=50, blank=True)
email = models.EmailField(max_length=50, blank=True)
adress = models.CharField(max_length=100, blank=True)
class Meta:
verbose_name = 'Глобальные настройки'
verbose_name_plural = 'Глобальные настройки'
def __str__(self):
return 'Глобальные настройки'
projects.views.py
from django.shortcuts import render, redirect, get_object_or_404
from global.models import Global
from .models import Advertising, Films, Presentations, AuthorsLeft, AuthorsRight, BackstageImg
from django.utils import timezone
in my editor 'global' has blue color, and if i try to import another app it works normally. Could it be that 'global' reserved by django, or i simply doing something wrong?
from django.db.models.loading import get_model
global_model = get_model('global', 'Global')
You can use it, like this:
first_instance = global_model.objects.first()
print("Phone: {}".format(first_instance.phone))

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/
...

Django 2: Can't import models and save it

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.

Why am I getting the following error: NameError: name 'models' is not defined

Whenever I run the program, I get the following error:
NameError at /table/
name 'models' is not defined
It says that there's an error on line 4 in my views.
Here is my views.py:
from django.shortcuts import render
def display(request):
return render(request, 'template.tmpl', {'obj': models.Book.objects.all()})
Here is my models.py:
from django.db import models
class Book(models.Model):
author = models.CharField(max_length = 20)
title = models.CharField(max_length = 40)
publication_year = models.IntegerField()
Here is my urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
# /table/
url(r'^$', views.display, name='display'),
]
Can somebody please tell me what is wrong?
You are referencing models.Book in your view, but you have not imported models. In your views.py you need to do from myapp import models. Or you can do from myapp.models import Book and change it in your view function to just Book.objects.all().

Django: ImportError: cannot import name Count

I just pulled from my github and tried to setup my application on my Ubuntu (I originally ran my app on a Mac at home).
I re-created the database and reconfigured the settings.py -- also update the template locations, etc.
However, when I run the server "python manage.py runserver" get an error that says:
ImportError: cannot import name Count
I imported the Count in my views.py to use the annotate():
from django.shortcuts import render_to_response
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.db.models import Count
from mysite.blog.models import Blog
from mysite.blog.models import Comment
from mysite.blog.forms import CommentForm
def index(request):
#below, I used annotate()
blog_posts = Blog.objects.all().annotate(Count('comment')).order_by('-pub_date')[:5]
return render_to_response('blog/index.html',
{'blog_posts': blog_posts})
Why is not working?
Also, if I remove the "import Count" line, the error goes away and my app functions like normal.
Thanks,
Wenbert
UPDATE:
my models.py looks like this:
from django.db import models
class Blog(models.Model):
author = models.CharField(max_length=200)
title = models.CharField(max_length=200)
content = models.TextField()
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.content
def was_published_today(self):
return self.pub_date.date() == datetime.date.today()
class Comment(models.Model):
blog = models.ForeignKey(Blog)
author = models.CharField(max_length=200)
comment = models.TextField()
url = models.URLField()
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.comment
UPDATE 2
My urls.py looks like this:
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/(.*)', admin.site.root),
(r'^blog/$','mysite.blog.views.index'),
(r'^display_meta/$','mysite.blog.views.display_meta'),
(r'^blog/post/(?P<blog_id>\d+)/$','mysite.blog.views.post'),
)
This sounds like you're not using Django 1.1. Double check by opening up the Django shell and running
import django
print django.VERSION
You should see something like (1, 1, 0, 'final', 0) if you're using 1.1
I've updated my Django and it turns out that your import statement is correct as module structure was changed a bit. Are you sure your Django is of latest version?

Categories