BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

Image Files Uploading Example on a Shared Host

django.png




Bookmark and Share





bogotobogo.com site search:




Note

We start from where we left off (Need a minimal Django file upload example). The difference is we do it on a shared host not a on a local host.


Image_Upload_Local_Results.png

With small changes, the source code we used on a local host in previous chapter, we'll deploy it to a shared host running Django 1.6.5:

$ python -c "import django; print(django.get_version())"
1.6.5

The changes are:

  1. db: from sqlite to mysql
  2. urls.py
  3. Images files will be saved into media/documents which is a sub-diretory of the document root directory (www/dj). Note that we set:
    MEDIA_ROOT = '/home2/bogotob1/www/dj/media/'
    MEDIA_URL = 'http://www.bogotobogo.com/dj/media/'
    
    in settings.py.




Shared host setup
  1. .htaccess

    We need to create .htaccess file under the root directory of our Django project which is ~/public_html/djangoproject:

    $ cd ~/public_html/djangoproject
    

    Add the following to .htaccess:

    AddHandler fcgid-script .fcgi
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ mysite.fcgi/$1 [QSA,L]
    
  2. djangoproject.fcgi

    ~/public_html/djangoproject/djangoproject.fcgi file should look like this:

    #!/home/directory/bin/python
    import sys, os
    
    sys.path.insert(0, "/home/directory/python")
    sys.path.insert(13, "/home/directory/djangoproject")
    
    os.environ['DJANGO_SETTINGS_MODULE'] = 'djangoproject.settings'
    from django.core.servers.fastcgi import runfastcgi
    runfastcgi(method="threaded", daemonize="false")
    



Project and App Trees
  1. project: djangoproject
    tree_project.png

  2. app: myapp
    tree_app.png

  3. document root: www/dj
    tree_dj.png

    When we do upload an image file, it will be saved into ~/www/dj/media/documents. Note that we created the two directories (media and documents) before the upload.





Settings: myproject/settings.py

We need to set the database we're going to use. In this example for shared host, we'll use mysql:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'bogotob1_djforum',
        'USER': 'bogotob1_djforum',
        'PASSWORD': 'my_password',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    }
}

To upload files and to serve them, we want to specify where Django stores uploaded files and from what URL Django serves them via two variables in settings.py: MEDIA_ROOT and MEDIA_URL. They are by default empty:

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home2/media/media.lawrence.com/media/"
MEDIA_ROOT = '/home2/bogotob1/www/dj/media/'

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = 'http://www.bogotobogo.com/dj/media/'

Then, we also need to add myapp to INSTALLED_APPS:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
)




Model: myproject/myapp/models.py

Now we need a model with a FileField. This field stores files e.g. to media/documents/2014/07/06/ based on current date and MEDIA_ROOT. See FileField reference:

class FileField([upload_to=None, max_length=100, **options])

Our code:

from django.db import models

class Document(models.Model):
    docfile = models.FileField(upload_to='documents/%Y/%m/%d')

If our MEDIA_ROOT is set to /home2/bogotob1/www/dj/media/, and upload_to is set to documents/%Y/%m/%d. The %Y/%m/%d part of upload_to is strftime() formatting; %Y is the four-digit year, %m is the two-digit month and %d is the two-digit day. If we upload a file on July 06, 2014, it will be saved in the directory /home2/bogotob1/www/dj/media/documents/2014/07/06





Form: myproject/myapp/forms.py

To handle upload properly, we need a form. This form has only one field because of our minimal approach. See Form FileField reference for details:

class FileField(**kwargs)

Our code:

from django import forms

class DocumentForm(forms.Form):
    docfile = forms.FileField(
        label='Select a file',
    )

This defines a Form class with a single field (docfile) of FileField.





View: myproject/myapp/views.py

Our code:

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

from myproject.myapp.models import Document
from myproject.myapp.forms import DocumentForm

def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'])
            newdoc.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
    else:
        form = DocumentForm() # A empty, unbound form

    # Load documents for the list page
    documents = Document.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'myapp/list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )

def index(request):
    return render_to_response('myapp/index.html')

request.FILES['docfile'] can be saved to models.FileField. The model's save() handles the storing of the file to the filesystem automatically.





Project URLs: myproject/urls.py

"Django does not serve MEDIA_ROOT by default. That would be dangerous in production environment. But in development stage, we could cut short. Pay attention to the last line. That line enables Django to serve files from MEDIA_URL. This works only in development stage." - from Need a minimal Django file upload example.

