Category Archives: django

django扩展block

django扩展block        

django的

{% block [blockname] %}

{% endblcok %}

可以让开发者随意定义自己的block,然后在子模板中(通过extends来继承),可以声明同样的模块来重写该block。例如:

// base.htm

<html>
<head>
</head>

<body>

继续阅读

ajax+django异步上传文件

以下文字转自:

http://kuhlit.blogspot.com/2011/04/ajax-file-uploads-and-csrf-in-django-13.html

Ajax file uploads and CSRF (in Django 1.3, or possibly other frameworks)

To begin, this is an update of my old post
AJAX Uploads in Django (with a little help from jQuery)
. This guide is specific to Django, but my version of the file uploader can (theoretically, it is untested) be used with other web frameworks that use CSRF, like Ruby on Rails. You should be able to
follow along with the guide and make adjustments as appropriate for your framework.

  • My version of Valum’s file upload
  • Python 2.6+
  • Django 1.3+

If you are on an older version of Python and/or Django, reading the
prior version of this post
and especially
this Stack Overflow question of mine
may provide some help in adjusting the code. The only part that requires updated Python and Django is the save_upload function. The code uses buffered readers/writers and the ‘with’ keyword from Python 2.6+ (these parts
can easily be changed I suspect) and reads from the raw HttpRequest, which comes with Django 1.3+. The Stack Overflow question has code I tried before moving up to requiring these newer software versions. It worked for small uploads below CD ISO size (700MB)
and can probably be fixed to work with all uploads, I just found the Django 1.3+ solution easier and quicker at the time.

Ajax Upload handles the client-side very seamlessly and only gives one challenge to the programmer: it passes the file either as the raw request, for the “advanced” mode, or as the traditional form file for the “basic” mode. Thus, on the Django side, the
receiving function must be written to process both cases. As the old post discusses, reading this raw request was a bit of trouble, and that is why I went with Django 1.3 as a requirement for my code.

First is to get AJAX Upload installed by
downloading the latest version from my Github repo
. This fork of Valum’s original includes my changes as well as improvements from other forks that I need. As of this writing, I have added correct awareness in FileUploader of FileUploaderBasic’s ‘multiple’
parameter and included David Palm’s onAllComplete trigger. Once downloaded, grab
fileuploader.js and fileuploader.css out of the client folder and place them wherever is appropriate for your setup. Finally, link them in your HTML via your Django templates.

HTML

This is the HTML code that will house the upload button/drag area so place it appropriately.

?
1
2
3
4
5
<div
id="file-uploader">      
    <noscript>         
        <p>Please enable JavaScript to use file uploader.</p>
    </noscript>        
</div>

Javascript

You probably want to dump this in the same HTML/template file as the above, but it is up to you of course.

var uploader = new qq.FileUploader( {
    action: "{% url ajax_upload %}",
    element: $('#file-uploader')[0],
    multiple: true,
    onComplete: function( id, fileName, responseJSON ) {
      if( responseJSON.success )
        alert( "success!" ) ;
      else
        alert( "upload failed!" ) ;
    },
    onAllComplete: function( uploads ) {
      // uploads is an array of maps
      // the maps look like this: { file: FileObject, response: JSONServerResponse }
      alert( "All complete!" ) ;
    },
    params: {
      'csrf_token': '{{ csrf_token }}',
      'csrf_name': 'csrfmiddlewaretoken',
      'csrf_xname': 'X-CSRFToken',
    },
  } ) ;
}

继续阅读

django附加额外信息到user

django附加额外信息到user  

django的用户模块提供了很好的用户管理,包括用户的注册和登录认证,但是发现user的模型中只包含了简单的几个数据段,如果我们想要其他的信息,比如用户的兴趣爱好,职业等,我们怎么办呢。

下面我找到一篇的很好的文章提到了,怎么做到这点。

Django User Profiles – Simple yet powerful

So you're building a web application, and using the excellent contrib.auth subsystem to manage user accounts. Most probably you need to store additional information about your users, but how? Django profiles to the rescue!

Django provides a lightweight way of defining a
profile object linked to a given user. The profile object can differ from project to project, and it can even handle different profiles for different sites served from the same database.

In a nutshell, using Django profiles consists of 3 steps:

  • Define a model that holds the profile information.
  • Tell Django where to look for the profile object.
  • Create the user profile as needed.

Defining the user profile model

The only requirement Django places on this model is that it have a unique ForeignKey to the User model, and is called user. Other than that, you can define any other fields you like.

For our example, we'll create 2 user profile fields (url and company).

account/models.py

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    url = models.URLField("Website", blank=True)
    company = models.CharField(max_length=50, blank=True)

继续阅读

django工程使用静态文件

django中使用static文件-图片,css,js文件非常麻烦。于是直接使用apache的alias功能。

在development环境开发时,也就是使用django自带的web server来开发测试时可以在urls.py中加入:

from django.conf import settings
urlpatterns += patterns(”,
    (r’^static/(?P<path>.*)$’, ‘django.views.static.serve’, {‘document_root’: settings.STATICFILE_ROOT}),
)

继续阅读

django语法点滴

以下是在练习和项目过程中总结列出来的django的易出错和该注意的地方,因为比较比较杂,单独不能成一篇文章,因此都列在这里。

1. django的template中

{%         %}

注意%和}必须紧挨着,不能有空格,否则django不认。

2. 创建django的form可以直接定义default值

继续阅读

django redirect

django redirect  

以下文字摘自一篇讨论,其中提到了redirect的几种方法:

1. HttpResponseDirect

2. redirect

3. url.py 中直接redirect

80
down vote
accepted

It's simple:

from django.http import HttpResponseRedirect

def myview(request):
    ...
    return HttpResponseRedirect("/path/")

More info in the
official Django docs

Update

There is apparently a better way of doing this in Django now using generic views.

Example –

from django.views.generic.simple import redirect_to

urlpatterns = patterns('',   
    (r'^one/$', redirect_to, {'url': '/another/'}),

    #etc...
)

继续阅读

django调试

django调试  

如果通过django自带web服务器来测试程序,我们就可以使用 print 来将需要查看的东西直接打印到控制台上。

但是这样做还是有些不方便,如果能调试就好了。

事实上,django有提供这个功能。

首先需要安装django-pdb

安装django-pdb

pip install django-pdb

添加django-pdb 到INSTALLED_APPS

接着直接添加django-pdb到你的工程的settings.py的INSTALLED_APPS下面

INSTALLED_APPS = {

django_pdb,

}

以pdb选项运行django web server

python manage.py runserver –pdb

bash: manage.py runserver --pdb
Validating models...

0 errors found
Django version 1.3, using settings 'testproject.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

接下来,从浏览器访问你工程中的app,就会激活django的调试器

GET /
function "myview" in testapp/views.py:6
args: ()
kwargs: {}

> /Users/tom/github/django-pdb/testproject/testapp/views.py(7)myview()
-> a = 1
(Pdb)

继续阅读