Search This Blog

Showing posts with label Django. Show all posts
Showing posts with label Django. Show all posts

Tuesday, January 17, 2012

Django, Force Https on Django Admin in Apache


Encrypt all network traffic going through Django admin pages.
i.e. All pages http://yoursite.com/admin/ANY_PAGES will be redirected to
secure pages https://yoursite.com/admin/ANY_PAGES


Just add a redirect match to your httpd.conf file. For example, in Ubuntu (/etc/apache2/sites-available/your_config_file) you can do:

RedirectMatch ^/admin.* https://yoursite.com/admin

Friday, May 13, 2011

Django with Authorize.net

Pay with authorize.net in Django? If you are going to use AIM method, you can download the open source django-authorizenet library.
  1. extract the package, put it under your django project as another module.
  2. python manage.py syncdb, so you install the Response model that can stores the authorize.net's response after you submit a transaction
  3. write your own view class, prepare the aim payment form template and aim payment successful template
  4. in the view class, pass the form context variables and let django-authorizenet render or submit the payment for you
  5. you will need to get the login key and transaction id from authorize.net, of course.

Sunday, February 20, 2011

Django, Use Gmail to Send your email

Put this in your setting.py (or your local_settings.py whcih settings.py can import it)
This setup is very useful on your development machine, so that you don't need to maintain your own smtp server.

EMAIL_HOST
= 'smtp.gmail.com'
EMAIL_PORT
= 587
EMAIL_HOST_USER = 'gmail_account'
EMAIL_HOST_PASSWORD = 'gmail_password'
EMAIL_SUBJECT_PREFIX
= '[your django project]'
EMAIL_USE_TLS
= True



Monday, January 31, 2011

Django, Reading Code for Your New Project

(summary) Djangocon, 2010, by Justin Lilly
watch video

You join a Django project. You would like to contribute code. But how? The codebase is probably more than 10 thousand lines, where do you start? Everyone has similar experience, here are some tips for learning code base. Although we use Django as our example, the concept applies to other projects too.
  1. Exploratory code reading: This is often a mandatory step for learning new code base. You need to build certain amount of vocabulary for the code. In Django, for example, if you see someone uses generic view, you should have an idea what generic view is. During code exploration, you also build a level of fuzzy understanding of the code. Don't worry about if you don't fully understand what a method does. You are already building a foundation. Later on, they will just click.
  2. Focus, Focus on small parts: Once you built enough vocabulary for the code, you should start focus on certain part of the code. Remember the 80-20 rule? Find something you are interested in, and start focusing on it. Creating a code reading branch, change the variable, do whatever you like. Git log --numstat, if you are using git as your version control, to find what is being modified frequently.
  3. Debug code, find a ticket: import pdb; pdb.set_trace(). Put that at the place you want the program to stop and trace. In Django, you can put that into the first line of a view function you are interested in. Select one easy ticket in your project, and provide a solution to it. After a ticket or two, you will learn a lot.
  4. Read unit tests: it's very very nice if your project has unit test. They are obvious, small, and focusing on a small part of the code base. For example, if you see a test case: test_create_shopping_cart(). You can learn the work flow of creating a shopping cart just by looking at the unit test.
  5. Views, Models, and Urls: urls.py is the entry point of the code, like the main() in C++. find . -name models.py, use that to find out how your Django "views" all the useful data stored in the db. grep -r 'a_function' . , to see where a_function is called among files.
  6. Don't go too deep, so ask questions: you don't have to find out all the answer yourself. If you question some part of the code (and you can do better), you can just ask someone who knows it. They can explain why it is implemented this way. Keep in mind the 20-80 rule. You would like to contribute to your team in a week or two.
Happy code reading.

Sunday, October 11, 2009

Django, Apply Security Update in FreeBSD

If the port is not ready, we can apply the update on Django on ourself in FreeBSD.

For example, to apply [1.1.X] SECURITY ALERT: Corrected regular expressions for URL and email fields, go to

/usr/local/lib/python2.6/site-packages/django/

find the files and change the python source yourself.

Tuesday, September 22, 2009

Django, Feel it

Portable:
http://blog.dpeepul.com/2009/08/31/top-10-tips-to-a-new-django-developer/

Think reusable:
make use of reverse(), permalink(), and {% url %} tag.
get data from another model (get_model), and provide a default model
make your form pluggable

a good example is to have a view function, with request as the first argument, then people can specify their own form, template, and url they can go after the view.
http://ericholscher.com/projects/reusable-app-docs/index.html
http://www.youtube.com/watch?v=A-S0tqpPga4

Where should your App live?
A project has a collection of apps(comments, tag, etc...). Try decouple your apps from your site, so you can use your app in another project, and other people can use yours app, too
http://www.muhuk.com/2009/03/django-where-should-my-app-live/


In urls.py:

url is how user can type in the address bar, sending a command or go to a place
i.e. (regular expression, path.to.viewFunction)
then the matching method, can be found in the view (views.py) to run.

You can pass argument in the urls.py, with (), so your view method can get extra argument.
You can use "name grouping" for as keyword argument instead as positional argument

In views.py
in each method, you can load the model (database), play with it. At the end, you can also
"render_to_response" to specify a template to show, and passing some variables into
the template.