from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import RedirectView
from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
        (r'^myapp/', include('myapp.urls')),
) 

See django.conf.urls.static.static and Django: how do you serve media / stylesheets and link to them within templates.





App URLs: myapp/urls.py
from django.conf.urls import patterns, include, url

urlpatterns = patterns('myapp.views',
    url(r'^$', 'list', name='list'),
    url(r'^list/$', 'list', name='list'),
)




Template: myproject/myapp/templates/myapp/list.html

In this section, we have a template for the list and an upload form. The form must have enctype attribute set to multipart/form-data and method set to post to make upload to Django possible. See File Uploads documentation for details.

The FileField has many attributes that can be used in templates. E.g. {{ document.docfile.url }} and {{ document.docfile.name }} as in the template. See more about these in Using files in models article and The File object documentation.

<!DOCTYPE html>
<html>
        <head>
                <meta charset="utf-8">
                <title>Minimal Django File Upload Example</title>
        </head>

        <body>
                <!-- List of uploaded documents -->
                {% if documents %}
                        <ul>
                        {% for document in documents %}
                                <li><a href="{{ document.docfile.url }}">{{ document.docfile.name }}
                                <img src="{{ document.docfile.url }}" alt="{{ document.docfile.name }}">
                                </a></li>
                        {% endfor %}
                        </ul>
                {% else %}
                        <p>No documents.</p>
                {% endif %}

                <!-- Upload form. Note enctype attribute! -->
                <form action="{% url "list" %}" method="post" enctype="multipart/form-data">
                        {% csrf_token %}
                        <p>{{ form.non_field_errors }}</p>
                        <p>{{ form.docfile.label_tag }} </p>
                        <p>
                                {{ form.docfile.errors }}
                                {{ form.docfile }}
                        </p>
                        <p><input type="submit" value="Upload" /></p>
                </form>

        </body>

</html>




syncdb

In ~/djangoproject directory:

$ python manage.py syncdb




The files

Here is the archive of the source code: myapp.tar.gz.














Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







Django 1.8



Introduction - Install Django and Project Setup

Creating and Activating Models

Hello World A - urls & views

Hello World B - templates

Hello World C - url dispatcher

Hello World D - Models and SQLite Database

MVC - Hello World

Hello World on a Shared Host A

Hello World on a Shared Host B

Hello World - Admin Site Setup

virtualenv

Creating test project on virtualenv

Test project's settings.py

Creating Blog app and setting up models

Blog app - syncdb A

Blog app - syncdb B

Blog app - views and urls

Blog app - templates

Blog app - class based templates

Image upload sample code - local host

Authentication on Shared Host using FastCGI

User Registration on Shared Host A

User Registration with a Customized Form on Shared Host B

Blogs on Shared Host

Serving Django app with uWSGI and Nginx

Image upload sample code - shared host

Managing (Deploying) Static files (CSS, Images, Javascript) on Shared Host

Forum application on a Shared Host

Django Python Social Auth : Getting App ID (OAuth2) - Facebook, Twitter, and Google

Django: Python social auth, Facebook, Twitter, and Google Auth

Django: Python social auth, Facebook, Twitter, and Google Auth with Static files

...

Django 1.8 hosted on Linode VPS ==>

1. Setup CentOS 7 hosted on VPS

1B. Setup CentOS 7 hosted on VPS (multi-domain hosting setup) - Name server and Zone File settings (from GoDaddy to Linode)

2. ssh login and firewall

3. Apache Install

4. Install and Configure MariaDB Database server & PHP

5. Install and Configure Django

6. Model

7. Model 2 : populate tables, list_display, and search_fields

8. Model 3 (using shell)

9. Views (templates and css)

10. Views 2 (home page and more templates)

11. TinyMCE

12. TinyMCE 2

13. ImageField/FileField : Serving image/video files uploaded by a user

14. User Authentication 1 (register & forms)

15. User Authentication 2 (login / logout)

16. User Authentication 3 (password reset) - Sent from Email (gmail) setup etc.

17. User Authentication 4 (User profile & @login_required decorator)

18. User Authentication 5 (Facebook login)

19. User Authentication 6 (Google login)

20. User Authentication 7 (Twitter login)

21. User Authentication 8 (Facebook/Google/Twitter login buttons)

22. Facebook open graph API timeline fan page custom tab 1

23. Facebook Open Graph API Timeline Fan Page Custom Tab 2 (SSL certificate setup)

24. Facebook open graph API timeline fan page custom tab 3 (Django side - urls.py, settings.py, and views.py)

