A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

WordPress: Post Types and Page Templates

Aside from the normal “Add Post” link in the WP-Admin Panel, you can add a custom post type. See http://codex.wordpress.org/Post_Types#Custom_Types.

For example, if you want to add “Videos and Podcasts” as another post type, you put this in your functions.php file:

register_post_type('videos_and_podcasts', array(
	'label' => __('Videos and Podcasts'),
	'singular_label' => __('Video/Podcast'),
	'public' => true,
	'show_ui' => true,
	'capability_type' => 'post',
	'hierarchical' => false,
	'rewrite' => false,
	'query_var' => false,
	'supports' => array('title', 'editor', 'author')
));

More details on the options can be found here.

You should be able to see something like this in your WP-Admin:

Your new custom post type is just like a normal post type.

Combining a custom post type with a Page Template

You can take things further by combining the custom page type with a Page Template. You simply have to create a PHP file that looks like this:

<?php
/*
Template Name: Landing Page Test
*/
?>
    <?php get_header(); ?>
    <h1>This is a test landing page</h1>
    <?php
    $args = array( 'post_type' => 'videos_and_podcasts', 'posts_per_page' => 10 );
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
    	the_title();
    	echo '<div class="entry-content">';
    	the_content();
    	echo '</div>';
    endwhile;
    ?>
 
    <?php get_footer(); ?>
<?php wp_footer(); ?>

In your WP-Admin, when you try to add a Page, you should be able to see something like this:
.

There you have it, a Page Template combined with a custom post type to display a different “frontpage” / “landing page”.

Posted in General | Tagged , , , , | Leave a comment

Django: Creating multiple select checkboxes with Forms

I got stuck for almost an hour trying to create a multiple select checkbox. Here is how to do it:

First, I put this in my forms.py

class UserlistForm(forms.Form):
    users = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,label="Notify and subscribe users to this post:")

Then in my views.py I have something like this:

def post_message(request, groupid):
    custgroup = Group.objects.get(id=groupid)
    groupusers = User.objects.filter(groups__name=custgroup.name)
 
    userlistform = UserlistForm()
 
    #This fills up the "choices"
    userlistform.fields['users'].choices = 
        [(x.id, x) for x in User.objects.filter(groups__name=custgroup.name)]
 
    data = {"userlistform":userlistform,}
 
    return render_to_response("message/view_message.html",
                          data, context_instance=RequestContext(request))

In your template, you should just display userlistform:

{{userlistform.as_p}}

EDIT:
I forgot to mention that when you want to get the “list” of selected items you use this:

userlist = request.POST.getlist('users')
"""
you will get something like this:
[u'1', u'2', u'3']
"""
Posted in General | Tagged , , , , | 3 Comments

Python: Saving a file from the URL by chunks

For example, when you want to save an image from a URL.

https://github.com/images/modules/header/logov3-hover.png
f = urllib.urlopen(request.POST['url'])
    p = os.path.join(settings.UPLOAD_DIRECTORY, "saved_file.jpg")
    filesize = 0
    with open(p,'wb') as output:
        while True:
            buf = f.read(65536)
            filesize += len(buf)
            if not buf:
                break
            output.write(buf)
Posted in General | Tagged | Leave a comment

Django: Reading an image outside the public accessible directory and displaying the image through the browser

In some cases you would want to have “private” images for your logged-in users, you will not be able to store the images in the public accessible directory.

For example, if you have “my_private_photo.png” stored in your normal “images” directory, any user (logged in or not) will be able to do this in the URL bar:

http://www.yourwebsite.com/images/my_private_photo.png

When an anonymous user does that, he would be able view the private image.

To do this, you must store your “private images” outside the public accessible directory. In this example, we will put the private images in:

/home/wenbert/private_storage

Before I proceed, please take note that this example will use X-Sendfile. Please refer to my post on how to install and configure X-Sendfile in your Apache webserver.

Now for the view.py, it would look something like this:

def display_image(request, image_id):
    path = "/home/wenbert/private_storage"
    file = image_id
    filepath = os.path.join(path,file)
 
    #Here, you put your code to check whether the user has access to this photo or not
 
    response = HttpResponse(mimetype=mimetypes.guess_type(filepath)) 
    response['Content-Disposition']='filename="%s"'
                                    %smart_str(file)
    response["X-Sendfile"] = filepath
    response['Content-length'] = os.stat(filepath).st_size
 
    return response

In your urls.py, you would want to add something like this:

