??xml version="1.0" encoding="utf-8" standalone="yes"?> 打开settings.pyQ在database节点下: ENGINE 数据库引擎名Uͼ可以?/span>'django.db.backends.postgresql_psycopg2'?
'django.db.backends.mysql' ?
'django.db.backends.sqlite3' NAME 数据库名Uͼ 如果使用sqliteQ这里就是db文gl对路径Q比如f:/temp/mysite/data.db USER 数据库用户名Qsqlite不需?/p>
PASSWORD 密码Qsqlite不需?/p>
HOST 数据库主机ipQsqlite不需?/p>
使用sqlite。如果用其他如PostgerSQL、MySQL{,在配|之前要保先在数据库中已徏立相关项目?br />
Powered by ScribeFire. Powered by ScribeFire. There are lots of gems buried in Django that are slowly coming to light. Generic views and specifically the CRUD (create, update, delete) generic views are extremely powerful but underdocumented. This brief tutorial will show you how to make use of CRUD generic views in your Django application. One of my first encounters with Rails was the simple todo list tutorial which managed to relate lots of useful information by creating a simple yet useful application. While I will do my best to point out interesting and useful things along the way, it is probably best that you be familiar with the official Django tutorials. Now would also probably be a good time to mention that this tutorial works for me using MySQL and revision 524. Django is under constant development, so things may change. I’ll do my best to keep up with changes. As with all Django projects, the best place to start is to start with Now that we have the project set up, let’s take a look at our rather simple model (
The model is short and sweet, storing a title, description, two dates, and if the task is done or not. To play with your model in the admin, add the following to Feel free to play around with your model using the admin site. For details, see tutorial 2. Now let’s configure our URLs. We’ll fill in the code behind these URLs as we go. I edited
Note: I had to alter the formatting of the urlpatterns in order to make them fit. It looks a lot better in its original formatting. We use the Let’s look at each of these URLs one at a time, along with the code behind them.
This points to our index view, which is an index function in
This view creates two lists for us to work with in our template, Make sure that you have a template directory defined in todo.settings.main (this refers to
Now let’s take a look at the template that I’m using for the index:
Don’t let this index scare you, it’s just a little bit of logic, a little looping, and some links to other parts of the application. See the template authoring guide if you have questions. Here’s a picture to give you a better idea as to how the above barebones template renders in Firefox: Now let’s take a look at the following URL pattern:
There’s a lot of magic going on here that’s going to make your life really easy. First off, we’re going to call the Here’s the template that I am using for
Here’s what the create template looks like rendered: If we fill out the form without the proper (or correctly formatted) information, we’ll get an error:
This URL pattern handles updates. The beautiful thing is it sends requests to
So if there’s no object present, we’re creating. If there’s an object present, we’re updating. Same form. Pretty cool.
Warning: It looks like form.create_date_date and form.create_date_time have broken between the time I wrote this and wrote it up. This form will not prepopulate the form with the stored information. There’s a ticket for this, and I’ll update as neccesary when it has been fixed. Here’s the URL pattern to delte a task:
There’s another little Django gem in the delete function. If we end up at
Once this form is submitted, the actual delete takes place and we are redirected to the main index page (because we set That pretty much covers the basics of the CRUD generic views. The great thing about generic views is that you can use them along side your custom views. There’s no need to do a ton of custom programming for list/detail, date-based, or CRUD since those generic views are available to you. Because we set up our URL patterns, we can make sure that we craft URLs that look pretty and make sense. For my sample tasks application I decided that I wanted to create links that would immediately set a task as complete and then redirect to the index. This is pretty much trivial and can be accomplished by adding the following URL pattern and backing it up with the appropriate view. Here’s the pattern:
And here’s the view that goes along with it (from
I do plan to actually handle errors and respond accordingly, but it was late last night and I just wanted to see it work (and it does). Django rocks. Generic views rock. The framework and specifically the generic views make your life easy. My little tasks app took a few hours to put together, but a significant portion of that was reading up on the documentation, trying to figure out generic views using the existing docs and reading the source, and of course pestering the DjangoMasters about generic views and other stuff on #django (thanks all). I hope this overview of CRUD generic views helps, but if anything confuses you, don’t hesitate to comment or get in touch with me (matt at ooiio dot com). Also expect to see updates to this tutorial as APIs change and I get a little more time to clean up my code. Feel free to download and play with my little todo app: todo-tutorial.tar.gz or todo-tutorial.zip. Consider them released under a BSD-style license. Above all, don’t sue me. django-admin.py is Django's command-line utility for administrative tasks. This document outlines all it can do. django-admin.py是Django的命令行理pȝQ这文档将详细介绍他的功能?/p>
In addition, manage.py is automatically created in each Django project. manage.py is a thin wrapper around django-admin.py that takes care of two things for you before delegating to django-admin.py: The django-admin.py script should be on your system path if you installed Django via its setup.py utility. If it's not on your path, you can find it in site-packages/django/bin within your Python installation. Consider symlinking to it from some place on your path, such as /usr/local/bin. Generally, when working on a single Django project, it's easier to use manage.py. Use django-admin.py with DJANGO_SETTINGS_MODULE, or the --settings command line option, if you need to switch between multiple Django settings files. django-admin.py action [options] manage.py action [options] action should be one of the actions listed in this document. options, which is optional, should be zero or more of the options listed in this document. Run django-admin.py --help to display a help message that includes a terse list of all available actions and options. Most actions take a list of appname``s. An ``appname is the basename of the package containing your models. For example, if your INSTALLED_APPS contains the string 'mysite.blog', the appname is blog. Prints the admin-index template snippet for the given appnames. Use admin-index template snippets if you want to customize the look and feel of your admin's index page. See Tutorial 2 for more information. Creates a cache table named tablename for use with the database cache backend. See the cache documentation for more information. Runs the command-line client for the database engine specified in your DATABASE_ENGINE setting, with the connection parameters specified in your DATABASE_USER, DATABASE_PASSWORD, etc., settings. This command assumes the programs are on your PATH so that a simple call to the program name (psql, mysql, sqlite3) will find the program in the right place. There's no way to specify the location of the program manually. Displays differences between the current settings file and Django's default settings. Settings that don't appear in the defaults are followed by "###". For example, the default settings don't define ROOT_URLCONF, so ROOT_URLCONF is followed by "###" in the output of diffsettings. Note that Django's default settings live in django/conf/global_settings.py, if you're ever curious to see the full list of defaults. Introspects the database tables in the database pointed-to by the DATABASE_NAME setting and outputs a Django model module (a models.py file) to standard output. Use this if you have a legacy database with which you'd like to use Django. The script will inspect the database and create a model for each table within it. As you might expect, the created models will have an attribute for every field in the table. Note that inspectdb has a few special cases in its field-name output: This feature is meant as a shortcut, not as definitive model generation. After you run it, you'll want to look over the generated models yourself to make customizations. In particular, you'll need to rearrange models' order, so that models that refer to other models are ordered properly. Primary keys are automatically introspected for PostgreSQL, MySQL and SQLite, in which case Django puts in the primary_key=True where needed. inspectdb works with PostgreSQL, MySQL and SQLite. Foreign-key detection only works in PostgreSQL and with certain types of MySQL tables. Executes the equivalent of sqlall for the given appnames. Starts a lightweight development Web server on the local machine. By default, the server runs on port 8000 on the IP address 127.0.0.1. You can pass in an IP address and port number explicitly. If you run this script as a user with normal privileges (recommended), you might not have access to start a port on a low port number. Low port numbers are reserved for the superuser (root). DO NOT USE THIS SERVER IN A PRODUCTION SETTING. It has not gone through security audits or performance tests. (And that's how it's gonna stay. We're in the business of making Web frameworks, not Web servers, so improving this server to be able to handle a production environment is outside the scope of Django.) The development server automatically reloads Python code for each request, as needed. You don't need to restart the server for code changes to take effect. When you start the server, and each time you change Python code while the server is running, the server will validate all of your installed models. (See the validate command below.) If the validator finds errors, it will print them to standard output, but it won't stop the server. You can run as many servers as you want, as long as they're on separate ports. Just execute django-admin.py runserver more than once. Note that the default IP address, 127.0.0.1, is not accessible from other machines on your network. To make your development server viewable to other machines on the network, use its own IP address (e.g. 192.168.2.1) or 0.0.0.0. Port 7000 on IP address 127.0.0.1: Port 7000 on IP address 1.2.3.4: By default, the development server doesn't serve any static files for your site (such as CSS files, images, things under MEDIA_ROOT_URL and so forth). If you want to configure Django to serve static media, read the serving static files documentation. To disable auto-reloading of code while the development server is running, use the --noreload option, like so: Starts the Python interactive interpreter. Django will use IPython, if it's installed. If you have IPython installed and want to force use of the "plain" Python interpreter, use the --plain option, like so: django-admin.py shell --plain sql [appname appname ...] Prints the CREATE TABLE SQL statements for the given appnames. Prints the CREATE TABLE and initial-data SQL statements for the given appnames. Refer to the description of sqlinitialdata for an explanation of how to specify initial data. Prints the DROP TABLE SQL statements for the given appnames. Prints the CREATE INDEX SQL statements for the given appnames. Prints the initial INSERT SQL statements for the given appnames. For each model in each specified app, this command looks for the file <appname>/sql/<modelname>.sql, where <appname> is the given appname and <modelname> is the model's name in lowercase. For example, if you have an app news that includes a Story model, sqlinitialdata will attempt to read a file news/sql/story.sql and append it to the output of this command. Each of the SQL files, if given, is expected to contain valid SQL. The SQL files are piped directly into the database after all of the models' table-creation statements have been executed. Use this SQL hook to populate tables with any necessary initial records, SQL functions or test data. Prints the DROP TABLE SQL, then the CREATE TABLE SQL, for the given appnames. Prints the SQL statements for resetting PostgreSQL sequences for the given appnames. See http://simon.incutio.com/archive/2004/04/21/postgres for more information. Creates a Django app directory structure for the given app name in the current directory. Creates a Django project directory structure for the given project name in the current directory. Creates the database tables for all apps in INSTALLED_APPS whose tables have not already been created. Use this command when you've added new applications to your project and want to install them in the database. This includes any apps shipped with Django that might be in INSTALLED_APPS by default. When you start a new project, run this command to install the default apps. If you're installing the django.contrib.auth application, syncdb will give you the option of creating a superuser immediately. New in Django development version Discover and run tests for all installed models. See Testing Django applications for more information. Validates all installed models (according to the INSTALLED_APPS setting) and prints validation errors to standard output. Example usage: Explicitly specifies the settings module to use. The settings module should be in Python package syntax, e.g. mysite.settings. If this isn't provided, django-admin.py will use the DJANGO_SETTINGS_MODULE environment variable. Note that this option is unnecessary in manage.py, because it takes care of setting DJANGO_SETTINGS_MODULE for you. Example usage: Adds the given filesystem path to the Python import search path. If this isn't provided, django-admin.py will use the PYTHONPATH environment variable. Note that this option is unnecessary in manage.py, because it takes care of setting the Python path for you. Displays a help message that includes a terse list of all available actions and options. New in Django development version Inform django-admin that the user should NOT be prompted for any input. Useful if the django-admin script will be executed as an unattended, automated script. Disable the use of the auto-reloader when running the development server. Displays the current Django version. Example output: New in Django development version Example usage: Verbosity determines the amount of notification and debug information that will be printed to the console. '0' is no output, '1' is normal output, and 2 is verbose output. New in Django development version Tells Django where to find the various CSS and JavaScript files for the admin interface when running the development server. Normally these files are served out of the Django source tree, but because some designers customize these files for their site, this option allows you to test against custom versions. The django-admin.py / manage.py commands that output SQL to standard output will use pretty color-coded output if your terminal supports ANSI-colored output. It won't use the color codes if you're piping the command's output to another program. If you use the Bash shell, consider installing the Django bash completion script, which lives in extras/django_bash_completion in the Django distribution. It enables tab-completion of django-admin.py and manage.py commands, so you can, for instance... A small addition: Powered by Zoundry
]]>
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
安装Django
安装python2.5及以上版本,但不使用python3.0?/h2>
数据库如果用sqlliteQpython已经内徏Q不需另行安装Q如果需要用myslq或其他数据库Q需要自行安装?br />
接下来安装DjangoQ在widnwos下)Q?br />
1、从http://www.djangoproject.com/download/下蝲Django
2、在windwos下用python setup.py install 安装Q我原想使用python setup.py develop安装Q没成功Q,前提是设|好python环境和已安装setuptools?br />
3、将python安装目录下lib\site-packages\django\bin\django-admin.py 复制到python安装目录下的\scripts\目录?br />
下面可以试一下,启动cmdH口Q?br />
C:\Documents and Settings\Administrator>python
>>> import django
>>> django.VERSION
(1, 2, 0, 'rc', 1)
安装OK。开始创建第一个project吧?br />
1、选定一个目录,启动cmdH口Q?br />
F:\temp>django-admin.py startproject mysite2
F:\temp>
q将在当前目录下新徏一个projectQ名字ؓmysite2Q注意不要?django"{保留字作ؓproject名称Q,目录l构为:
2010-05-30 13:29 <DIR> .
2010-05-30 13:29 <DIR> ..
2010-05-30 13:29 557 manage.py
2010-05-30 13:29 3,387 settings.py
2010-05-30 13:29 561 urls.py
2010-05-30 13:29 0 __init__.py
4 个文?nbsp; 4,505 字节
2 个目?29,717,716,992 可用字节
先了解这么多吧,详细的文件内容单独再说?br />
2、启动http server:
F:\temp\mysite2>python manage.py runserver
Validating models...
0 errors found
Django version 1.2 rc 1, using settings 'mysite2.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
打开web browserQ输入地址http://127.0.0.1:8000/Q可以看到server已经启动了。当Ӟ如果你希望换一个端口,可以使用Q?span style="font-family: monospace;">
python manage.py runserver 端口?br />
3、接着配置databaseQ?br />
'django.contrib.contenttypes',内容理?
'django.contrib.sessions',session控制
'django.contrib.sites',多site理
如果用不到该appQ可以注释掉Q这不在database中徏立相关管理tables。然后用:
python manage.py syncdb
建立相应的tables?br />
4、在mysite2目录下,新徏一个自qappQ?br />
python manage.py startapp polls
新Z个polls目录Q内容如下:
2010-05-30 14:07 <DIR> .
2010-05-30 14:07 <DIR> ..
2010-05-30 14:07 60 models.py
2010-05-30 14:07 537 tests.py
2010-05-30 14:07 27 views.py
2010-05-30 14:07 0 __init__.py
5、创建modelsQ?br />
~辑models.py,内容如下Q?br />
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
q里有两个modelQPoll和ChoiceQ还存在一个one Poll to many Choice关系?br />
在setting.py 中将polls 加入到installed app 节点中,然后使用python manage.py syncdb 在database中新建相应的tables?span style="font-family: sans-serif;">table name 分别是:
polls_poll,polls_choice?br />
当然q有其他一些manage command:
6、用django shellQ?br />
python manage.py shell
q个cmd背后做了两g事:一是将mysite2加入到sys.path中去Q二是新ZDJANGO_SETTINGS_MODULE环境变量Q可以引用settings.py中的配置内容?br />
接下来就可以试了?br />
]]>
BTWQ如果有好的在线译q_Q哪位知我一声?br />
]]>
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
]]>
2、在url.py patterns中增加一行:
(r'^site_media/(?P<path>.*)$','django.views.static.serve',{'document_root':settings.STATIC_PATH}),
q要from django.conf import setting
3、在setting.py中加入一行:
STATIC_PATH='./medias'
如此讄后,可以在template file 中引用media中存攄静态文件了Q如Q?br />
<img src='/site_media/django.gif'>
详细可见limodou写的django step by step
]]>
1=django_py.acp
2=epydoc.acp
Q赞Q)
3、在acp文g中的定义的如Q?br />
(^\s*)cdef<space> = "\\1def ${1:}(self, ${2:}):\n\t${0}"
在几?{*:}之间可以用tab键直接{U输入位|?br />
4、在acp文g中?#8220;[”的自动完成:
[autostring_append]
[="!^]"
我想在输入[后自动补为[]Q由于[被定义ؓ了acp文g中的一个keyQ因此应该这样定义:
[autostring_append]
<square>="!^]"
q个questtionq得Climodou的回{?/a>Q非常感谢!
更多功能?a >ulipad的googlel?/a>
]]>address = [
('张三', '地址一'),
('李四', '地址?)
]
那么可以在template文gcsv.html中?br />row.0....方式引用?br />׃此前我从上一讲复制了address的定义:
address=[
{'name':'张三','address':'z阳树ַ'},
{'name':'里斯','address':'整整l散l?}
]
所以用row.0方式引用Ӟdjango不会报错Q但是什么内容也没有Q用row.name方式应用后正常?br />
]]>
]]>
Django Generic Views: CRUD
Published by Matt Croydon August 17th, 2005 in Projects, Python, Django
Note:Getting Started
django-admin.py startproject todo
. Make sure that the directory you created your project in is in your PYTHONPATH
, then edit todo/settings/main.py
to point to the database of your choice. Now would be a good time to set your DJANGO_SETTINGS_MODULE
to "todo.settings.main"
. Next move to your apps/
dir and create a new application: django-admin.py startapp tasks
and django-admin.py init
. The initial setup process is covered in much more detail in tutorial 1.The Model
todo/apps/tasks/models/tasks.py
):
from django.core import meta
# Create your models here.
class Task(meta.Model):
fields = (
meta.CharField('title', maxlength=200),
meta.TextField('description'),
meta.DateTimeField('create_date', 'date created'),
meta.DateTimeField('due_date', 'date due'),
meta.BooleanField('done'),
)
admin = meta.Admin(
list_display = ( 'title', 'description', 'create_date', 'due_date', 'done' ),
search_fields = ['title', 'description'],
date_hierarchy = 'due_date',
)
def __repr__(self):
return self.title
INSTALLD_APPS
in todo/settings/main.py
: 'todo.apps.tasks',
URL Configuration
todo/settings/urls/main.py
directly, but you’re probably best off decoupling your URLs to your specific app as mentiond in tutorial 3.
from django.conf.urls.defaults import *
info_dict = {
'app_label': 'tasks',
'module_name': 'tasks',
}
urlpatterns = patterns('',
(r'^tasks/?$', 'todo.apps.tasks.views.tasks.index'),
(r'^tasks/create/?$', 'django.views.generic.create_update.create_object',
dict(info_dict, post_save_redirect="/tasks/") ),
(r'^tasks/update/(?P<object_id>d+)/?$',
'django.views.generic.create_update.update_object', info_dict),
(r'^tasks/delete/(?P<object_id>d+)/?$',
'django.views.generic.create_update.delete_object',
dict(info_dict, post_delete_redirect="/tasks/new/") ),
(r'^tasks/complete/(?P<object_id>d+)/?$',
'todo.apps.tasks.views.tasks.complete'),
)
info_dict
to pass information about our application and module to the generic view handlers . The CRUD generic views need only provide these two pieces of information, but some generic views need more. See the generic views documentation for an explanation.Index
(r'^tasks/?$', 'todo.apps.tasks.views.tasks.index'),
todo/apps/tasks/views/tasks.py
:
from django.core import template_loader
from django.core.extensions import DjangoContext as Context
from django.utils.httpwrappers import HttpResponse, HttpResponseRedirect
from django.models.tasks import tasks
from django.core.exceptions import Http404
def index(request):
notdone_task_list = tasks.get_list(order_by=['-due_date'], done__exact=False)
done_task_list = tasks.get_list(order_by=['-due_date'], done__exact=True)
t = template_loader.get_template('tasks/index')
c = Context(request, {
'notdone_tasks_list': notdone_task_list,
'done_tasks_list': notdone_task_list,
})
return HttpResponse(t.render(c))
notdone_tasks_list
is (not suprisingly) a list of tasks that are not done yet. Similarly, done_tasks_list
contains a list of tasks that have been completed. We will use the template tasks/index.html
to render this view.todo/settings/main.py
). Here’s mine:
TEMPLATE_DIRS = (
"/home/mcroydon/django/todo/templates",
)
{% if notdone_tasks_list %}
<p>Pending Tasks:</p>
<ul>
{% for task in notdone_tasks_list %}
<li>{{ task.title }}: {{ task.description }} <br/>
Due {{ task.due_date }} <br/>
<a href="/tasks/update/{{ task.id }}/">Update</a>
<a href="/tasks/complete/{{ task.id }}/">Complete</a>
</li>
{% endfor %}
</ul>
{% else %}
<p>No tasks pending.</p>
{% endif %}
<p>Completed Tasks:</p>
<ul>
{% if done_tasks_list %}
{% for task in done_tasks_list %}
<li>{{ task.title }}: {{ task.description }} <br/>
<a href="/tasks/delete/{{ task.id }}/">Delete</a>
</li>
{% endfor %}
</ul>
{% else %}
<p>No completed pending.</p>
{% endif %}
<p><a href="/tasks/create/">Add a task</a></p>
Create Generic View
(r'^tasks/create/?$', 'django.views.generic.create_update.create_object', dict(info_dict, post_save_redirect="/tasks/") ),
create_object
generic view every time we visit /tasks/create/
. If we arrive there with a GET
request, the generic view displays a form. Specifically it’s looking for module_name_form.html
. In our case it will be looking for tasks_form
. It knows what model to look for because of the information we gave it in info_dict
. If however we reach this URL via a POST
, the create_object
generic view will create a new object for us and then redirect us to the URL of our choice (as long as we give it a post_save_redirect
).tasks_form.html
:
{% block content %}
{% if object %}
<h1>Update task:</h1>
{% else %}
<h1>Create a Task</h1>
{% endif %}
{% if form.has_errors %}
<h2>Please correct the following error{{ form.errors|pluralize }}:</h2>
{% endif %}
<form method="post" action=".">
<p><label for="id_title">Title:</label> {{ form.title }}
{% if form.title.errors %}*** {{ form.title.errors|join:", " }}{% endif %}</p>
<p><label for="id_description">Description:</label> {{ form.description }}
{% if form.description.errors %}*** {{ form.description.errors|join:", " }}{% endif %}</p>
<p><label for="id_create_date_date">Create Date:</label> {{ form.create_date_date }}
{% if form.create_date_date.errors %}*** {{ form.create_date_date.errors|join:", " }}{% endif %}</p>
<p><label for="id_create_date_time">Create Time:</label> {{ form.create_date_time }}
{% if form.create_date_time.errors %}*** {{ form.create_date_time.errors|join:", " }}{% endif %}</p>
<p><label for="id_due_date_date">Due Date:</label> {{ form.due_date_date }}
{% if form.due_date_date.errors %}*** {{ form.due_date_date.errors|join:", " }}{% endif %}</p>
<p><label for="id_due_date_time">Due Time:</label> {{ form.due_date_time }}
{% if form.due_date_time.errors %}*** {{ form.due_date_time.errors|join:", " }}{% endif %}</p>
<p><label for="id_done">Done:</label> {{ form.done }}
{% if form.done.errors %}*** {{ form.done.errors|join:", " }}{% endif %}</p>
<input type="submit" />
</form>
<!--
This is a lifesaver when debugging!
<p> {{ form.error_dict }} </p>
-->
{% endblock %}
Update
(r'^tasks/update/(?P<object_id>\d+)/?$', 'django.views.generic.create_update.update_object', info_dict),
tasks_form.html
, so with a little logic, 90% of the form can be exactly the same as the create form. If we go to /tasks/create/
, we get the blank form. If we visit /tasks/update/1/
we will go to the same form but it will be prepopulated with the data from the task with the ID of 1. Here’s the logic that I used to change the header:
{% if object %}
<h1>Update task:</h1>
{% else %}
<h1>Create a Task</h1>
{% endif %}
Delete
(r'^tasks/delete/(?P<object_id>\d+)/?$', 'django.views.generic.create_update.delete_object', dict(info_dict, post_delete_redirect="/tasks/new/") ),
/tasks/delete/1
using a GET
request, Django will automatically send us to the tasks_form_delete.html
template. This allows us to make sure that the user really wanted to delete the task. here’s my very simple tasks_form_delete.html
template:
<form method="post" action=".">
<p>Are you sure?</p>
<input type="submit" />
</form>
post_delete_redirect
.CRUD Generic Views And the Rest of Your Application
(r'^tasks/complete/(?P<object_id>\d+)/?$', 'todo.apps.tasks.views.tasks.complete'),
todo/apps/tasks/models/tasks.py
):
def complete(request, object_id):
try:
t = tasks.get_object(pk=object_id)
except:
# do something better than this
raise Http404
try:
t.done=True
t.save()
return HttpResponseRedirect('/tasks/')
except:
# do something better than this
raise Http404
Conclusion
24 Responses to “Django Generic Views: CRUD?/h4>
]]>
]]>
]]>django-admin.py and manage.py
This covers Django version 0.95 and the development version. Old docs: 0.90, 0.91
实际上,文gmanage.py会在每个Django工程创立的时候自动徏立,manage.py是django-admin.py功能的一个简单封装,它会为django-admin.py启用之前做好两项工作Q?/p>
如果你通过setup.py方式安装DjangoQdjango-admin.py脚本会被加入到系l\径。如果不在系l\径,你可以在Python安装路径下的site-packages/django/bin目录下找刎ͼq将他加入到你的pȝ路径下?/p>
一般情况下Q对单个Django projectQ用manage.py没有什么问题,如果你需要在不同的Django project间用django-admin.pyQ那么需要用DJANGO_SETTINGS_MODULE?-settings命o行参数?/p>
Usage
Available actions
adminindex [appname appname ...]
createcachetable [tablename]
dbshell
diffsettings
比较当前settings文g和Django~省settings文g之间的差异?/p>
在缺省settings中不存在的以"###"标识?/p>
inspectdb
install [appname appname ...]
runserver [optional port number, or ipaddr:port]
Examples:
django-admin.py runserver 7000
django-admin.py runserver 1.2.3.4:7000
Serving static files with the development server
Turning off auto-reload
如果要在服务已启动后止自动加蝲代码功能Q可使用--noreload参数?/p>
django-admin.py runserver --noreload
shell
sqlall [appname appname ...]
sqlclear [appname appname ...]
sqlindexes [appname appname ...]
sqlinitialdata [appname appname ...]
sqlreset [appname appname ...]
sqlsequencereset [appname appname ...]
startapp [appname]
startproject [projectname]
syncdb
test
validate
Available options
--settings
django-admin.py syncdb --settings=mysite.settings
--pythonpath
django-admin.py syncdb --pythonpath='/home/djangoprojects/myproject'
--help
--noinput
--noreload
--version
0.9.1
0.9.1 (SVN)
--verbosity
django-admin.py syncdb --verbosity=2
verbosity军_q行、调试信息显C别,0Q什么也不输出,1Q正常输出,2Q详l信息输?/p>
--adminmedia
Extra niceties
Syntax coloring
Bash completion
Comments
Indy September 27, 2006 at 4:04 a.m.
"Note that the default IP address, 127.0.0.1, is not accessible from other machines on your network. To make your development server viewable to other machines on the network, use its own IP address (e.g. 192.168.2.1) or 0.0.0.0." ... _as start parameter (e.g. manage.py runserver 192.168.2.1:8000)_
]]>
]]>
]]>
N必须使用自定义的模板语言Q?br />
]]>
模板
1、用 html 文g保存Q设计的变量?{{value_name}} 填充
2、需 from django.template import Template,Context 导入?
3、t=Template( 模板文g?)
c=Context( 模板变量内容 )
t.render(c)# 可以输出模板内容
4、 ?下面q段不理解什么意?
To prevent this, set a function attribute alters_data on the method. The template system won ?t execute a method if the method has alters_data=True set. For example:
def delete(self):
# Delete the account
delete.alters_data = True
5?Context 对象支持 push()/pop() Ҏ
6?模板文g中的标签Q?
没有 elseif;
For 循环中没?break ?continue
For 循环中的几个属性:
forloop.counter # 当前循环的次敎ͼ?1 开?
forloop.counter0 # 当前循环的次敎ͼ?0 开?
forloop.revcounter # 当前循环剩余ơ数Q从d@环次数递减
forloop.revcounter0 # 当前循环剩余ơ数Q从d@环次?-1 递减
forloop.first #boolean |如果为第一ơ@环,gؓ?
forloop.last # 同上
forloop.parentloop # 引用父@环的 forloop 对象
ifequal A B Q?AB 只能是模板变量、字W串、数?
pass Q如?A B 相等则执?
else
pass Q否则执?
endifequal
{# #} Q注?
{{A|B:”s”}} # ?A 执行 B qoQ?B qo可以有参?
几个qo器:
addslashes 加反斜杠
Date 格式化日期ؓ字符?
escape 转换为网늼?
length 长度
7?模板不能建立一个变量或者改变一个变量的|不能调用原生?python 代码
8??setting.py 中制定模板文件存攄目录Q?EMPLATE_DIRS Q,例:
TEMPLATE_DIRS = (
'/home/django/mysite/templates',
)
不要忘了最后的逗号Q除非你序列(Q换成列?[] Q但效率会降低;目录?/ 间隔
9?使用模板Q?
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})
可以填充到模板的变量换为locals()Q但性能会有所下降Q如
def current_datetime(request):
current_date = datetime.datetime.now()
return render_to_response('current_datetime.html', locals())
10、如果要引用讑֮的模板目录中子目录的模板文g ;
t = get_template('dateapp/current_datetime.html')
11、模板可嵌套Q模板文件名可用变量
{% include 'includes/nav.html' %}
{% include template_name %}
12、模板承,使用 extends 和一个特D的标签 block Q例Q?
Qbase.html
<head>
<title>
{% block title %}标题{% endblock %}
</title>
</head>
<body>
{% block content %}内容{% endblock %}
{% block footer %} 尾{% endblock %}
</body>
</html>
下面的模板承自 base.html
{% extends "base.html" %} Q这一行必LW一个模板标{行
{% block title %} 我的标题 {% endblock %}
{% block content %}
<p> 我的内容 </p>
{% endblock %} Q不一定要重新定义父模板中的每个模板块
通过 block.super 引用父模板块内容
http://groups.google.com/group/django-users django的google论坛列表
http://www.djangoproject.com/documentation/ django官方文档
http://code.djangoproject.com/browser/django/trunk/docs django官方最新文?可下?/p>
以前看过Q重新温习,开始看python框架DjangoQ已l安装,默认初始Ƣ迎界面已经出现了,Ҏhttp://www.woodpecker.org.cn/obp/django/django-stepbystep/newtest/doc/#id3介绍内容学习Q却出现了错误:
Could not import newtest.helloworld. Error was: No module named httpwrappers
查看django libQ确实没有这个类Q查扑֎因ing?.....
[24日补充]
googleC原因Q?br />HttpResponsecMdjango.utils.httpwrapers改到了django.http
参见Q?br />http://python.cn/pipermail/python-chinese/2006-April/023980.html
http://code.djangoproject.com/wiki/NamespaceSimplification
[再补充]
自我感觉dj的缺点:单独的标{ֺQ没有完全用pythonQ框架结构不是很清晰Q不如tapestryQ?br />
What would you think about making a screencast, a la Rails? That was a lot of Python to read, and I ended up skipping over it pretty quickly.
Cool stuff, but I noticed that the pluralize filter doesn’t work (see screenshot)
Dagur,
Yeah I noticed that but forgot to investigate it. I’ll let you know what I find out.
Steve,
Yeah, that would rock. I didn’t realize how much code I was going to have to escape and format before this post was done!
This is some cool stuff! It would be nice to have it as part of official Django documentation, if some small typos are corrected.
Unfortunately this example doesn’t work out of box.
1) Getting Started ?make sure to create your database _before_ you run django-admin.py init. It is not going to be created for you. Official Tutorial 1 (which is mentioned after “init? explains it in details.
2) The Model ?before going to play with the model make sure to install it using django-admin.py install tasks. It is explained in Official Tutorial 1.
3) URL Configuration ?probably urls should be decoupled as in Official Tutorial 3. It is better for novices to provide ready-made code instead of reference to Official Tutorial 3.
4) URL Configuration ?update should have the same parameters as create. Otherwise it doesn’t know where to forward to after updating.
5) URL Configuration ?most probably delete should forward to ?tasks/? ?tasks/new/?is not defined in your tutorial.
6) Index ?the same list is passed as ‘notdone_tasks_list?and ‘done_tasks_list? The latter should be done_task_list.
7) Index ?it should be noted that all template files are to be created in subdirectory ‘templates/tasks/? not directly in ‘templates/?
8) Create Generic View ?by some reasons tasks_form template has all ‘”?prepended with ‘\\? They should be removed, otherwise it doesn’t work.
9) Delete ?tasks_form_delete template should be renamed to tasks_confirm_delete.
I’m pretty sure that these tiny bugs are due to ongoing changes in Django and naturally occurring typos. Thank you for great tutorial!
Eugene,
Hey thanks for the feedback, I’ll do my best to update the tutorial this weekend. I did my best to get from scratch to my working situation, but I sure missed a couple of things along the way.
Thanks again for taking the time to go throught the tutorial and pointing out the little things.
Be aware that there are some significant and backwards-incompatible syntax changes for the models that might be showing up shortly, but I’ll definitely update this tutorial when/if that happens.
Great article.
Few minor additions that will help others (newb->newb). (I’m running django revision 525, FYI.)
1. A little reminder to “django-admin.py init tasks?to create the database table in the initialized database would help just before the screen pic of the index.html.
2. (r’^tasks/delete/(?P\d+)/?$? […] post_delete_redirect=?tasks/new/? ),
seems to work as
(r’^tasks/delete/(?P\d+)/?$? […] post_delete_redirect=?tasks/create/? ),
instead.
3. tasks_form_delete.html template seems to work as tasks_confirm_delete.hmtl instead
-=-
Awesome bite-sized article. Thanks for sharing.
I forgot to mention django-admin.py createsuperuser.
Matt, thank you the tutorial. I tried it but stopped with
/tasks/create/
because in my MS Explorer there is no submit button shown. Only input field.
Is it a problem on my side( django installation or MS Explorer or similar)?
Thank you for your reply
@Lada
You need to edit the template “tasks_form.html?and change all \?to ?
First of all , thank you Matt for the tutorial. I learnt a lot.
But I think that UPDATE should also have post_save_redirect like Create Generic View. For me it did not work without that.
Best regards,
Lad.
W A R N I N G ! ! ! :: This Tutorial is VERY MUCH OUT OF DATE!!!
So what is out of day ? can we have an updated tutorial ?
This article may be slightly out-of-date, but it had far more useful examples on generic views to extrapolate from then the “official documentation?on the topic.
Matt, many thanks!
hi
Prompt how to get rid of advertising?
Cool gay butts are online now. Gay Butts shows its http://www.gay-butts.be butts collection just in Febrary!
gay cock hugeWatch these horny sluts taking it in the ass for the first time and getting their virgin butts ripped wide open.
hot blonde huge dildoIt’s an experience they will never forget. Frenzied 3some and wild anal actions caught on video are waiting here for you.