...

A sample production site Django 1.8.7: sfvue.com / einsteinish.com ==>

A sample production app (sfvue.com) with virtualenv and Apache

2. Upgrading to Django 1.8.7 sfvue.com site sample with virtualenv and Apache

(*) Django 1.8.7 einsteinish.com site - errors and fixes

Django 1.8.12 pytune.com site - local with Apache mod_wsgi

Django 1.8.12 pytune.com site - local with Nginx and uWSGI

Django 1.8.12 pytune.com site - deploy to AWS with Nginx and uWSGI

Django Haystack with Elasticsearch and Postgres

Django Compatibility Cheat Sheet

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






Python tutorial



Python Home

Introduction

Running Python Programs (os, sys, import)

Modules and IDLE (Import, Reload, exec)

Object Types - Numbers, Strings, and None

Strings - Escape Sequence, Raw String, and Slicing

Strings - Methods

Formatting Strings - expressions and method calls

Files and os.path

Traversing directories recursively

Subprocess Module

Regular Expressions with Python

Regular Expressions Cheat Sheet

Object Types - Lists

Object Types - Dictionaries and Tuples

Functions def, *args, **kargs

Functions lambda

Built-in Functions

map, filter, and reduce

Decorators

List Comprehension

Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism

Hashing (Hash tables and hashlib)

Dictionary Comprehension with zip

The yield keyword

Generator Functions and Expressions

generator.send() method

Iterators

Classes and Instances (__init__, __call__, etc.)

if__name__ == '__main__'

argparse

Exceptions

@static method vs class method

Private attributes and private methods

bits, bytes, bitstring, and constBitStream

json.dump(s) and json.load(s)

Python Object Serialization - pickle and json

Python Object Serialization - yaml and json

Priority queue and heap queue data structure

Graph data structure

Dijkstra's shortest path algorithm

Prim's spanning tree algorithm

Closure

Functional programming in Python

Remote running a local file using ssh

SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table

SQLite 3 - B. Selecting, updating and deleting data

MongoDB with PyMongo I - Installing MongoDB ...

Python HTTP Web Services - urllib, httplib2

Web scraping with Selenium for checking domain availability

REST API : Http Requests for Humans with Flask

Blog app with Tornado

Multithreading ...

Python Network Programming I - Basic Server / Client : A Basics

Python Network Programming I - Basic Server / Client : B File Transfer

Python Network Programming II - Chat Server / Client

Python Network Programming III - Echo Server using socketserver network framework

Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn

Python Coding Questions I

Python Coding Questions II

Python Coding Questions III

Python Coding Questions IV

Python Coding Questions V

Python Coding Questions VI

Python Coding Questions VII

Python Coding Questions VIII

Python Coding Questions IX

Python Coding Questions X

Image processing with Python image library Pillow

Python and C++ with SIP

PyDev with Eclipse

Matplotlib

Redis with Python

NumPy array basics A

NumPy Matrix and Linear Algebra

Pandas with NumPy and Matplotlib

Celluar Automata

Batch gradient descent algorithm

Longest Common Substring Algorithm

Python Unit Test - TDD using unittest.TestCase class

Simple tool - Google page ranking by keywords

Google App Hello World

Google App webapp2 and WSGI

Uploading Google App Hello World

Python 2 vs Python 3

virtualenv and virtualenvwrapper

Uploading a big file to AWS S3 using boto module

Scheduled stopping and starting an AWS instance

Cloudera CDH5 - Scheduled stopping and starting services

Removing Cloud Files - Rackspace API with curl and subprocess

Checking if a process is running/hanging and stop/run a scheduled task on Windows

Apache Spark 1.3 with PySpark (Spark Python API) Shell

Apache Spark 1.2 Streaming

bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...

Flask app with Apache WSGI on Ubuntu14/CentOS7 ...

Selenium WebDriver

Fabric - streamlining the use of SSH for application deployment

Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App

Neural Networks with backpropagation for XOR using one hidden layer

NLP - NLTK (Natural Language Toolkit) ...

RabbitMQ(Message broker server) and Celery(Task queue) ...

OpenCV3 and Matplotlib ...

Simple tool - Concatenating slides using FFmpeg ...

iPython - Signal Processing with NumPy

iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github

iPython and Jupyter Notebook with Embedded D3.js

Downloading YouTube videos using youtube-dl embedded with Python

Machine Learning : scikit-learn ...

Django 1.6/1.8 Web Framework ...









Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master