(r'^display_image/(?P<image_id>d+)/$', display_image)

With this, you should be able to output images through your templates using the normal IMG tag. For example:

<img src="/display_image/private_photo.png" />

Note that I have hard-coded “private_photo.png”. This is assuming I already know the “image id” you want to display.

Comments/questions/suggestions, do not hesitate to post them below.

I hope that was helpful.

Posted in General | Tagged , , | 1 Comment

Apache mod_xsendfile for my Django app (UPDATED)

Here is how to setup/install mod_xsendfile in Apache2 + Django (mod_wsgi).

First do this to install apxs2

$> sudo apt-get install apache2-prefork-dev

Download mod_xsendfile: http://tn123.ath.cx/mod_xsendfile/

Install it by doing this:

$> apxs2 -cia mod_xsendfile.c

If you get an error compiling mod_xsendfile just ignore it, see: ubuntu forums

After installing…

$> cd /etc/apache2/mods-available
$> sudo vi xsendfile.load

Put this inside the “xsendfile.load”

LoadModule xsendfile_module /usr/lib/apache2/modules/mod_xsendfile.so

Save and exit Vi.

Open your httpd conf file or the equivalent and add “XSendFile On” and “XSendFilePath /home/path/”. See example:

#/etc/apache2/sites-available/client.test.com
<VirtualHost x.x.x.x:80>
     ServerAdmin wenbert@test.com
     ServerName client.test.com
     ServerAlias www.client.test.com
     DocumentRoot /home/client/public_html/

     XSendFile On
     XSendFilePath /home/client/storage

     WSGIScriptAlias / /home/client/application/django.wsgi
     <Directory /home/client/application>
         Order allow,deny
         Allow from all
    </Directory>

     Alias /robots.txt /home/client/public_html/robots.txt
     Alias /favicon.ico /home/client/public_html/favicon.ico
     Alias /images /home/client/public_html/images
     Alias /static /home/client/public_html/static
     Alias /admin_media /home/client/public_html/admin_media

     ErrorLog /home/client/logs/error.log
     CustomLog /home/client/logs/access.log combined
</VirtualHost>

Enable the xsendfile by using this command:

$> sudo a2enmod xsendfile

Then restart apache.

$> sudo /etc/init.d/apache2 restart

What it will look like in your views.py

@login_required
def download(request,filename):
    """
    Download a file
    "filename" must be a full path: /path/to/my/file.txt
    """
 
    #It's a good idea to check if the user is allowed access to the file here.
 
    response = HttpResponse(mimetype='application/force-download') 
    response['Content-Disposition']='attachment;filename="%s"'
                                    %smart_str(filename)
    response["X-Sendfile"] = filename
    response['Content-length'] = os.stat(filename).st_size
    return response

Credits:
Codeutopia
ubuntu forums
Stackoverflow

Posted in General | Tagged , , , | 2 Comments

File Streaming in Django (Sending large files through Django)

I am planning to build something involving serving large files over HTTP. Putting the files in a public accessible directory is not an option since I need to monitor the users who download the file. Users will need to login and certain groups will have access to certain files. In PHP, I would have no problem in implementing this but I am new to Python and Django so I had to look around. There will be very few users in this app – the most important requirement: the server will need to say alive when people download the big files (let’s say 200-500MB).

So I searched for “File Streaming in Django / Python” (not the exact keywords, but you get the idea). And I found this.

Since I use this blog like a “notebook” so that I can go back to it in case I forget things, I am going to copy-paste the entire code here. There is a bonus; the snippet includes “zipping a file” then sending it to the stream.

This snippet demonstrates how you can send a file (or file-like object) through Django without having to load the whole thing into memory. The FileWrapper will turn the file-like object into an iterator for chunks of 8KB.

This is a full working example. Start a new app, save this snippet as views.py, and add the views to your URLconf. The send_file view will serve the source code of this file as a plaintext document, and the send_zipfile view will generate a Zip file with 10 copies of it.

Use this solution for dynamic content only, or if you need password protection with Django’s user accounts. Remember that you should serve static files directly through your web server, not through Django:

http://www.djangoproject.com/documentation/modpython/#serving-media-files

import os, tempfile, zipfile
from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
 
def send_file(request):
    """                                                                         
    Send a file through Django without loading the whole file into              
    memory at once. The FileWrapper will turn the file object into an           
    iterator for chunks of 8KB.                                                 
    """
    filename = __file__ # Select your file here.                                
    wrapper = FileWrapper(file(filename))
    response = HttpResponse(wrapper, content_type='text/plain')
    response['Content-Length'] = os.path.getsize(filename)
    return response
 
