Wednesday, February 06, 2008
Wednesday, December 12, 2007
Dummies guide for using Slideshare Api using Ruby
unix timestamp => TS = Time.now.to_i
get hash => HASH = Digest::SHA1.hexdigest(sharedsecret+TS)
Api Key => AKEY
AKEY and sharedsecret will be mailed to you once you apply for API
http://www.slideshare.net/developers/documentation
for ex:
http://www.slideshare.net/api/1/get_slideshow?api_key=AKEY&ts=TS&hash=HASH&username=UN&password=PWD&slideshow_id=Sid
get hash => HASH = Digest::SHA1.hexdigest(sharedsecret+TS)
Api Key => AKEY
AKEY and sharedsecret will be mailed to you once you apply for API
http://www.slideshare.net/developers/documentation
for ex:
http://www.slideshare.net/api/1/get_slideshow?api_key=AKEY&ts=TS&hash=HASH&username=UN&password=PWD&slideshow_id=Sid
Labels:
api,
dummies guide,
rest,
ruby,
slideshare,
slideshareapi
Tuesday, December 11, 2007
Adding classes/style to django form elements
The 'attrs' argument to the Widget class used with each particular
Field (the Widget is what actually renders the HTML) accepts a
dictionary which will become HTML attribute names and values. For
example:
username = forms.CharField(widget=forms.TextInput(attrs={'class': 'myclass'}))
will become:
the old forms default of having class attributes for each
input type (e.g. class=vTextField for type=text)
Field (the Widget is what actually renders the HTML) accepts a
dictionary which will become HTML attribute names and values. For
example:
username = forms.CharField(widget=forms.TextInput(attrs={'class': 'myclass'}))
will become:
the old forms default of having class attributes for each
input type (e.g. class=vTextField for type=text)
Sunday, December 09, 2007
populating select box from database ror
controller code looks something like:
class testController < ApplicationController
def test
@categories= Category.find_all
end
end
use
<%= options_from_collection_for_select @categories, 'id', 'name' %>
to populate the select box
class testController < ApplicationController
def test
@categories= Category.find_all
end
end
use
<%= options_from_collection_for_select @categories, 'id', 'name' %>
to populate the select box
Saturday, December 08, 2007
Django Forms
Start with this basic Form subclass, which we’ll call ContactForm:
from django import newforms as forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
A form is composed of Field objects.
Creating Form instances
A Form instance is either bound to a set of data, or unbound.
* If it’s bound to a set of data, it’s capable of validating that data and rendering the form as HTML with the data displayed in the HTML.
* If it’s unbound, it cannot do validation but it can still render the blank form as HTML.
To create an unbound Form instance, simply instantiate the class:
>>> f = ContactForm()
To bind data to a form, pass the data as a dictionary as the first parameter to your Form class constructor:
>>> data = {'subject': 'hello',
... 'message': 'Hi there',
... 'sender': 'foo@example.com',
... 'cc_myself': True}
>>> f = ContactForm(data)
In this dictionary, the keys are the field names, which correspond to the attributes in your Form class. The values are the data you’re trying to validate. These will usually be strings, but there’s no requirement that they be strings; the type of data you pass depends on the Field, as we’ll see in a moment.
If you need to distinguish between bound and unbound form instances at runtime, check the value of the form’s is_bound attribute:
>>> f = ContactForm()
>>> f.is_bound
False
>>> f = ContactForm({'subject': 'hello'})
>>> f.is_bound
True
Note that passing an empty dictionary creates a bound form with empty data:
>>> f = ContactForm({})
>>> f.is_bound
True
If you have a bound Form instance and want to change the data somehow, or if you want to bind an unbound Form instance to some data, create another Form instance. There is no way to change data in a Form instance. Once a Form instance has been created, you should consider its data immutable, whether it has data or not.
1) The primary task of a Form object is to validate data. With a bound Form instance, call the is_valid() method to run validation and return a boolean designating whether the data was valid:
2) Each Field in a Form class is responsible not only for validating data, but also for “cleaning” it — normalizing it to a consistent format.
f.errors
In this dictionary, the keys are the field names, and the values are lists of Unicode strings representing the error messages. The error messages are stored in lists because a field can have multiple error messages.
f.cleaned_data
If your data does not validate, your Form instance will not have a cleaned_data attribute:
cleaned_data will always only contain a key for fields defined in the Form, even if you pass extra data when you define the Form. In this example, we pass a bunch of extra fields to the ContactForm constructor, but cleaned_data contains only the form’s fields:
print f
You can access errors without having to call is_valid() first. The form’s data will be validated the first time either you call is_valid() or access errors.
The validation routines will only get called once, regardless of how many times you access errors or call is_valid()
Each field type has a default HTML representation. CharField and EmailField are represented by an . BooleanField is represented by an . Note these are merely sensible defaults; you can specify which HTML to use for a given field by using widgets
Use the auto_id argument to the Form constructor to control the label and id behavior. This argument must be True, False or a string.
If auto_id is False, then the form output will not include
from django import newforms as forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
A form is composed of Field objects.
Creating Form instances
A Form instance is either bound to a set of data, or unbound.
* If it’s bound to a set of data, it’s capable of validating that data and rendering the form as HTML with the data displayed in the HTML.
* If it’s unbound, it cannot do validation but it can still render the blank form as HTML.
To create an unbound Form instance, simply instantiate the class:
>>> f = ContactForm()
To bind data to a form, pass the data as a dictionary as the first parameter to your Form class constructor:
>>> data = {'subject': 'hello',
... 'message': 'Hi there',
... 'sender': 'foo@example.com',
... 'cc_myself': True}
>>> f = ContactForm(data)
In this dictionary, the keys are the field names, which correspond to the attributes in your Form class. The values are the data you’re trying to validate. These will usually be strings, but there’s no requirement that they be strings; the type of data you pass depends on the Field, as we’ll see in a moment.
If you need to distinguish between bound and unbound form instances at runtime, check the value of the form’s is_bound attribute:
>>> f = ContactForm()
>>> f.is_bound
False
>>> f = ContactForm({'subject': 'hello'})
>>> f.is_bound
True
Note that passing an empty dictionary creates a bound form with empty data:
>>> f = ContactForm({})
>>> f.is_bound
True
If you have a bound Form instance and want to change the data somehow, or if you want to bind an unbound Form instance to some data, create another Form instance. There is no way to change data in a Form instance. Once a Form instance has been created, you should consider its data immutable, whether it has data or not.
1) The primary task of a Form object is to validate data. With a bound Form instance, call the is_valid() method to run validation and return a boolean designating whether the data was valid:
2) Each Field in a Form class is responsible not only for validating data, but also for “cleaning” it — normalizing it to a consistent format.
f.errors
In this dictionary, the keys are the field names, and the values are lists of Unicode strings representing the error messages. The error messages are stored in lists because a field can have multiple error messages.
f.cleaned_data
If your data does not validate, your Form instance will not have a cleaned_data attribute:
cleaned_data will always only contain a key for fields defined in the Form, even if you pass extra data when you define the Form. In this example, we pass a bunch of extra fields to the ContactForm constructor, but cleaned_data contains only the form’s fields:
print f
You can access errors without having to call is_valid() first. The form’s data will be validated the first time either you call is_valid() or access errors.
The validation routines will only get called once, regardless of how many times you access errors or call is_valid()
Each field type has a default HTML representation. CharField and EmailField are represented by an . BooleanField is represented by an . Note these are merely sensible defaults; you can specify which HTML to use for a given field by using widgets
Use the auto_id argument to the Form constructor to control the label and id behavior. This argument must be True, False or a string.
If auto_id is False, then the form output will not include
Saturday, November 24, 2007
render_to_response()
render_to_response()
Because it’s such a common idiom to load a template, fill a Context and return an HttpResponse object with the result of the
rendered template, Django provides a shortcut that lets you do those things in one line of code. This shortcut is a function
called render_to_response(), which lives in the module django.shortcuts. Most of the time, you’ll be using render_to_response() rather than loading templates and creating Context and HttpResponse objects manually.
Here’s the ongoing current_datetime example rewritten to use render_to_response():
from django.shortcuts import render_to_response
import datetime
def current_datetime(request):
now = datetime.datetime.now()
return render_to_response('current_datetime.html', {'current_date': now})
What a difference! Let’s step through the code changes:
l We no longer have to import get_template, Template, Context or HttpResponse. Instead, we
import django.shortcuts.render_to_response. The import datetime remains.
l Within the current_datetime function, we still calculate now, but the template loading, context creation, template rendering
and HttpResponse creation is all taken care of by the render_to_response() call. Because render_to_response() returns
an HttpResponse object, we can simply return that value in the view.
The first argument to render_to_response() should be the name of the template to use, relative to your template directory. The
second argument, if given, should be a dictionary to use in creating a Context for that template. If you don’t provide a second
argument, render_to_response() will use an empty dictionary
Because it’s such a common idiom to load a template, fill a Context and return an HttpResponse object with the result of the
rendered template, Django provides a shortcut that lets you do those things in one line of code. This shortcut is a function
called render_to_response(), which lives in the module django.shortcuts. Most of the time, you’ll be using render_to_response() rather than loading templates and creating Context and HttpResponse objects manually.
Here’s the ongoing current_datetime example rewritten to use render_to_response():
from django.shortcuts import render_to_response
import datetime
def current_datetime(request):
now = datetime.datetime.now()
return render_to_response('current_datetime.html', {'current_date': now})
What a difference! Let’s step through the code changes:
l We no longer have to import get_template, Template, Context or HttpResponse. Instead, we
import django.shortcuts.render_to_response. The import datetime remains.
l Within the current_datetime function, we still calculate now, but the template loading, context creation, template rendering
and HttpResponse creation is all taken care of by the render_to_response() call. Because render_to_response() returns
an HttpResponse object, we can simply return that value in the view.
The first argument to render_to_response() should be the name of the template to use, relative to your template directory. The
second argument, if given, should be a dictionary to use in creating a Context for that template. If you don’t provide a second
argument, render_to_response() will use an empty dictionary
Labels:
context,
django,
http,
httpresponse,
render_to_response
Friday, November 23, 2007
Django Stuff - 1
Projects vs. apps
What’s the difference between a project and an app? An app is a Web application that does something — e.g., a weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular Web site. A project can contain multiple apps. An app can be in multiple projects.
Each model is a Python class that subclasses django.db.models.Model.
Each attribute of the model represents a database field.
Model metadata (non-field information) goes in an inner class named Meta.
Metadata used for Django’s admin site goes into an inner class named Admin
Executing Custon SQL
def my_custom_sql(self):
from django.db import connection
cursor = connection.cursor()
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
row = cursor.fetchone()
return row
How Django processes a request
When a user requests a page from your Django-powered site, this is the algorithm the system follows to determine which Python code to execute:
Django looks at the ROOT_URLCONF setting in your settings file. This should be a string representing the full Python import path to your URLconf. For example: "mydjangoapps.urls".
Django loads that Python module and looks for the variable urlpatterns. This should be a Python list, in the format returned by the function django.conf.urls.defaults.patterns().
Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.
Once one of the regexes matches, Django imports and calls the given view, which is a simple Python function. The view gets passed a request object as its first argument and any values captured in the regex as remaining arguments.
What’s the difference between a project and an app? An app is a Web application that does something — e.g., a weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular Web site. A project can contain multiple apps. An app can be in multiple projects.
Each model is a Python class that subclasses django.db.models.Model.
Each attribute of the model represents a database field.
Model metadata (non-field information) goes in an inner class named Meta.
Metadata used for Django’s admin site goes into an inner class named Admin
Executing Custon SQL
def my_custom_sql(self):
from django.db import connection
cursor = connection.cursor()
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
row = cursor.fetchone()
return row
How Django processes a request
When a user requests a page from your Django-powered site, this is the algorithm the system follows to determine which Python code to execute:
Django looks at the ROOT_URLCONF setting in your settings file. This should be a string representing the full Python import path to your URLconf. For example: "mydjangoapps.urls".
Django loads that Python module and looks for the variable urlpatterns. This should be a Python list, in the format returned by the function django.conf.urls.defaults.patterns().
Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.
Once one of the regexes matches, Django imports and calls the given view, which is a simple Python function. The view gets passed a request object as its first argument and any values captured in the regex as remaining arguments.
Labels:
django,
executing custom sql,
projects vs app,
request
Subscribe to:
Posts (Atom)