Tuesday, June 10, 2014

Ajax Json Html Form Submission

<html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
        <script type="text/javascript" src="/site_media/js/jquery.cookie.js"></script></javascript>
       <script type="text/javascript" src="/site_media/js/ms-Dropdown-master/js/msdropdown/jquery.dd.js"></script>
        <link rel="stylesheet" href="/site_media/js/ms-Dropdown-master/css/msdropdown/dd.css">
    </head>

    <body>
        <script type="text/javascript">
            var imagesCombo;
            var categoriesCombo;
            var catOptionJson;
            var imagesOptionJson;
            var categoriesOptionJson;
            var jsonData;

            $(document).ready(function()
            {
                $("body select").msDropDown();
                var csrftoken = $.cookie('csrftoken');

                function csrfSafeMethod(method)
                {
                    // these HTTP methods do not require CSRF protection
                    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
                }

                function sameOrigin(url)
                {
                    // test that a given url is a same-origin URL
                    // url could be relative or scheme relative or absolute
                    var host = document.location.host; // host + port
                    var protocol = document.location.protocol;
                    var sr_origin = '//' + host;
                    var origin = protocol + sr_origin;
                    // Allow absolute or scheme relative URLs to same origin
                    return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
                            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
                        // or any other URL that isn't scheme relative or absolute i.e relative.
                            !(/^(\/\/|http:|https:).*/.test(url));
                }

                $.ajaxSetup(
                        {
                            beforeSend: function(xhr, settings)
                            {
                                if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url))
                                {
                                    // Send the token to same-origin, relative URLs only.
                                    // Send the token only if the method warrants CSRF protection
                                    // Using the CSRFToken value acquired earlier
                                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                                }
                            }
                        });

                console.log('Before Image Edit Form POST');
                $("#ImageAssignmentForm").submit(function(event)
                {
                    console.log($("#ImageAssignmentForm").serialize())
                    event.preventDefault();
                    $.ajax(
                    {
                        type:"POST",
                        url:"/UploadImages/ImageAssignSubmit/",
                        dataType: "json",
                        data: $("#ImageAssignmentForm").serialize(),
                        success: function(json)
                        {
                            count = 0;
                            $.each( json, function(key, value)
                            {
                                console.log( key, value.fields );
                                count++;
                            });
                        }
                    });
                });

                console.log('Before Image Edit Form GET');
                $.ajax(
                        {
                            type:"GET",
                            url:"/UploadImages/ImageEditJson/",
                            dataType: "json",
                            success: function(json)
                            {
                                count = 0;
                                console.log(json);
                                jsonData = json;

                                for (var countRemove = 0; countRemove < imagesCombo.length; countRemove++)
                                {
                                    imagesCombo.remove(0);
                                    // console.log(countRemove);
                                }

                                for (var countRemove = 0; countRemove < categoriesCombo.length; countRemove++)
                                {
                                    categoriesCombo.remove(0);
                                    // console.log(countRemove);
                                }

                                $.each( json, function(key, value)
                                {
                                    if ( value.model == 'upload_images_app.image' )
                                    {
                                        imagesOptionJson = {value:value.pk, image:value.fields.thumbnail_image_location};
                                        imagesCombo.add(imagesOptionJson);
                                    }
                                    if ( value.model == 'main_app.category' )
                                    {
                                        // Remove Date Renew After Everything Is Working.
                                        catOptionJson = {value:value.pk, text:value.fields.category};
                                        console.log("categories");
                                        console.log(catOptionJson);
                                        categoriesCombo.add(catOptionJson);
                                    }
                                });
                                imagesCombo.set("selectedIndex", 0);
                                categoriesCombo.set("selectedIndex", 0);
                            }
                        });
                $("body select").msDropDown();
                imagesCombo = $("#id_thumbnail_image_location_id").msDropDown().data("dd");
                categoriesCombo = $("#id_category").msDropDown().data("dd");
            });
        </script>

        <h2>Image Upload And Edit</h2>
        {% if form.errors %}
            <p style="color: red;">
                Please correct the error{{form.error|pluralize}} below.
            </p>
        {% endif %}

        <form id="ImageAssignmentForm" action="." method="post">
            {% csrf_token %}
            <p>
                <label for="id_category">Category:</label>
                <select style="width:500px;" name="category" id="id_category" class="mydds" onchange="showValue(this.value)">
                </select>
            </p>

            <p>
                <label for="id_thumbnail_image_location_id">Image Gallery:</label>
                <select style="width:130px;" name="thumbnail_image_location_id" id="id_thumbnail_image_location_id" class="mydds" onchange="showValue(this.value)">
                </select>
            </p>
            <input type="submit" value="Assign Image To Category" />
        </form>
    </body>
