Django: ImportError: cannot import name Count - python

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?

Related

ModuleNotFoundError: No module named 'musiclibrary.song'

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.

Django FileNotFoundError at /admin

I have model registered on admin page:
models.py
from django.db import models
class Question(models.Model):
cat = models.IntegerField()
quest = models.TextField(max_length=200)
answer = models.CharField(max_length=1000)
path = models.FilePathField()
date = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(default=0)
def __str__(self):
return f'{self.cat} - {self.quest}'
admin.py
from django.contrib import admin
from .models import Question
admin.site.register(Question)
and I can see a database through admin page:
https://i.stack.imgur.com/SuCcX.png
but I can't click on any record of the table and modify it due to an error:
https://i.stack.imgur.com/M6W5a.png
I did it many times since now, and I have never encountered such an error.
Does anybody have an idea how to fix it?
Acorrding to Django docs FilePathField() has one required argument path, which is:
"The absolute filesystem path to a directory from which this FilePathField should get its choices."
So you need modify your models.py:
class Question(models.Model):
...
path = models.FilePathField(path='/home/images')
...

URL Redirection is not working (Django 3.0)

I am the newbie of writing programming, now I am learning django.
I have a problem for URL redirection. I create the model and it does work at admin site.
Also I set the PK for each article, that successfully generate the URL by PK.
However when I post the message form the front-end, after posting it appear the error message suppose it should be redirect to the page of DetailViewand
I have imported the reverse function in my model, but it seem not working.
My python version : 3.7.6 and django version : 3.0.0
ImproperlyConfigured at /add/
No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.
My View
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView
from .models import Page
class PageListView(ListView):
model = Page
template_name='home.html'
context_object_name = 'all_post_list'
class PageDetailView(DetailView):
model = Page
template_name='post.html'
class PageCreateView(CreateView):
model = Page
template_name='post_new.html'
fields = ['title', 'author', 'body', 'body2']
Model
from django.urls import reverse
from django.db import models
from ckeditor.fields import RichTextField
class Page(models.Model):
title = models.CharField(max_length=50)
author = models.ForeignKey(
'auth.User',
on_delete=models.CASCADE,
)
body = RichTextField()
body2 = models.TextField()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post', args=[str(self.id)])
URL
from django.urls import path
from .views import PageListView, PageDetailView, PageCreateView
urlpatterns = [
path('add/', PageCreateView.as_view(), name='post_new'),
path('', PageListView.as_view(), name='home'),
path('blog/<int:pk>/', PageDetailView.as_view(), name='post'),
]
Thanks for helping. :)
I think your indentation is the problem here. Fix it by:
class Page(models.Model):
title = models.CharField(max_length=50)
author = models.ForeignKey(
'auth.User',
on_delete=models.CASCADE,
)
body = RichTextField()
body2 = models.TextField()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post', args=[self.id])

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

Improperly configured django error

I have a simple django project and whenever i run it, it gives me an improperly configured error. Tells me my model is missing a query set:
Improperly Configured Error Image
Here's the code for my views.py. The functionality doesn't matter for now:
import random
from django.shortcuts import render
from django.http import HttpResponse
from django.views import View
from django.views.generic import TemplateView
from django.views.generic.list import ListView
class RestaurantList(ListView):
querySet = Restaurant.objects.all()
template_name = 'restaurants/restaurants_list.html'
class SpicyList(ListView):
template_name = 'restaurants/restaurants_list.html'
querySet = Restaurant.objects.filter(category__iexact='spicy')
class AsianList(ListView):
template_name = 'restaurants/restaurants_list.html'
querySet = Restaurant.objects.filter(category__iexact='asian')
Here's the code for my models.py
from django.db import models
class Restaurant(models.Model):
name = models.CharField(max_length=120)
loocation = models.CharField(max_length=120, null=True, blank=True)
category = models.CharField(max_length=120, null=True, blank=False)
timestamp = models.DateTimeField(auto_now=True)
updated = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
urls.py code:
from django.contrib import admin
from django.conf.urls import url
from django.views.generic import TemplateView
from restaurant.views import *
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', TemplateView.as_view(template_name='home.html')),
url(r'^restaurants/$', RestaurantList.as_view()),
url(r'^restaurants/asian/$', AsianList.as_view()),
url(r'^restaurants/spicy/$', SpicyList.as_view()),
url(r'^Contact/$', TemplateView.as_view(template_name='Contact.html')),
url(r'^About/$', TemplateView.as_view(template_name='About.html'))
]
It's only the urls containing 'restaurants' that give me this error. The rest are fine.
Here's a picture of my file structure at the side
File Structure
The queryset attribute should be lower case at all.
all your views contain querySet
replace them by queryset lower case
Or you can provide the model attribute model = ModelName
See more In the Official Documentation

Categories