importError: No module named django.db - django

from django.db import models
# Create your models here.
def Article(models.Model):
title=models.CharField(max_length=200)
body=models.TextField()
pub_date=models.DateTimeField('date published')
likes=models.IntegerField()
def __unicode__(self):
return self.title
This is my code
I am using Django 1.8.2
I am within virtual environment

Are you sure that you create a simple project?
django-admin.py startproject nameofyourproject
mkdir apps
cd apps
django-admin.py startapp nameofyourapp
add in settings in variable "Installed Apps" your new app
nothing should fail...

can you activate your virtual environment. And make sure django is install in your virtual environment by using following command.
pip freeze
out put of pip freeze
(Dev-Env)➜ django_chat git:(singleUserChat) pip freeze
Django==1.7.1

Related

Django deploy errors

I just launched the Django app. As an image, everything is in place, but the form and admin panel do not work. Anyone who knows please help
I get this error when I run the form.
Let me know if I need to share any code.
model.py
from django.db import models
# Create your models here.
class Form(models.Model):
fname_lname = models.CharField(max_length=50, verbose_name="Ad Soyad")
number = models.CharField(max_length=20, verbose_name="Nömrə")
send_date = models.DateTimeField(auto_now_add=True, verbose_name="Tarix")
class Meta:
verbose_name = 'Formlar'
verbose_name_plural = 'Formlar'
def __str__(self):
return self.fname_lname
As Marco suggested, once you deploy you should run your migrations since you're probably using a different database. You run migrations same as when in development depending on your platform the following should work:
python manage.py makemigrations
python manage.py migrate
just make sure you are on the same directory as the manage.py file. Also remember that you will have to tweak the settings.py file database settings if you haven't already.
try the commands below:
python manage.py makemigrations --fake
python manage.py migrate --fake
if it donot work, i think you have to delete database and recreate it,
if you need the data you can use python manage.py dumbdata ->data.json
and after you create the new database use python manage.py loaddata data.json

ModuleNotFoundError: No module named 'stripe'

ModuleNotFoundError: No module named 'stripe' Even I Have import into my views.py fle
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from django.conf import settings
import stripe
STRIPE_PUBLISHABLE_KEY1=settings.STRIPE_PUBLISHABLE_KEY
# Create your views here.
def testing(request):
return render(request,"login.html",{'key':STRIPE_PUBLISHABLE_KEY1})
def charge(request): # new
if request.method == 'POST':
charge = stripe.Charge.create(
amount=500,
currency='usd',
description='A Django charge',
source=request.POST['stripeToken']
)
return render(request, 'success.html')
Always Showing Error
NameError at /charge/
name 'stripe' is not defined
May be you haven't install it in your enviroment,Try to install it using
pip install stripe
for more details see documentations https://pypi.org/project/stripe/
Did you install Stripe? if not, try:
pip install stripe
Yet another reason may be that you are using venv but that you installed the module for the wrong version of Python. For example, compare these:
# install to default Python version, which might be, say, 3.10
# ...and then you'll get module not found if you expected to install it to, say, 3.9.
pip install -r requirements.txt
# install the module for 3.9 explicitly
python3.9 -m pip install -r requirements.txt

Running Django Unit Tests on Bamboo with Postgresql

I am using Django 1.9.6. I have, for example, the following model in my models.py file:
class Question(BaseModel):
question_text = models.CharField(max_length=500, unique=True)
class Meta:
verbose_name = 'Question'
verbose_name_plural = 'Questions'
def __unicode__(self):
return (
u"Question id: {}".format(self.id)
)
and in tests.py I am running the following test on it:
class TestQuestionModel(TestCase):
def setUp(self):
Question.objects.create(question_text="What is the airspeed velocity of an unladen swallow?")
def test_simple_questions(self):
simpleQuestion = Question.objects.get(question_text="What is the airspeed velocity of an unladen swallow?")
self.assertEqual(simpleQuestion.question_text, "What is the airspeed velocity of an unladen swallow?")
And I'm using a postgres database. This all works hunky-dory locally.
I understand that I need to convert the output to JUnit XML to run the tests in Bamboo, but I am getting a little stuck. This answer got me 90% of the way there, but I am struggling to figure out the postgres part. The script I am running before the JUnit Parser is as follows:
#installing pip locally
wget https://bootstrap.pypa.io/get-pip.py
python get-pip.py --root=${bamboo.build.working.directory}/tmp --ignore-installed
export PATH=${bamboo.build.working.directory}/tmp/usr/local/bin:$PATH
export PYTHONPATH=${bamboo.build.working.directory}/tmp/usr/local/lib/python2.7/dist-packages:$PYTHONPATH
echo Pip is located `which pip`
# setting up virtualenv
pip install --root=${bamboo.build.working.directory}/tmp --ignore-installed virtualenv
virtualenv .
. bin/activate
# get pg_config
apt-get install libpq-dev python-dev
# from the backend/Dockerfile
pip install --no-cache-dir -r requirements.txt
# running tests into JUnit XML format
python ./manage.py test --junitxml=test-reports\results.xml
And I am getting several errors:
E: Could not open lock file /var/lib/dpkg/lock - open (13: Permission denied)
E: Unable to lock the administration directory (/var/lib/dpkg/), are you root?
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-ZV8Jz0/psycopg2/
Traceback (most recent call last):
File "./manage.py", line 6, in
from django.core.management import execute_from_command_line
ImportError: No module named django.core.management
Can someone help me overcome this?