</html>

Upload html file

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Image Upload</title>

        <!--<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script></javascript> -->
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
        <script type="text/javascript" src="/site_media/js/sha1.js"></script>
        <script type="text/javascript" src="/site_media/js/jquery.cookie.js"></script></javascript>

        <script type="text/javascript">
            $(document).ready(function()
            {
                $('#ImageInfo').html('testing testing').show();
                $('#ImageInfo').load('/UploadImages/ImageEdit/');
            });
        </script>

    </head>

    <body>
        <!-- Image Assignment To Locations -->
        <div id="ImageInfo">
            Working?

            <div id="ImageEditResults">

            </div>

        </div>

        <!-- List of uploaded documents -->
        {% if UploadImageFile %}
            <ul>
            {% for image in UploadImageFile %}
                <li><a href="{{ UploadImageFile.image_file.url }}">{{ UploadImageFile.image_file.name }}</a></li>
            {% endfor %}
            </ul>
        {% else %}
            <p>No images.</p>
        {% endif %}

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

</html>

Admin

from django.contrib import admin
from example.image_app.models import Image

# Register your models here.
admin.site.register(Image)

Upload Form

from django import forms
from example.main_app.models import Category
from example.images_app.models import Image
from django.contrib.auth.models import User

class UploadImageForm(forms.Form):
    image_file = forms.ImageField(
        label='Select an image',
        help_text='max. 42 megabytes'
    )

Django Upload Models

import os
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from django.forms import ModelForm
from exmaple.main_app.models import Category

def get_image_path(instance, filename):
    return os.path.join('../media/UploadImages', instance.user.username, filename)

class UploadImageFile(models.Model):
    name = models.CharField(max_length=200)
    user = models.ForeignKey(User)
    # image_file = models.FileField( upload_to=get_image_path)
    image_file = models.ImageField( upload_to=get_image_path)

class Image(models.Model):
    category = models.ManyToManyField(Category, blank=True)
    image_location = models.URLField(max_length=500, blank=True)
    midsize_image_location = models.URLField(max_length=500, blank=True)
    thumbnail_image_location = models.URLField(max_length=500, blank=True)
    title = models.CharField(max_length=100, blank=True)
    description = models.CharField(max_length=500, blank=True)
    enabled = models.BooleanField(default=True)

    def __str__(self):
        return '%s %s, %s, %s, %s' % (self.category, self.image_location, self.thumbnail_image_location, self.title, self.description)

class ImageForm(ModelForm):
    class Meta:
        model = Image

View Ajax Json

from django.shortcuts import render

from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.core import serializers

from example.my_app.models import Example

def example_cat(request, in_category):
    examples = list( Example.objects.filter(category = in_category) )
    variables = RequestContext( request,
        {
            'examples': examples,
        })
    return render_to_response('Example/Example.html', variables)

def example_cat_json(request, in_category):
    try:
        examples = list( Example.objects.filter(category = in_category) )
        data = serializers.serialize('json', examples)
        print data
        return HttpResponse(data, mimetype='application/javascript')
    except Category.DoesNotExist:
        print "Error: Category does not exist."
        message = "Error: Category does not exist."
        return HttpResponse(message)

Urls Main To App Urls

# example.com urls.py
import os.path
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.conf import settings

from django.contrib import admin

site_media = os.path.join(os.path.dirname(__file__), 'site_media')

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', include('bedeckedinbeads.main_app.urls')),
    url(r'^admin/', include(admin.site.urls)),
    (r'^My/', include('example.my_app.urls')),
    (r'^login/$', 'django.contrib.auth.views.login'),
    (r'^logout/$', 'django.contrib.auth.views.logout'),
    (r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
     { 'document_root': site_media }),

) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

# my_app urls.py

urlpatterns = patterns('example.my_app.views',
    url(r'^Gallery/$', 'product_gallery', name='product_gallery'),
    url(r'^Category/(?P<productID>\d+)/$', 'product_gallery_cat', name='product_gallery_cat'),
    url(r'^CategoryName/(?P<in_category>\w+)/$', 'product_gallery_cat_name', name='product_gallery_cat_name'),
)

