Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Processing file uploaded by jquery fileupload
I've followed the tutorial for jquery fileupload the code I've written is below $('#image_file').fileupload({ dataType: 'json', type: 'post', url: '/whats-on/upload-event/?v='+event_id, contentType: "application/json; charset=utf-8", done: function (e, data) { console.log('done'); } }); It returns an error ValueError: No JSON object could be decoded Here's the python function it fails when it tries @csrf_exempt def create_event(request): context = RequestContext(request) response_data = {} response_data['status'] = False if request.FILES: file = request.FILES[u'files'] response_data['status'] = True elif request.method == 'POST': data = json.loads(request.body) It doesn't go through request.FILES and fails when it reaches data = json.loads(request.body) -
Django - Html page with multiple parts, updating on selection
I want to create a page with basically 4 "parts" A radio button list, with values based on search results A text area that gets updated based on what was selected in the radio button section Another radiobutton list, that changes based on what was selected in list 1. Another text area, updates based on list 2's selection As an example. List 1 could be Dogs Cats Parrots If you select dogs, the text area will say: "mans best friend, they bark" List 2 would then say: Poodle Foxterrier Then selection poodle the 2nd text area will say "short white haired dog" Can this be done through using forms/widgets? I'm quite new to Django so I'm not sure what would be the best way to do this, as it has to be a non javascript solution. -
Calculate multiple modelField from one Formfield
I need extract multiple ModelField value from one FormField. where I should do this? in clean_<field> functions? with cleaned_data mutation? form __init__ function? in model.save or form.save function? model: def normalize_name(name): # some code return name class MyModel(models.Model): name = models.CharField(max_length=250) normalize_name = models.CharField(max_length=250, unique=True) form: class MyForm(forms.ModelForm): class Meta: model = MyModel fields = ('name',) # or normalize_name? or both? -
Django date format issue using strptime().date
I'm using django 1.8 in python 2.7 My code is (datetime.strptime('diagnosis_circumstances_date', "%Y-%m-%d")).date() and us a result I get time data 'diagnosis_circumstances_date' does not match format '%Y-%m-%d'. My date is 1980-08-28. -
Django - choice set, but no drop down in form
I would like to have a choice set in my model for template and validation. However, in the model.form for that model I want to have just an integer field. How can I change the widget in order to just get a InputField? I tried to change the widget to forms.Model, but that did not seem to work. I get a error: 'IntegerField' object has no attribute 'attrs' forms.py: class KombiPublikationForm(forms.ModelForm): class Meta: model = KombiPublikation #fields = [] exclude = ['pub_sprache'] widgets = { 'monat': forms.IntegerField(), # does not work } model.py: MONTH = ( (1, 'Januar'), (2, 'Februar'), (3, 'März'), (4, 'April'), (5, 'Mai'), (6, 'Juni'), (7, 'Juli'), (8, 'August'), (9, 'September'), (10, 'Oktober'), (11, 'November'), (12, 'Dezember'), ) class KombiPublikation(models.Model): [...] monat = models.IntegerField(choices=MONTH) Thanks! -
Error: Could not find git remote
I tried to run this command on Heroku. heroku run cp -r /app/.heroku/python/lib/python2.7/site-packages/django/contrib/admin/static/admin doctor_app/static/ And I got this error. ▸ Error: Could not find git remote /app/.heroku/python/lib/python2.7/site-packages/django/contrib/admin/static/admin in /home/adil/Code/mezino/DocTest/doctor_app ▸ remotes: heroku Any Idea, Why ? -
access form data in view
I hava a form in my template which is for search.I did not made any form class to it. Is it possible to have access form data in view or should I make a form class to it. <form class="navbar-form" role="search" action="{% url 'my_url_name' %}" method="get"> <div class="input-group add-on"> <input class="form-control" placeholder="search" name="srch-term" id="srch-term" type="text"> <div class="input-group-btn"> <button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button> </div> </div> </form> I use this form for its style and I can not make this style with Form class -
Django not able to acess S3 static files in heroku
I am trying to deploy my application on Heroku. I am facing issue with static files. I have followed this article on Django and Static Assets. But my deployed app was not able to access django-admin static files. Then I used this question as a reference and uploaded my static data to AWS-S3 and tried to link with django. But still not working. Below is my setting.py import os AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = 'doctor-app-assets' STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' STATIC_URL = 'http://' + AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'storages', 'rest_framework', 'listing', ] WSGI_APPLICATION = 'doctor_app.wsgi.application' STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), ) STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' Here is my Procfile web: python manage.py collectstatic --noinput; gunicorn doctor_app.wsgi --workers=4 --bind=0.0.0.0:$PORT Here is my S3-bucket My admin panel for django app is still ugly without css. Please help me out here ? -
Removing Inconsistency in django web app
I am working on making an online two player tic-tac-toe game. I am using django framework for it. Since I am making the tic-tac-toe table(data structure to store state of game) global in my views, it leads to inconsistent state when the app is opened by more than one client at same time. Working of my app: The user is given a choice to play first or not. He submits his choice. His choice is decoded by 'chance' view. The user then starts playing and clicks on certain box on the board. This move is decoded by 'index' view. Then computer's move is computed and is then displayed on the board. But when two users play the game simultaneously, both are changing the same global table or board. I cannot make it as local variable since the previous data will be lost. How do I store the data for each user and use it? Views code: from django.shortcuts import render from django.http import HttpResponse from django.http import Http404 from django.http import JsonResponse from random import randint from django.views.decorators.csrf import csrf_exempt xpos = -1 ypos = -1 start = 0 a = [[0 for x in range(3)] for x in range(3)] … -
How can I filter objects using django views?
I am using this generic view and I would like to filter the campaign_type's for only certain types. I was trying to use queryset= CampaignType.objects.filter(type='social') but it doesn't work. Any Clue ? class CCtypeUpdate(generic.UpdateView): model = Campaign fields = ['campaign_type'] template_name = 'campaign/campaign.html' success_url = '../../' -
Django REST framework foreign keys and filtering 5
I have following models in django app: `class StoreTransaction(models.Model): store = models.ForeignKey('store_master.StoreBasic') store_terminal = models.ForeignKey('store_master.StoreTerminal') transaction_number = models.PositiveIntegerField() class Meta: unique_together = ("store", "store_terminal", "transaction_number")` `class SalesTransaction(models.Model): store_transaction = models.OneToOneField('StoreTransaction') total_amount = models.DecimalField(max_digits=20, decimal_places=2) total_amount_round = models.PositiveIntegerField() diff_amount = models.DecimalField(max_digits=6, decimal_places=2) discount_amount = models.DecimalField(max_digits=20, decimal_places=2)` -
Django Rest Framework with UTF-8
I am using Django 1.10 and Django Rest Framework 3. Here is my view ofGET method(list): class JSONResponse(HttpResponse): def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) @csrf_exempt def news_list(request): if request.method == 'GET': news = News.objects.all() serializer = Newsserializer(news, many=True) return JSONResponse(serializer.data) Well it works just fine and gives me all my rows in Json format. Now i want to use UTF-8 characters in my columns. But when i GET all my data i see characters like this ★ or شسیببییبیسب. How can i fix this? -
assertRaises working with arguments
Trying to write test in django like this: self.assertRaises(ProtectedError, self.client.post, path=reverse('crm:client', kwargs={'pk': 1}), data=initial_data) But getting error then running test: Traceback (most recent call last): File "/Users/smosker/PycharmProjects/CRM_system/dive_into/crm/tests.py", line 378, in test_delete_client response = self.client.post(reverse('crm:client', kwargs={'pk': 1}), initial_data) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/test/client.py", line 512, in post secure=secure, **extra) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/test/client.py", line 313, in post secure=secure, **extra) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/test/client.py", line 379, in generic return self.request(**r) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/test/client.py", line 466, in request six.reraise(*exc_info) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/views/generic/base.py", line 89, in dispatch return handler(request, *args, **kwargs) File "/Users/smosker/PycharmProjects/CRM_system/dive_into/crm/views.py", line 74, in post object_get.delete() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/base.py", line 895, in delete collector.collect([self]) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/deletion.py", line 229, in collect field.rel.on_delete(self, field, sub_objs, self.using) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/deletion.py", line 28, in PROTECT sub_objs ProtectedError: ("Cannot delete some instances of model 'Client' because they are referenced through a protected foreign key: 'Activity.client'", [<Activity: Клиент: test, Тема: test, Отправлено: Нет>]) It's like function was called before assertRaises, so it doesnt catch it, but i cant understand how it happened. -
Django Patch Side effect IntegrityError not being raised
I have the following view, which excepts POST requests, and serializes an objects data (a Draftschedule) to create a new copy (a FrozenSchedule): from reports.tasks import create_frozen_schedule def freeze_schedule(request, pk): """Valid post request will freeze a Draft Schedule serializing its data""" client = get_object_or_404(Client, draftschedule=pk) try: # Serialize data into a FrozenSchedule object frozenschedule = create_frozen_schedule(pk, request.user.id) except IntegrityError: # Warn user if action failed messages.warning(request, "A Schedule of this Type already exists") return redirect(client.draftschedule) else: # If Schedule is Frozen successfully messages.success(request, "Schedule Frozen") return redirect(frozenschedule) I'm trying to write a test to assert certain things happen after an IntegrityError is raised. I'm struggling to understand why it's failing, it's not immediately obvious to me where I'm going wrong since I'm fairly inexperienced with mocking / patching. I've tried to mock the create_frozen_schedule function to raise an IntegrityError when called: @patch('reports.tasks.create_frozen_schedule') def test_freeze_schedule_with_conflict(self, mock_freeze): mock_freeze.side_effect = IntegrityError with self.assertRaises(IntegrityError): self.client.post(self.url) # More unit tests following same premise... But I end up with the following error: .......................................................................................F............ ====================================================================== FAIL: test_freeze_schedule_with_conflict (reports.tests.test_views.TestFreezeSchedule) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python3.4/unittest/mock.py", line 1136, in patched return func(*args, **keywargs) File "/home/jwe/piesup2/reports/tests/test_views.py", line 495, in test_freeze_schedule_with_conflict self.client.post(self.url) AssertionError: IntegrityError not raised ---------------------------------------------------------------------- Points to … -
Customizing the user model: how to show related info in the admin
Django 1.10.2 Studying customization of the User model. Trying to follow the documentaion https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#extending-the-existing-user-model I wish to store that department and show it in the admin. The problem is that department doesn't appear. I played with fieldsets and list_display, but failed. Could you help me understand how to show the department in the admin? admin.py from django.contrib.auth.models import User from django.db import models class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) department = models.CharField(max_length=100) from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User # Define an inline admin descriptor for Employee model # which acts a bit like a singleton class EmployeeInline(admin.StackedInline): model = Employee can_delete = False verbose_name_plural = 'employee' # Define a new User admin class UserAdmin(BaseUserAdmin): inlines = (EmployeeInline, ) # Re-register UserAdmin admin.site.unregister(User) admin.site.register(User, UserAdmin) -
Django DRF serializer on PrimaryKeyRelatedField
Question about PrimaryKeyRelatedField serialization in Django DRF version 3.4.7. models class UserModel(AbstractEmailUser): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.email) class Conversation(models.Model): admin = models.ForeignKey('UserModel', db_index=True, related_name='admin_user') patient = models.ForeignKey('UserModel', db_index=True) subject = models.CharField(max_length=255, db_index=True) user_reply = models.BooleanField(default=False) admin_seen = models.BooleanField(default=False) expire = models.DateTimeField() conversation_type = models.ForeignKey('ConversationType', db_index=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.admin) class ConversationMessages(models.Model): text = models.TextField(db_index=True) conversation = models.ForeignKey('Conversation', db_index=True, related_name='msg_conv') user = models.ForeignKey('UserModel', db_index=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.user) class ConversationFiles(models.Model): message = models.ForeignKey('ConversationMessages', db_index=True, related_name='message') file = models.FileField(upload_to='conversations', db_index=True) def __str__(self): return str(self.user) Every model has related field for Rest Framework. Logic is create conversation, then take ID from conversation and save message model. serialize's class MessagesSerializer(serializers.ModelSerializer): text = serializers.CharField(required=False) conversation = serializers.PrimaryKeyRelatedField(queryset=Conversation.objects.all(), required=False) user = serializers.PrimaryKeyRelatedField(queryset=UserModel.objects.all(), required=False) class Meta: model = ConversationMessages class ConversationSerializer(serializers.ModelSerializer): admin = serializers.PrimaryKeyRelatedField(queryset=UserModel.objects.all(), required=False) msg_conv = MessagesSerializer() class Meta: model = Conversation def create(self, validated_data): msg_conv = validated_data.pop('msg_conv', None) admin_user = Conversation.objects.create(**validated_data) ConversationMessages.objects.create(conversation_id=Conversation.objects.get(id=admin_user.id).id, **msg_conv) return admin_user Serializer is problem on POST method. Everything works great POST object create data in database, but problem is when serializer save object i get this message: 'RelatedManager' object has no attribute 'conversation'. View … -
How to check if a file is empty avoid reading the whole file?
I am using django and want to check if a uploading file is empty, but avoid uploading or reading the whole file, because it might be huge and take time to calculate. -
I am creating Django Project from Visual Studio 15.During creating the project i am getting following error. i also intall all packages
The project file 'C:\User\user\AppData\Local\Temp\nglxarve.3dk\Temp\DjangoWebProject6.pyproj'cannot be opened. There is a missing project subtype. Subtype: '{5F0BE9CA-D677-4A4D-8806-6076C0FAAD37}' is supported by this installation. -
I am new to python and unit test. How to write a unit test for a function that returns random string
How to write a test case for this: def rand_fun(): # return a random string My test case: def test_rand_fun(): # what to write here to check rand_fun Thanks in advance -
Django How can I use redis in Windows10?
I am developing small system with Django framework and Windows 10. I am going to use Redis for caching on memory. Well, I found that Redis doesn't support Windows OS officially but MsOpenTech provides a package for Windows 64 bit. I installed it with chocolatey package manager. https://chocolatey.org/packages/redis-64 Then I installed django-redis package by pip install in cmd. Well, It automatically installed redis module at the same time. I thought it would be fine to delete redis module because I already installed redis 3.0.503 64 bit(for Win). But it occured error "no mudule named 'redis'". I checked django-redis directory "django_redis-4.5.0-py3.4.egg-info". There was one line 'redis>=2.10.0' in 'requries.text' file. so I assumed django-redis is set to need redis 2.10.0 as default. well, then I just installed redis by pip install redis in cmd. After setting in Django, I saved some key value data as test on redis. (by using cache_page decorator) CACHES = { "default" : { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTION": { "CLIENT_CLASS": "django_redis.client.DefaultClient", }, "KEY_PREFIX": "Test" } } I connected to redis. redis-cli -n 1 I checked keys 127.0.0.1:6379[1]> keys * result was like this. empty (empty list or set) then I put test data on redis by cache_page … -
django rest framework - Nested serialization not including nested object fields
i'm trying to get nested object fields populated, however the only thing being returned is the primary key of each object (output below): { "name": "3037", "description": "this is our first test product", "components": [ 1, 2, 3, 4 ] } How do I have the component model's fields populated as well (and not just the PKs)? I would like to have the name and description included. models.py class Product(models.Model): name = models.CharField('Bag name', max_length=64) description = models.TextField ('Description of bag', max_length=512, blank=True) urlKey = models.SlugField('URL Key', unique=True, max_length=64) def __str__(self): return self.name class Component(models.Model): name = models.CharField('Component name', max_length=64) description = models.TextField('Component of product', max_length=512, blank=True) fits = models.ForeignKey('Product', related_name='components') def __str__(self): return self.fits.name + "-" + self.name serializers.py from rest_framework import serializers from app.models import Product, Component, Finish, Variant class componentSerializer(serializers.ModelSerializer): class Meta: model = Component fields = ('name', 'description', 'fits') class productSerializer(serializers.ModelSerializer): #components_that_fit = componentSerializer(many=True) class Meta: model = Product fields = ('name', 'description', 'components') #fields = ('name', 'description', 'components_that_fit' ) The documented approach doesn't seem to be working for me, and gives me the following error (you can see the lines following the standard approach commented out in the serializers.py entry above: Got AttributeError when attempting … -
Python Django official tutorial "Polls", beginner gets frustrating errors.
I am trying to follow through the Python Django Tutorial from the official site. However I find it hard to follow. I did everything as written but I got the following error" enter image description here It sounds like something is wrong with the ENV, but I am not so sure why. Also at the last line of error it said "include is not defined"... -
How to prefetch a list of unique values from a related Django model?
I'd like to prefetch a list of unique values from a related model in Django in as few queries as possible. For instance, consider the following : class A(models.Model): b = models.ForeignKey('B') value = models.CharField(max_length=10) class B(models.Model): pass I'd like to annotate each model instance of a queryset on B, with a list of unique values from the value column in the related A objects. >>> qs = B.objects.all().annotate(distinct_a_values=...) >>> [a.value for a in qs.first().a_set.all()] ["value_1", "value_2", "value_1"] >>> qs.first().distinct_a_values ["value_1", "value_2"] The closest I could find was to use a Prefetch object : >>> qs = B.objects.all().prefetch_related( Prefetch( 'a_set', A.objects.all().distinct('value').only('value', 'b_id'), to_attr='distinct_a_values' ) ) It works, but feels clunky, and it is definitely weird to get a list of A objects, only to discover that they are distinct on something other than the primary key. Any other way? -
Django HTML template not rendering the jQuery formset plugin
The jquery has been included in the following html template: <!DOCTYPE html> <html> <head> <title>Medicians</title> </head> <body> {% load staticfiles %} {% load crispy_forms_tags %} {% load formset_tags %} {% if messages %} {% for message in messages %} <p>{{ message }}</p> {% endfor %} {% endif %} <form method="post"> {% csrf_token %} <label>First Name</label> {{ profile_form.first_name }} {% if profile_form.first_name.errors %} {% for error in profile_form.first_name.errors %} {{ error|escape }} {% endfor %} {% endif %} <label>Last Name</label> {{ profile_form.last_name }} {% if profile_form.last_name.errors %} {% for error in profile_form.last_name.errors %} {{ error|escape }} {% endfor %} {% endif %} {{ link_formset.management_form }} {% for link_form in link_formset %} <div class="link-formset"> {{ link_form.anchor }} {% if link_form.anchor.errors %} {% for error in link_form.anchor.errors %} {{ error|escape }} {% endfor %} {% endif %} {{ link_form.url }} {% if link_form.url.errors %} {% for error in link_form.url.errors %} {{ error|escape }} {% endfor %} {% endif %} </div> {% endfor %} {% if link_formset.non_form_errors %} {% for error in link_formset.non_form_errors %} {{ error|escape }} {% endfor %} {% endif %} <input type="submit" value="Update Profile" class="button"/> </form> <!-- Include formset plugin - including jQuery dependency --> <!-- This is where I need … -
Error loading psycopg2 module: dlopen with virtualenv django python 2.7
Guys I stuck this problem for couple weeks already. I have tried almost every answer I could find in stack overflow. The error is below: (venv1) Caimings-MacBook-Pro:yang NLStom$ python manage.py migrate Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/NLStom/Desktop/hey/yang/venv1/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Users/NLStom/Desktop/hey/yang/venv1/lib/python2.7/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/Users/NLStom/Desktop/hey/yang/venv1/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/NLStom/Desktop/hey/yang/venv1/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/Users/NLStom/Desktop/hey/yang/venv1/lib/python2.7/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/NLStom/Desktop/hey/yang/venv1/lib/python2.7/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/NLStom/Desktop/hey/yang/venv1/lib/python2.7/site-packages/django/contrib/auth/base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File "/Users/NLStom/Desktop/hey/yang/venv1/lib/python2.7/site-packages/django/db/models/base.py", line 119, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/Users/NLStom/Desktop/hey/yang/venv1/lib/python2.7/site-packages/django/db/models/base.py", line 316, in add_to_class value.contribute_to_class(cls, name) File "/Users/NLStom/Desktop/hey/yang/venv1/lib/python2.7/site-packages/django/db/models/options.py", line 214, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/Users/NLStom/Desktop/hey/yang/venv1/lib/python2.7/site-packages/django/db/__init__.py", line 33, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/Users/NLStom/Desktop/hey/yang/venv1/lib/python2.7/site-packages/django/db/utils.py", line 211, in __getitem__ backend = load_backend(db['ENGINE']) File "/Users/NLStom/Desktop/hey/yang/venv1/lib/python2.7/site-packages/django/db/utils.py", line 115, in load_backend return import_module('%s.base' % backend_name) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/NLStom/Desktop/hey/yang/venv1/lib/python2.7/site-packages/django/db/backends/postgresql/base.py", line 24, in <module> raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: dlopen(/Users/NLStom/Desktop/hey/yang/venv1/lib/python2.7/site-packages/psycopg2/_psycopg.so, 2): Symbol not found: _PQbackendPID Referenced from: /Users/NLStom/Desktop/hey/yang/venv1/lib/python2.7/site-packages/psycopg2/_psycopg.so Expected in: dynamic lookup …