views takes an http request (from your urls.py), and (almost always) return an response.
template can help the view. it helps to generate some "text".

If http request and http response are not enough for you, you can always write your own http middleware. So that you can do something in between request and response, without copy&paste code to each of your view, but simply, import your middleway.

In models.py
you can set the database schema here. To let views or admin to use it, just tell them to
import the model class. And then you can use the API to make queries.

model is just "a python class". In your view after retrieving your model, you can add any attribute to it if you want.

Django supports cache framework. Use it if speed is your big priority.

HttpReqest and HttpResponse:
You can set cookie, get cookie, rediret, do all kinds of essential operations.
more on the doc...

User Profile:
In user authentication, we can store profile for each user (built-in feature)
more on the doc...

Modify Model Frequently (during development)
  1. Modify the model
  2. manage.py reset appname
  3. use Fixture to generate test data
  4. goto 1.
more...



Debug your Django
Remeber pdb? the python debugger. Just add import pdb, pdb.set_trace() to your code where you want to stop. You can see information in your terminal!

Monday, September 21, 2009

Django, Admin Interface

add 'django.contrib.admin to INSTALLED_APPS in settings.py

run python manage.py syncdb (because you've installed a new application to update the db)

in the urls.py, uncomment the lines for admin, and uncomment the url pattern for admin

then you can go to /admin/ and log in

To tell the admin to use your model, create an admin.py in your my_model directory
from mysite.my_model.models import your_model_method
from django.contrib import admin

admin.site.register(your_model_method)


Then restart your server.

You can customize your model with your "to string" like method. In your admin.py under your model,

class ideaAdmin(admin.ModelAdmin):
list_display = ('title', 'description')

admin.site.register(idea, ideaAdmin)


----------------------
you can easily change the "django" in the admin interface. just make an "admin" directory in your "template" directory,
and then copy the base_site.html from django/contrib/admin/templates/admin to your admin directory.

read more:
http://docs.djangoproject.com/en/1.0/intro/tutorial02/

Django, Create Your Model

python manage.py startapp my_model
my_model/model.py

settings.py
INSTALLED_APPS
-->mysite.my_model

python manage.py sql my_model
(check the actual sql statements)

python manage.py syncdb
(really create the database)

python manage.py shell
>>
i = idea(title="Butterfly", description="sell butterfly", author="Jie", date=datetime.datetime.now())


To use your model in views.py and admin.py, just import your model class from your model.

Sunday, September 20, 2009

Django, Create Your 404 Page Not Found

1. make a 404.html in your template directory
2. change Debug=False, in your settings.py (if you forget the step one, your server will get 500, server error)

Django, Free Django Hosting

It is not English, but you know how to enter the information to create an account anyway :)
http://www.alwaysdata.com
(10M free. more than enough to write lots of code, and you have ssh access too!)

Now, to get your free Django to work, it is very easy by just following their (non-English) wiki.
http://wiki.alwaysdata.com/wiki/D%C3%A9ployer_une_application_Django

You will need two files, django.fcgi, and .htaccess on this shared hosting environment.
(You can copy and paste the two files below)
django.fcgi
#------------------------------------------------------
#!/usr/bin/python
import os, sys

_PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, _PROJECT_DIR)
sys.path.insert(0, os.path.dirname(_PROJECT_DIR))

_PROJECT_NAME = _PROJECT_DIR.split('/')[-1]
os.environ['DJANGO_SETTINGS_MODULE'] = "%s.settings" % _PROJECT_NAME

from django.core.servers.fastcgi import runfastcgi

runfastcgi(method="threaded", daemonize="false")
#-------------------------------------------------------
.htaccess
AddHandler fcgid-script .fcgi
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ django.fcgi/$1 [QSA,L]
---------------------------------------------------------


1. Create your Django project. django-admin.py startproject mysite
2. Create a "public" directory under "mysite"
3. put django.fcgi and .htaccess under the public directory

Your "mysite" structure will look like this:
myproject/
__init__.py
manage.py
public/
django.fcgi
.htaccess
media/
settings.py
urls.py
myapp/
views.py
models.py

Notice the media directory under public, you can create a soft link for that with
ln -s /var/lib/python/django/1.1/django/contrib/admin/media/ media

so, you can get the Django admin to work properly, i
it's django version 1.1 in this case.


Then, your "public" url is under Django's control!
http://youraccount.alwaysdata.net/mysite/public/

e.g. If you follow the hello world example in the Django book, you can go
http://youraccount.alwaysdata.net/mysite/public/hello
and it will print the happy Django's "hello world".

Last step:
Make sure you go to your administration panel. Go to domain, edit, and change your root directory to, for example, /www/mysite/public/
or people can view your source code :)

So you can use your free Django powered site with
http://youraccount.alwaysdata.net/hello

Deployment:
tar your entire site and upload with ftp, and then untar.
remember to update the "TEMPLATE_DIRS" (using ABSOLUTE path), and update the "DATABASE_NAME" (using ABSOLUTE path if using sqlite)


also read:
http://www.codekoala.com/blog/2008/installing-django-shared-hosting-site5/
http://www.ibm.com/developerworks/opensource/library/os-django/index.html