WSGI.py

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os, sys

#################################################################################
#                                   Logging                                     #
#################################################################################
import logging
logger =logging.getLogger("")
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stderr)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(levelname)-8s %(messages)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

sys.stdout = sys.stderr

#################################################################################
#                        Setting Environment Application                        #
#################################################################################
sys.path.append('/usr/local/lib/python2.7/dist-packages/django')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example.settings")

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

Ubuntu Configuration Example

<VirtualHost *:80>
        ServerName example.com
        ServerAlias www.example.com

        WSGIDaemonProcess natenesler.com python-path=/home/ubuntu/public_html/example.com/example:/usr/local/lib/python2.7/site-packages/
        WSGIProcessGroup example.com

        # AliasMatch ^/([^/]*\.css) /home/ubuntu/public_html/example.com/example/example/static/styles/$1

        Alias /media/ /home/ubuntu/public_html/example.com/example/example/media/
        Alias /static/ /home/ubuntu/public_html/example.com/example/example/static/

        <Directory /home/ubuntu/public_html/example.com/example/example/static>
          <IfVersion < 2.3 >
               Order allow,deny
               Allow from all
          </IfVersion>
          <IfVersion >= 2.3>
               Require all granted
          </IfVersion>               
        # Order deny,allow
                # Allow from all
                # Apache 2.4 requires following below in place of
                # Allow from all
                # Require all granted
        </Directory>

        <Directory /home/ubuntu/public_html/example.com/example/example/media>
                <IfVersion < 2.3 >
                        Order allow,deny
                        Allow from all
                </IfVersion>
                <IfVersion >= 2.3>
                        Require all granted
                </IfVersion>               
                # Order deny,allow
                # Allow from all
                # Apache 2.4 requires following below in place of
                # Allow from all
                # Require all granted
        </Directory>

        WSGIScriptAlias / /home/ubuntu/public_html/example.com/example/example/apache/wsgi.py

        <Directory /home/ubuntu/public_html/example.com/example/example/apache>
                <Files wsgi.py>
                    <IfVersion < 2.3 >
                            Order allow,deny
                            Allow from all
                        </IfVersion>
                    <IfVersion >= 2.3>
                            Require all granted
                    </IfVersion>               
                        # Order allow,deny
                    # Allow from all
                        # Apache 2.4 requires following below in place of
                        # Allow from all
                        # Require all granted
                </Files>
        </Directory>


        ErrorLog ${APACHE_LOG_DIR}/error-example.com.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog ${APACHE_LOG_DIR}/access-example.com.log combined

    Alias /doc/ "/usr/share/doc/"
    <Directory "/usr/share/doc/">
        Options Indexes MultiViews FollowSymLinks
        AllowOverride None
        <IfVersion < 2.3 >
            Order allow,deny
            Allow from all
        </IfVersion>
        <IfVersion >= 2.3>
            Require all granted
        </IfVersion>               
        # Order deny,allow
        # Deny from all
        # Allow from 127.0.0.0/255.0.0.0 ::1/128
    </Directory>
</VirtualHost>

Django Installs Ubuntu

# Setting Up A LAMP Django Server Or LAM if you want to think of it that way
#!/bin/bash

# Installing Python
sudo apt-get -y install python
sudo apt-get -y install python-dev

# Installing easy_install for python Django Apps.
sudo apt-get -y install python-setuptools
# Python pip install for Django Apps
sudo apt-get -y install python-pip

sudo apt-get -y install mysql-server
sudo apt-get -y install python-mysqldb
sudo apt-get -y install apache2 libapache2-mod-python
sudo apt-get -y install mysql-server python-mysqldb
sudo apt-get -y install libapache2-mod-wsgi

# Add meta data into ogv ogg videos DURATION: 30.03 for example
# oggz-comment video.ogv -l DURATION: 30.03
sudo apt-get install -y oggz-tools
sudo apt-get -y install ffmpeg
sudo add-apt-repository  ppa:stebbins/handbrake-releases
sudo apt-get update
sudo apt-get -y install handbrake-cli
sudo apt-get -y install ffmpeg2theora
sudo apt-get install gifsicle

sudo pip install PIL
sudo pip install --upgrade PIL