def send_zipfile(request):
    """                                                                         
    Create a ZIP file on disk and transmit it in chunks of 8KB,                 
    without loading the whole file into memory. A similar approach can          
    be used for large dynamic PDF files.                                        
    """
    temp = tempfile.TemporaryFile()
    archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
    for index in range(10):
        filename = __file__ # Select your files here.                           
        archive.write(filename, 'file%d.txt' % index)
    archive.close()
    wrapper = FileWrapper(temp)
    response = HttpResponse(wrapper, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=test.zip'
    response['Content-Length'] = temp.tell()
    temp.seek(0)
    return response

A comment from the site:

jdriscoll (on October 9, 2007):
For people on Windows you’ll need to specify “read binary” mode for anything other than a text file:

wrapper = FileWrapper(file(filename), “rb”)

Also, I chatted for a few minutes in IRC (#django) asking for suggestions/recommendations from other people. “andym recommends you use X-Sendfile”. So, after I implement the code above, I will look into X-Sendfile – that will probably in another post.

The source is found here: http://djangosnippets.org/snippets/365/. (Thanks!)

Any comments/suggestions, post them below. I would especially love to read other recommendations on how you would go about sending big files through Django/Python.

Posted in General | Tagged , , , | 3 Comments

A Simple Tkinter Example (Python)

What is Tkinter?

Tkinter is Python’s de-facto standard GUI (Graphical User Interface) package. It is a thin object-oriented layer on top of Tcl/Tk.

Here is a simple Tkinter example.

The code below should generate a very simple GUI with a label, a textbox, a button that will allow you to browse a file and a Submit/Execute button.

Another thing is that when you “browse” for a file, the full path of the browsed file will be displayed in the filelocation textbox.

from Tkinter import *
import tkFileDialog, tkMessagebox
 
class App:
 
    def __init__(self, master):
        self.master = master
 
        #call start to initialize to create the UI elemets
        self.start()
 
    def start(self):
        self.master.title("This is the title of the 'Window'")
 
        self.now = datetime.datetime.now()
 
        #CREATE A TEXT/LABEL
        #create a variable with text
        label01 = "This is some text"
        #put "label01" in "self.master" which is the window/frame
        #then, put in the first row (row=0) and in the 2nd column (column=1), align it to "West"/"W"
        Label(self.master, text=label01).grid(row=0, column=0, sticky=W)
 
        #CREATE A TEXTBOX
        self.filelocation = Entry(self.master)
        self.filelocation["width"] = 60
        self.filelocation.focus_set()
        self.filelocation.grid(row=1,column=0)
 
        #CREATE A BUTTON WITH "ASK TO OPEN A FILE"
        self.open_file = Button(self.master, text="Browse...", command=self.browse_file) #see: def browse_file(self)
        self.open_file.grid(row=1, column=1) #put it beside the filelocation textbox
 
        #CREATE RADIO BUTTONS
        RADIO_BUTTON = [
            ("This will display A", "A"),
            ("This will display B","B")
        ]
 
        #initialize a variable to store the selected value of the radio buttons
        #set it to A by default
        self.radio_var = StringVar()
        self.radio_var.set("A")
 
        #create a loop to display the RADIO_BUTTON
        i=0
        for text, item in RADIO_BUTTON:
            #setup each radio button. variable is set to the self.radio_var
            #and the value is set to the "item" in the for loop
            self.radio = Radiobutton(self.master, text=text, variable=radio_var, value=item)
            self.radio.grid(row=2, column=i)
            i += 1
 
        #now for a button
        self.submit = Button(self.master, text="Execute!", command=self.start_processing, fg="red")
        self.submit.grid(row=3, column=0)
 
    def start_processing(self):
        #more code here
 
    def browse_file(self):
        #put the result in self.filename
        self.filename = tkFileDialog.askopenfilename(title="Open a file...")
 
        #this will set the text of the self.filelocation
        self.filelocation.insert(0,self.filename) 
root = Tk()
app = App(root)
root.mainloop()

Save the code as “gui.py” and then use your command line to execute it.

$ python gui.py

A Window should open up!

FYI, This is just a snippet from my first working Python script. You can view the rest of the source code in my Github: http://github.com/wenbert/tide_converter

Comments, suggestions or recommendations are of course welcomed!

You can find more resources here.

Posted in General | Tagged , | 2 Comments

A Basic Python Class

This is the basic structure of a Python class.

>>> class Simplex:
...     "An example class"""
...     def __init__(self, x, y):
...             self.a = x
...             self.b = y
...     def addition(self):
...             return self.a + self.b
...
>>> z = Simplex(3,4)
>>> z.a, z.b
(3, 4)
>>> z.addition()
7
>>> z.__doc__
'An example class'
>>>
  1. I created the class
  2. Instantiated the class and gave 3 and 4 as parameters.
  3. Call a method
  4. Test out __doc__

Source: http://docs.python.org/tutorial/classes.html

Posted in General | Tagged , , , | 1 Comment

My notes for Lists in Python

Lists

  • A list is a sequence of values.
  • [ and ]
  • like numerically indexed arrays in PHP
>>> # a list of numbers
>>> my_numbers = [10, 15, 20, 25]
>>> print my_numbers
[10, 15, 20, 25]    
>>> 
>>> #a list of strings
>>> my_strings = ['Wenbert', 'Programming', 'Address']
>>> print my_strings
['Wenbert', 'Programming', 'Address']
>>> 
>>> # a list within a list
>>> nested = ['Wenbert', ['PHP','Python','Javascript'], 'Philippines']
>>> print nested, my_numbers
>>>  ['Wenbert', ['PHP','Python','Javascript'], 'Philippines'] [10, 15, 20, 25]
>>>
>>> #Check if "PHP" is in "nested" list
>>> 'PHP' in nested
True
>>> 'Java' in nested
False

To traverse a list:

for item in nested:
    print item

Slicing a list:

>>> basket = ['apples', 'mangoes', 'guava', 'grapes']
>>> basket[2:4]
['guava', 'grapes']

You can append to a list:

>>> basket =  ['apples', 'mangoes', 'guava', 'grapes']
>>> basket.append('banana')
>>> print basket
['apples', 'mangoes', 'guava', 'grapes', 'banana']

You can sort a list:

>>> basket =  ['apples', 'mangoes', 'guava', 'grapes']
>>> basket.sort()
>>> print basket
['apples', 'grapes', 'guava', 'mangoes']

You can “pop”, “delete” and “remove” from a list.

>>> basket =  ['apples', 'mangoes', 'guava', 'grapes']
>>> 
>>> basket.pop()
'grapes'
>>> print basket
['apples', 'mangoes', 'guava']
>>> 
>>> basket.remove('mangoes')
>>> print basket
['apples', 'guava']
>>> 
>>> del basket[0]
>>> print basket
['guava']

Spliting and Joining:

>>> string = 'Wenbert Del Rosario'
>>> pieces = string.split()
>>> print pieces
['Wenbert', 'Del', 'Rosario']
>>>
>>> bag = 'healing potion | dagger | round shield |gold'
>>> items = bag.split(' | ')
>>> print items
['healing potion', 'dagger', 'round shield |gold']
>>> ">".join(items) #glue items together with the ">" symbol
'healing potion>dagger>round shield |gold'

That’s about it. If I encounter more, I will update this post.

Posted in General | Tagged , | 2 Comments

Basic Python: Filenames and paths

Another Python post! I am still learning the language. Since I cannot remember everything, I am posting it here for future reference.

Get the Current Working Directory
To get the “current working directory” do this:

import os
current_dir = os.getcwd()
print current_dir

If you are doing this from the command line, you should see something like:

/home/wenbert

Get the Absolute Path of a File

import os
abs_path = os.path.abspath('myfile.txt')
print abs_path #will show something like: /home/wenbert/myfile.txt

Check if a File or Directory Exists
I am demonstrating this as if you are in the interactive Python shell and not as a file.

>>> import os
>>> os.path.exists('myfile.txt')
True
>>> os.path.exists('non-existent-file.txt')
False

Check “value” if it is a Directory or is a File
isdir()

>>> import os
>>> os.path.isdir('myfile.txt')
False
>>> os.path.isdir('/home/wenbert/mydirectory')
True

isfile()

>>> import os
>>> os.path.isfile('myfile.txt')
True
>>> os.path.isfile('/home/wenbert/mydirectory')
False

List everything inside a directory

>>> import os
>>> os.listdir('/home/wenbert/mydirectory')
['sub_directory','myfile.txt', 'sample.txt']

FYI: I am reading “Learn Pythong the Hard Way” and “Think Python”.

Comments / Suggestions are welcomed!

Posted in General | Tagged , , , , , , , | Leave a comment