Integrate SASS/SCSS with Django

I want to use SASS/SCSS with Django application.
I followed the link https://bitbucket.org/synic/django-sass.
I installed SASS using sudo pip install sass.
When i run Python manage.py runserver,iam getting error as
'sass' is not a valid tag library: Template library sass not found, tried django.templatetags.sass
Can Anyone help me?!
python sass (pip install sass) https://pypi.python.org/pypi/sass is different
from django-sass (https://bitbucket.org/synic/django-sass)
Download django sass from https://bitbucket.org/synic/django-sass after that install and setup as documented .
Have you first installed sass, the ruby app?
$ apt-get install ruby-sass
You'll know if it's done properlly; as type sass on the command line, does sassy things.
Next, I cloned django-sass (from the other answer):
git clone git#bitbucket.org:synic/django-sass.git
Then navigated to the puled folder and installed it.
$ python setup.py install
Initially the installation crashed out:
IOError: [Errno 2] No such file or directory: 'CHANGES.rst'
So I quickly created the file:
touch CHANGES.rst
and ran the install command again.
no problems.
The django-sass-processor package is a great package that lets you easily integrate SASS/SCSS with Django.
Here's a tutorial on how to set up SASS/SCSS with Django.
I've used the package a few times and have been happy with it.
Here is my DIY out of the box solution
Install Libsass and Watchdog
pip install libsass watchdog
Create an app named core
python manage.py startapp core
core/sass.py
import os
import time
import site
import sass
import threading
from pathlib import Path
from django.apps import apps
from django.conf import settings
from watchdog.observers import Observer
from watchdog.events import FileClosedEvent
def compiler():
packageFolders = [
site.getusersitepackages(),
*[path for path in site.getsitepackages()],
]
staticFolders = settings.STATICFILES_DIRS.copy()
staticFolders += [
os.path.join(app.path, "static") for app in apps.get_app_configs()
]
compileFolders = staticFolders.copy()
for staticFolder in staticFolders:
for packageFolder in packageFolders:
if Path(staticFolder).is_relative_to(packageFolder):
if staticFolder in compileFolders:
compileFolders.remove(staticFolder)
if settings.DEBUG:
def watcher(path):
class Event(FileClosedEvent):
def dispatch(self, event):
filename, extension = os.path.splitext(event.src_path)
if extension == ".scss":
time.sleep(0.5)
for d in compileFolders:
if os.path.isdir(d):
try:
sass.compile(
dirname=(d, d),
output_style="expanded",
include_paths=staticFolders,
)
except sass.CompileError as error:
print(error)
event_handler = Event(path)
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
for d in compileFolders:
if os.path.isdir(d):
try:
sass.compile(
dirname=(d, d),
output_style="expanded",
include_paths=staticFolders,
)
except sass.CompileError as error:
print(error)
thread = threading.Thread(target=watcher, args=(d,), daemon=True)
thread.start()
else:
d = settings.STATIC_ROOT
if os.path.exists(d):
try:
sass.compile(
dirname=(d, d),
output_style="expanded",
include_paths=staticFolders,
)
except sass.CompileError as error:
print(error)
core/apps.py
from django.apps import AppConfig
from core.sass import compiler
class CoreConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'core'
def ready(self):
compiler()
For more info, djboilerplate is a boilerplate project where I have added this out of the sass feature

Django installing custom app(Postgresql model)

I've installed following packages https://github.com/zacharyvoase/django-postgres via pip and virtualenv.:
pip install git+https://github.com/zacharyvoase/django-postgres.git
It was installed succesfully. I used it in my model(As described in its documentaion)
from django.db import models
import django_postgres as pg
USStates = pg.Enum('states_of_the_usa', ['AL', 'WY'])
class Address(pg.CompositeType):
line1 = models.CharField(max_length=100)
line2 = models.CharField(max_length=100, blank=True)
city = models.CharField(max_length=100)
zip_code = models.CharField(max_length=10)
state = USStates()
country = models.CharField(max_length=100)
when I try to sync it via shell, it throws an error:
(virtualenv) user$ python manage.py sync_pgviews
Unknown command: 'sync_pgviews'
Type 'manage.py help' for usage.
Have I left something after installing an app? And is it the correct way to install django new app?
In order for management commands to work, the app has to be added to INSTALLED_APPS. However, a basic problem that you have is that the module doesn't support ENUM yet. Its still a work in progress.
After adding new app:
add app to INSTALLED_APPS in settings.py
run python manage.py syncdb
add urls to urls.py
Perhaps you should go through this (again?) https://docs.djangoproject.com/en/dev/intro/tutorial01/