sudo easy_install paramiko
sudo easy_install django-filer
sudo easy_install django-celery
sudo easy_install django_appmedia
sudo easy_install --upgrade pycrypto
sudo easy_install easy-thumbnails
sudo easy_install django-multimedia

sudo apt-get -y install apache2-mpm-worker apache2-dev
sudo easy_install virtualenv virtualenvwrapper pip

sudo apt-get build-dep python-imaging
sudo apt-get -y install libjpeg62 libjpeg62-dev 
sudo apt-get -y install libfreetype6 libfreetype6-dev 
sudo apt-get -y install libfreetype6 libfreetype6-dev zlib1g-dev 
sudo apt-get -y install libjpeg8 libjpeg8-dev

# Installing Django Merchant
#/usr/local/lib/python2.7/dist-packages/django_merchant-0.0.3a0-py2.7.egg
sudo easy_install django-merchant

# Google Wallet Payment System For Django
sudo pip install django-payments

# Installing Boto for AWS Services such as FPS and S3 etc.
sudo easy_install boto

# Installing FFMPEG Video Encoding for Django.
sudo apt-get -y install ffmpeg
sudo apt-get -y install python-dev
sudo easy_install paramiko
sudo easy_install django-filer
sudo easy_install django-celery
sudo easy_install django_appmedia
sudo easy_install --upgrade pycrypto
sudo easy_install easy-thumbnails
sudo easy_install django-multimedia

# Installing Django Admin Tools Dashboard
sudo easy_install -Z django-admin-tools

# Install Easy Maps Google Maps For Django
sudo easy_install geopy
sudo easy_install django-easy-maps

# S3 Storages
sudo easy_install django-storages

# MySQL Python Module
sudo easy_install MySQL-python

# Install Django User Email Verficiation Registration System.
sudo easy_install django-registration

# Install Django JQuery File Upload System.
sudo easy_install django-jquery-file-upload
sudo easy_install pillow

sudo apt-get remove libapache2-mod-python
sudo apt-get -y install libapache2-mod-wsgi
# sudo echo "LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so" > /etc/apache2/mods-available/wsgi.load
sudo a2enmod wsgi
sudo service apache2 restart

# XML Processing
sudo easy_install elementtree

Helpful Django Commands

# Django Basic Helpful Commands
#!/bin/bash
# Sync Database
python manage.py syncdb

# Run Debug Server
python manage.py runserver

# Validating The Database
python manage.py validate

# See the SQL statments used to generate the database tables.
python manage.py sqlall app_name

# Creates a new app. Be sure to add it to the settings.py file and also to the urls.py file.
python manage.py startapp appname

# Debug Django Page Location
http://localhost:8000/

# Install Django
sudo python setup.py install

sudo apt-get install python-django

# Django Verison
django-admin.py --version

# Create A New Django Project
django-admin.py startproject project_name

# Create A New Django App
django-admin.py startapp app_name

# urls.py patterns
.    # Any character
^    # Start of a string
$    # End of a string
*    # 0 or more repetitions
+    # 1 or more repetitions
?    # 0 or 1 repetitions
|    # A | B means A or B
[a-z]    # Any lowercase character
\w    # Any alphanumeric character or _
\d    # Any digit

# Display SQL Statements Out Of Django
python manage.py sql folder_name_that_conatins_model.py

# Django Python Interactive Shell
python manage.py shell

# Django Python Sphinx Search Configuration File Generate
python manage.py generate_sphinx_config MyApp >> sphinx.conf

# Installing easy_install for python Django Apps.
sudo apt-get install python-setuptools

Licenses

LGPL / GPL:
https://www.gnu.org/licenses/lgpl.html

Updates To Django 1.6

quotes around the view name in templates:
http://stackoverflow.com/questions/15974905/url-requires-a-non-empty-first-argument-the-syntax-changed-in-django-1-5-see


Django Apps

Google Waller:
http://django-payments.readthedocs.org/en/latest/modules.html#google-wallet
http://django-payments.readthedocs.org/en/latest/usage.html

Django Social Auth:
https://github.com/omab/django-social-auth

Django Social Registration:
https://github.com/flashingpumpkin/django-socialregistration

Sending Email:
https://docs.djangoproject.com/en/dev/topics/email/

Ajax Form Submission:
http://www.micahcarrick.com/ajax-form-submission-django.html

