Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django get 2nd,3rd,4th column from row. for loop
I have a row named question It has following fields 1 id 2 question 3 option1 4 option2 5 option3 6 option4 7 answer So to access option4 i would do that by question.option4 Now i have to display all of the 4 options I have the following template <ol> {% for i in "xxxx" %} <li>{{question.}}</li> {% endfor %} </ol> What to write to get option1,2,3,4... in for loop question.(dont know what to write) -
AngularJS Error: Unknown provider: eProvider <- e <- $exceptionHandler <- $rootScope
I am suddenly seeing this error on our EC2 production instance. I deployed a new release and realized the error. Afterwards, I deployed the earlier version but the issue did not get resolved. The error shows up no matter whatever previously working commit I deploy. -
{% block %} in {% blocktrans %}
I am planning to implement Arabic translations which will make a whole sentence to be written right-to-left. How should do this?: <!-- parent.html --> {% blocktrans %} {% block category %}{% endblock category %} - Site Name {% endblocktrans %} <!-- child.html --> {% extends 'parent.html' %} {% block category %}Books{% endblock category %} for Arabic translation I need to use blocktrans, and I need to use different children names as well. -
How to make a simple 'trending topics' page using python(django)
In my website there will be some static content with pictures in it... i want to make a home page that will show the trending topics based on the view count of every content. how can i do that ? -
Issue with an endpoint - can't post - foreignkey option missing (DjangoREST)
So this is what my user api looks like: { "count": 1, "next": null, "previous": null, "results": [ { "id": 1, "username": "FOOBAR", "Todo_List": [ { "url": "http://localhost:8000/todolist_api/1/", "default": true, "name": "Chores", "todos": [ { "url": "http://localhost:8000/todos_api/1/", "todolist_id": 1, "name": "Laundry", }, { "url": "http://localhost:8000/todos_api/2/", "todolist_id": 1, "name": "Sweep floor", } ] }, { "url": "http://localhost:8000/todolist_api/2/", "default": true, "name": "Work", "todos": [ { "url": "http://localhost:8000/todos_api/3/", "todolist_id": 2, "name": "Talk to Boss", }, { "url": "http://localhost:8000/todos_api/4/", "todolist_id": 2, "name": "Say Hello to Janitor", } ] } ] ] } I have 3 API endpoints : user_api, todolist_api, and todos_api I'm having trouble with my todos_api. I have it set so when a user wants to add another todo for a specific todos_list, they have to send a post request to the todos_api with the todolist's pk and the name of the todo. Ie: if I wanted to created another todo for "Chores", I'd send a post request to the todos_api with todolist_id = 1, and name = "Dust the computer". The issue that is the option for the todolist_id is missing. And When I hit post anyway, I get the error saying todolist_id cannot be null. I think it might be … -
How to configure Django-cms 3.4 in my Django 1.8 project
Every time I try to do I get import error like no modeule name mptt no plugin found but I have installed all the plugins. -
Django-Summernote: Working fine on local machine but server not posting the data
I am using Django-summernote for my project. It works perfectly on local system. But on server (Nginx+gunicorn) it is not updating the data. I mean widget loads properly. Image are also uploaded to server, but it throws 404 error upon submission. Any solution? -
AttributeError: 'BoxesView' object has no attribute 'object_list'
Trying to add a form to my homepage view and getting this error when I submit the form. Here's my code: views.py class BoxesView(ListView, FormMixin): template_name = 'polls.html' form_class = UserRegistrationForm def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = User.objects.create_user(username=username, password=password) user.save() return redirect('/') return self.form_invalid(form) def get_context_data(self, **kwargs): context = super(BoxesView, self).get_context_data() context['form'] = self.get_form() question_list = Question.objects.all().order_by('-date') choice = Choice.objects.all() context['question_list'] = question_list context['choice'] = choice search = self.request.GET.get('search') posts = Post.objects.all().filter(category=1).order_by('-date') if search: posts = posts.filter( Q(title__icontains=search) | Q(content__icontains=search) ) else: posts = Post.objects.all().filter(category=1).order_by('-date') context['posts'] = posts return context def get_queryset(self): pass forms.py class UserRegistrationForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = [ 'username', 'password', ] base.html <form action="" enctype="multipart/form-data" method="post">{% csrf_token %} <div class="registerBox"> {{ form.username }} {{ form.password }} <input type="submit" value="register"/> </div> </form> My traceback is pointing me to these lines: return self.form_invalid(form) & context = super(BoxesView, self).get_context_data(). Hopefully this can give you an indication of what the problem is but i've been unable to work it out.Any idea? -
Django file upload - fileno Error
I am trying to upload a file (audio-file) from a django webapp to a django rest service. The form: <form method="post" action="/" name="submit" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="uploaded_file"><br /><br /> <input type="submit" name="submit" value="Submit"> </form> The view: from poster.streaminghttp import register_openers from poster.encode import multipart_encode import urllib2 <...> def post(self, request): """ POST request: handles file upload to web service """ uploaded_file = request.FILES['uploaded_file'] server = "http://127.0.0.1:8000" headers = {} # Register the streaming http handlers with urllib2 register_openers() data = { 'uploaded_file' : uploaded_file, 'file_name' : uploaded_file.name, 'additionalattr': 111, } datagen, headers = multipart_encode(data) headers['Authorization'] = 'Token <...>' headers['Connection']='keep-alive' urllib_request = urllib2.Request('%s/file_upload/' % ( server ), datagen, headers) json_response = json.loads(urllib2.urlopen(urllib_request).read()) return <...> When I upload I file, I get following error code caused by multipart_encode: Traceback (most recent call last): File "/Users/phoebus/Library/Python/2.7/lib/python/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/Users/phoebus/Library/Python/2.7/lib/python/site-packages/django/core/handlers/base.py", line 186, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/phoebus/Library/Python/2.7/lib/python/site-packages/django/core/handlers/base.py", line 184, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/phoebus/Library/Python/2.7/lib/python/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "/Users/phoebus/Library/Python/2.7/lib/python/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Users/phoebus/Library/Python/2.7/lib/python/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/Users/phoebus/Projects/speechanalyzerwebapp/speechanalyzerwebapp/welcome.py", line 41, in post … -
What is an advisable Vagrant box(Linux) for developing in Python(Django, Scrapy)?
I'm new to developing in windows using Vagrant so any idea will be much appreciated. What is an advisable Vagrant box(Linux) for developing in Python(Django, Scrapy)? And please can you also include the config for the VagrantFile for it for example what will be the box, url and so on. Thank you so much in advance. -
URL patterns (Django Programming)
I'm trying to generate a regex for just numbers. But for some reason the pattern doesn't seem to match. My code is: url('^[\d\-]+/$', views.room, name='room'), The request has to go to this expression. The HTML href for the above is: <href="/polls/layout/103/> -
django AbstractUser model 'str' object has no attribute '_meta'
I can not register a custom User model in the admin.py. No admin.py , all works fine Why do the customUser? I not know what this is problems. I did everything according to the documentation models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ AbstractUser._meta.get_field('email')._unique = True AbstractUser._meta.get_field('email').blank = False class User(AbstractUser): is_agency = models.BooleanField(_('agency status'), default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def get_is_agency(self): return self.is_agency admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from settings import AUTH_USER_MODEL as CustomUser admin.site.register(CustomUser, UserAdmin) Traceback Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f169c48a730> Traceback (most recent call last): File "/home/ti/PycharmProjects/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/ti/PycharmProjects/venv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/home/ti/PycharmProjects/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/home/ti/PycharmProjects/venv/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/ti/PycharmProjects/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/ti/PycharmProjects/venv/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ti/PycharmProjects/venv/lib/python3.5/site-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/home/ti/PycharmProjects/venv/lib/python3.5/site-packages/django/contrib/admin/apps.py", line 23, in ready self.module.autodiscover() File "/home/ti/PycharmProjects/venv/lib/python3.5/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "/home/ti/PycharmProjects/venv/lib/python3.5/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/home/ti/PycharmProjects/venv/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import … -
ps command cpu utilization for gunicorn always reads 0%
I am charting my CPU/MEM usage for some gunicorn workers I have running with multiple django apps and I am getting the info from the ps command I am running this... /bin/ps -C gunicorn -o pcpu -o pmem -o cmd which always outputs like this: %CPU %MEM CMD 0.0 0.5 command 0.0 0.5 command 0.0 2.2 command 0.0 0.6 command 0.0 0.7 command 0.0 0.7 command which is great but the CPU% is always at 0...even if I make my app do some CPU heavy process like pulling A LOT of info out of a postgresql database. Shouldn't the CPU% be going up when the gunicorn worker is told to do something like that? -
Django using pk like int in the view function
I am trying to make an asynchronous multiplayer game. My idea is to share a template ('play_game.html') between players. So when the player 1 has the turn, then a bottom appears and when He press It, the function play_game gets a request and a one, with this one, It adds a one to the turn so, It's renders the play_game.hmtl with the next turn to play. The problem: The game function always gets one. If I press F5 in the browser but I don't press the bottom then the value still been one. I don't know. This is the code: this is the function @login_required def play_game(request, flag): current_user = User.objects.get(user=request.user.id) game = current_user.game if int(flag) == 1: if game.turn < game.players_total: game.turn = game.turn + 1 else: game.turn = 1 game.save() turn = game.turn context = { 'current_user' : current_user, 'turn' : turn } return render(request,'play_game.html', context) This is the template play_game.html {% extends 'base.html' %} {% load staticfiles %} {% block content %} {% if current_user.turn == turn %} <p> your turn <p/> <li><a href="{% url 'play_game' flag=1 %}"> Move </a></li> {% endif %} {% endblock %} and this is the url: url(r'^game_list/join_to_game/play_game/(?P<flag>[0-9]+)/$', views.play_game, name='play_game'), The problem in … -
changing between python script and JavaScript
I'm developing a Django web application for chatting with chatbot. I used the view and it url to run the python script (so far so good). chatbot.js: //user input function insertMessage() { msg = $('.message-input').val(); if ($.trim(msg) == '') { return false;} $('<div class="message message-personal">' + msg + '</div>').appendTo($('.mCSB_container')).addClass('new'); setDate(); $('.message-input').val(null); updateScrollbar(); setTimeout(function() { chatMessage();}, 1000 + (Math.random() * 20) * 100);} $('.message-submit').click(function() { UserInput = $('.message-input').val(); var chatbot ={ user_iput: UserInput}; $.ajax({ type: "POST", url: "http://127.0.0.1:8000/chat/api/", data: chatbot,}); insertMessage();}); $(window).on('keydown', function(e) { if (e.which == 13) { UserInput = $('.message-input').val(); var chatbot ={ user_iput : UserInput}; $.ajax({ type: "POST", url: "http://127.0.0.1:8000/chat/api/", data: chatbot,}); insertMessage(); return false; }}); //chatbot repaly function chatbot_welcoming(){ var Welcoming_log = [ 'السلام عليكم، كيف استطيع خدمتك؟', 'المساعد الذكي محمد في خدمتك', 'اهلن بك، اتمنى انك بخير اليوم', 'مرحباً، مساعدك الشخصي محمد في خدمتك',]; Array.prototype.random = function () {return this[Math.floor((Math.random()*this.length))];} var chat_response = Welcoming_log.random(); return chat_response;} function get_response(){ var chat_log= $.parseJSON($.ajax({ type: "GET", url: "http://127.0.0.1:8000/chat/api/", dataType: "json", async: false}).responseText); var last = chat_log[chat_log.length - 1] return last;} var start_chatting = 0; function run_chatbot_script(){ $.ajax({ type: 'GET', url: 'http://127.0.0.1:8000/chatbot/run_python_script/',});} function chatMessage() { if ($('.message-input').val() != '') { return false;} $('<div class="message loading new"><figure class="avatar"><img src="https://s13.postimg.org/whea1mgif/icon.png" /></figure><span></span></div>').appendTo($('.mCSB_container')); updateScrollbar(); … -
Saving pandas DataFrame to database in Django
I am working on a Django project, where I need to save data from multiple pandas DataFrames into Django models. I also use MySQL to store the data. However, one of the DataFrames - df, is equivalent to the Django model/database table, where I want to store the data. So my sql-table is a one to one copy of df. df is also the largest dataframe that I have. I was thinking, if it would make sense to simply apply df.to_sql instead of saving the data through the Django model, where I have to iterate over the rows of df. I already tried it and it seems to work fine (and also fast). However, I am not sure if such an approach is good from Django's perspective, because I am saving the rest of the data through models. I would really appreciate any help or suggestions! -
Django Form getting invalid
I am newbie to Django. I have some troubles with forms after moving into new verison. Following, 1, The model class UserProfileDetails(models.Model): user = models.OneToOneField(User) profilePicture = models.ImageField('Profile Picture',upload_to='static/ProfilePic/', null=True,blank=True) def __str__(self): return self.user.username 2, The form class imageUploadForm(forms.ModelForm): class Meta: model= UserProfileDetails fields = ['user','profilePicture'] 3, And finally the view function def upload_pic(request): current_user = request.user if request.method == 'POST': form = imageUploadForm(request.POST, request.FILES) if form.is_valid(): pic = form.cleaned_data['profilePicture'] m = UserProfileDetails(user= current_user.id,profilePicture=pic) m.save() else: raise NotImplemented("What if the user doesn't have an associated profile?") return HttpResponseRedirect(reverse('polls:profile')) This code worked with Django 1.8. But after porting to Django 1.10.4, the form is getting invalid. I believe, the problem is with OneToOneField. Why this form is getting invalid? -
RQScheduler on Heroku
I'm trying to run rqscheduler with django-rq on Heroku with RedisToGo. I've implemented django-rq as described in their readme (https://github.com/ui/django-rq). I have a worker that starts an rqworker, and another worker that starts up rqscheduler using the management command suggested in the readme. The rqworker starts up successfully, but I keep running into this error with rqscheduler: redis.exceptions.ConnectionError: Error 111 connecting to localhost:6379. Connection refused. In my settings, I have this configuration for the my Redis Queues: RQ_QUEUES = { 'default': { 'HOST': 'localhost', 'PORT': 6379, 'DB': 0, 'PASSWORD': '*****', 'DEFAULT_TIMEOUT': 500, }, 'high': { 'URL': os.getenv('REDISTOGO_URL', 'redis://localhost:6379/0'), # If you're on Heroku 'DEFAULT_TIMEOUT': 500, }, 'low': { 'HOST': 'localhost', 'PORT': 6379, 'DB': 0, } } and I have this in my Procfile: web: gunicorn app.wsgi --log-file - worker: python manage.py rqworker high scheduler: python manage.py rqscheduler Any thoughts on why this might be happening? -
Why am I getting search results that do not contain my query in Haystack with Elasticsearch backend?
Description of setup and symptoms I don't think I'm setting up Elasticsearch 1.7 + django-haystack==2.5.1 up properly for what I'm trying to achieve. Let's say I have a very simple app, let's call it search_bug_repro apps/search_bug_repro/models.py from django.db import models class SearchBugRepro(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name apps/search_bug_repro/search_indexes.py from haystack import indexes from .models import SearchBugRepro class SearchBugReproIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) def get_model(self): return SearchBugRepro templates/search/indexes/search_bug_repro/searchbugrepro_text.txt {{ object.name }} config/settings HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': 'http://XXX.XXX.XXX.XXX:9200', 'INDEX_NAME': 'haystack' } } Here's how I built my index: manage.py rebuild_index WARNING: This will irreparably remove EVERYTHING from your search index in connection 'default'. Your choices after this are to restore from backups or rebuild via the `rebuild_index` command. Are you sure you wish to continue? [y/N] y Removing all documents from your index because you said so. Converted retries value: False -> Retry(total=False, connect=None, read=None, redirect=0) Starting new HTTP connection (1): XXX.XXX.XXX.XXX http://XXX.XXX.XXX.XXX:9200 "DELETE /haystack HTTP/1.1" 404 66 DELETE http://XXX.XXX.XXX.XXX:9200/haystack [status:404 request:0.013s] > None < {"error":"IndexMissingException[[haystack] missing]","status":404} All documents removed. Indexing 4 search bug repros Converted retries value: False -> Retry(total=False, connect=None, read=None, redirect=0) http://XXX.XXX.XXX.XXX:9200 "GET /haystack/_mapping HTTP/1.1" 404 66 GET http://XXX.XXX.XXX.XXX:9200/haystack/_mapping [status:404 request:0.004s] > … -
Django order by foreign key attributes but only those that were responsible for meeting the filter condition
I will start off with the caveat that I'm not confident about how to ask this question so I would be very grateful if anyone can help me word it better. I would like to order by foreign key attributes but only those foreign keys that satisfied the .filter(). Here is my example: it is a geodjango example because this is analogous to my actual problem. from django.contrib.gis.db import models as gismodels class Employee(gismodels.Model): id = gismodels.IntegerField() name = gismodels.CharField(max_length=255) etc... class Office(gismodels.Model): name = gismodels.CharField(max_length=255) geometry = gismodels.PointField(srid=4326) employees = gismodels.ManyToManyField(Employee, null=True) employee_count = gismodels.IntegerField() etc... class District(gismodels.Model): name = gismodels.CharField(max_length=255) geometry = gismodels.MultiPolygonField(srid=4326, blank=True) etc.. # Select all employees in district, ordered by the employee count of the offices within that district # Problematically employees can belong to multiple offices in many districts, # I only want to order by the employee count of the offices that actually lie within the district (so this doesn't work as it will include offices outside the district in the ordering): employees_sorted_by_office_employee_count = Employee.objects.filter(office__geometry__within=district.geometry).order_by('office__employee_count').distinct() -
Django Rest Framework partial update
I'm trying to implement partial_update with Django Rest Framework but I need some clarification because I'm stuck. Why do we need to specify partial=True? In my understanding, we could easily update Demo object inside of partial_update method. What is the purpose of this? What is inside of serialized variable? What is inside of serialized variable in partial_update method? Is that a Demo object? What function is called behind the scenes? How would one finish the implementation here? Viewset class DemoViewSet(viewsets.ModelViewSet): serializer_class = DemoSerializer def partial_update(self, request, pk=None): serialized = DemoSerializer(request.user, data=request.data, partial=True) return Response(status=status.HTTP_202_ACCEPTED) Serializer class DemoSerializer(serializers.ModelSerializer): class Meta: model = Demo fields = '__all__' def update(self, instance, validated_data): print 'this - here' demo = Demo.objects.get(pk=instance.id) Demo.objects.filter(pk=instance.id)\ .update(**validated_data) return demo -
Django 1.8 SelectFilter2 images not showing
I'm using the SelectFilter in Django admin on version 1.8. The images for the filter don't show. A bit like this issues, except this doesn't have the solution for me as this issue was just for v 1.9 https://code.djangoproject.com/ticket/26394 The last post here: https://github.com/darklow/django-suit/issues/469 helped me fix it with a hack to the SelectFilter2.js by adding in this: if (typeof admin_static_prefix == 'undefined'){ admin_static_prefix = '/xxxx/static/admin/'; } This fixes the issues but now has a hack to the js which is environment specific so really not nice. I tracked back through the code trying to find out why the admin_static_prefix wasn't being passed correctly and in the end I think it is. I can even see when the page is generated the call which I assume is made to the js. <script type="text/javascript">addEvent(window, "load", function(e) {SelectFilter.init("id_tags", "tags", 0, "/xxxx/static/admin/"); });</script> So it looks like it should be fine, but something is not working. There is another error on the page: Uncaught TypeError: Cannot read property 'id' of nullinit @ SelectFilter2.js:24(anonymous function) @ (index):547 But once I set admin_static_prefix the widget and images work fine so I'm not sure if this is a red herring or not. For ease of reference … -
How to add datetime.combine to get_context_data in ListView
in models.py class Event(models.Model): event_date= models.DateField(auto_now=False, auto_now_add=False) evet_time= models.TimeField(auto_now=False, auto_now_add=False) in view.py class EventList(FilterMixin, ListView): model = Event filter_class = EventFilter template_name = 'events/event_list.html' def get_context_data(self, *args, **kwargs): context = super(EventList, self).get_context_data(*args, **kwargs) context["filter_form"] = EventFilter(data=self.request.GET or None) return context need to add next values to context. context["now"] = datetime.utcnow() + timedelta(hours=1)- work fine context["event_date_time"] - how to combine date and time from db table? Trying next: context["event_date_time"] = datetime.combine(self.event_date, self.event_time) Don't work. Thx for help. -
Django on Apache2, django-wkhtmltopdf without celery run shell subprocess
In the past in order to make any os binary calls from Django over WSGI on Apache2 with a Debian server, I've had to use celeryd to queue the message, open a subprocess (Apache2 would not create a new child process for security reasons, but maybe there was another way - I couldn't seem to find one and this worked). I found django-wkhtmltopdf wrapper and it works perfectly for my situation, run from the shell. When I run it from the web page, however, it gives me a CalledProcessError: Command returned non-zero exit status 1 with no other details in the logs or in the traceback. Is this the same issue? Apache2 cannot call the subprocess for wkhtmltopdf because Apache2 is not allowing a child process? Thanks for your help or any guidance where I can find some! -
Can't import a module in python 2.7 even though pip says it is installed
I've read the many posts on SO regarding using Pillow or Image instead of PIL but I'm still having trouble with this module. I'm running this on my MBP on 10.9.5. I used pip to install image 1.5.5 and Pillow 3.4.2. However, when I go to import the module in my script, it keeps saying there's no module of that name. first.last@localhost:/usr/local/bin> pip freeze | grep Pillow Pillow==3.4.2 first.last@localhost:/usr/local/bin> pip freeze | grep image image==1.5.5 first.last@localhost:/usr/local/bin> which pip /usr/local/bin/pip first.last@localhost:/usr/local/bin> which python /usr/local/bin/python Python 2.7.10 (v2.7.10:15c95b7d81dc, May 23 2015, 09:33:12) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import image Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named image >>> import PIL Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named PIL >>> import Pillow Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named Pillow >>> import pillow Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named pillow I checked /Library/Python/2.7/site-packages and it doesn't seem like the .py files are there for pillow …