Dynamic Formset:
https://github.com/elo80ka/django-dynamic-formset/tree/master/demo/example

Django Forms Utils:
https://bitbucket.org/carljm/django-form-utils/src

Libav Video Conversion Replaces FFMPEG:
http://libav.org/documentation.html
http://roxlu.com/2014/039/decoding-h264-and-yuv420p-playback
http://roxlu.com/2013/002/converting-video-audio-using-avconv
http://en.flossmanuals.net/ogg-theora/command-line-editing/analysing-ogg/

http://www.xiph.org/oggz/

Gifsicle:
http://www.lcdf.org/gifsicle/
http://nullprogram.com/blog/2012/04/10/
http://www.lcdf.org/gifsicle/man.html

Django Packages:
https://www.djangopackages.com

Django Cart:  Super Simple Cart System:  You will have to develop it further.  Great start for custom solutions.
https://code.google.com/p/django-cart/

Django Shop Area Tax:
https://github.com/Lacrymology/django-shop-area-tax

Language Pack For Django Shop Area Tax 
https://github.com/Lacrymology/django-shop-l10n

Django Email Registration:
https://github.com/matthiask/django-email-registration
https://github.com/bitmazk/django-registration-email


Django Reference

Django Reference:

Urls:
https://docs.djangoproject.com/en/1.6/ref/urls/

Database ORM:
https://docs.djangoproject.com/en/dev/topics/db/queries/#limiting-querysets

In [19]: import logging                                 
In [20]: l = logging.getLogger('django.db.backends')    
In [21]: l.setLevel(logging.DEBUG)                      
In [22]: l.addHandler(logging.StreamHandler())      
In [23]: User.objects.all().order_by('-id')[:10]          
(0.000) SELECT "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user" ORDER BY "auth_user"."id" DESC LIMIT 10; args=()
Out[23]: [<User: hamdi>]
 
Query Sets:
https://docs.djangoproject.com/en/dev/ref/models/querysets/
 
Many To Many:
https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/
 
Queries:
https://docs.djangoproject.com/en/dev/topics/db/queries/ 
 
Fields:
https://docs.djangoproject.com/en/dev/ref/models/fields/ 
 
Query Managers:
Meta Class:
Models With Meta:
Meta Classes In More Depth:
Templates:
https://docs.djangoproject.com/en/1.6/topics/templates/
Built In Template Tags:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/ 

Python Lists:
http://effbot.org/zone/python-list.htm

Settings:
https://docs.djangoproject.com/en/1.5/ref/settings/

Forms:
https://docs.djangoproject.com/en/dev/topics/forms/
Widgets Forms:
https://docs.djangoproject.com/en/dev/ref/forms/widgets/

Class Views Mixins Django 1.6:
http://djbook.ru/rel1.6/topics/class-based-views/mixins.html

Http Response Redirect Reverse:
http://stackoverflow.com/questions/11183704/how-to-correctly-do-httpresponseredirect-with-reverse

Url Resolver Utility Functions:
https://docs.djangoproject.com/en/dev/ref/urlresolvers/

Statics:
https://docs.djangoproject.com/en/dev/howto/static-files/

Resources:
https://code.djangoproject.com/wiki/DjangoResources

Reusable App Development:
https://docs.djangoproject.com/en/1.6/intro/reusable-apps/

Django App Part 1:
https://docs.djangoproject.com/en/dev/intro/tutorial01/

Django App Part 2: Administration Page:
https://docs.djangoproject.com/en/1.6/intro/tutorial02/

Django App Part 03 : Urls And Views:
https://docs.djangoproject.com/en/1.6/intro/tutorial03/

Django App Part 04: Forms And Views:
https://docs.djangoproject.com/en/1.6/intro/tutorial04/

Django App Part 05: Testing:
https://docs.djangoproject.com/en/1.6/intro/tutorial05/

Django App Part 06: Look And Fell Custimization:
https://docs.djangoproject.com/en/1.6/intro/tutorial06/

Django Admin Commands:
https://docs.djangoproject.com/en/dev/howto/custom-management-commands/

Django User Auth:
https://docs.djangoproject.com/en/1.6/topics/auth/#module-django.contrib.auth

Django User Auth Apache:
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/apache-auth/

Django Internationalization:
https://docs.djangoproject.com/en/dev/topics/i18n/translation/ 

Django Main Page:
https://www.djangoproject.com/