Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Stripe and Starting dj-stripe
Stripe is great, but using a library makes it even better. Dj-stripe is a great django library for working with stripe to get people to subscribe to your service. See how simple it is to start working with dj-stripe.Watch Now... -
Django Extensions 1.3.8
We are happy to release: Django-Extensions Version 1.3.8 This brings the usual tons of fixes and improvements Get it at: https://pypi.python.org/pypi/django-extensions/1.3.8 Changes: Feature: show_urls, add option to specify dense or verbose output format Improvement: better support for django 1.7 migrations Improvement: better support for django's admin docs BugFix: runjob, job_name and app_name was swapped in error message Docs: Update link to chinese docs Python3: unreferenced_files, fix python3 compatibility Python3: pipchecker, fix python3 compatibility -
Release 0.8.0 alpha 2
We just released LFS 0.8.0a2. This is a feature release. Changes Removes double colons from management forms Removes django-tagging from dependencies Information You can find more information and help on following locations: Documentation on PyPI Demo Releases on PyPI Source code on bitbucket.org and github. Google Group lfsproject on Twitter IRC -
File download script
Greetings! If you recall, a while ago we saw how to write a file upload script. File download is also equally important. Let's see how to write a download script now.def download (request): filename = "/foo/bar/%s.%s" % (name, extension) f1 = open (filename, "r") response = HttpResponse (f1, mimetype = "type/extension") response['Content-Disposition'] = "attachment; filename = foo_bar.extension" return responseOk, now let's examine this code:Specify the file nameOpen this file in read modeCreate HttpResponse object with the following parameters: filename, and mimetype.MIME stands for Multipurpose Internet Mail Extension.Here's a list of all MIME types. Find the appropriate one for the extension you want: http://www.sitepoint.com/web-foundations/mime-types-complete-list/The second filename in the last but one line is the name and extension which the downloaded file should have. For example, your file may be .py, but you might want to make it download as .txtFinally, return the HttpResponse object, and et voila! You have your file ready for download.Note: As usual, this download will be triggered when the URL that points to the function download in the particular view is accessed.Cheers! -
Django 1.6 最佳实践: 如何正确撰写说明文档
之前已经提过, 说明文档对于任何项目都很重要. 有了reStructuredText和Sphinx后, 你可能会迫不及待地为你的项目撰写文档. 1. 使用reStructuredText RST文档可能是现在最流行的文档修饰语言了. reStructuredText便采用RST格式为项目撰写文档. Django和Python的文档都是使用reStructuredText撰写的. 以下是如何使用reStructuredText的简单例子: 段落标题 ==== 次标题 ---- **强调 (粗体)** *斜体* 简单连接: http://www.weiguda.com #) 计数列表项1 #) 计数列表项2 * 不计数列表项1 * 不计数列表项2 代码:: def like(): print("I like ice cream.") 2. 使用Sphinx Sphinx是一个从.rst文件生成HTML, LaTeX等格式的文件的工具. 具体用法见http://sphinx-doc.org/. 我们建议定期使用Sphinx更新文档, 以免错误产生. 3. 其他文档 之前我们讲过在项目根目录下放置requirements.txt文档, 用于储存项目依赖的第三方package信息. 还应当包含以下文件: 文件或目录存在理由说明 README.rst 每个Python项目都应当有 最少提供一句介绍项目目的的语句. 并能给出连接到安装说明的链接. docs/ 项目说明文档应放入其中, 这是Python社区的通用做法 docs/deployment.rst 让你节约一天时间来部署 如何部署项目的说明 docs/installation.rst 方便新开发者或使用新环境使用者开始 如何安装项目的说明 docs/architecture.rst 方便开发人员理解项目的构架, 和随着时间项目构架的变化 -
Release 0.8.0 alpha 1
We just released LFS 0.8.0. This is a feature release. Changes Added pluggable criteria Added pluggable addresses Added criteria for customer taxes Factored out PayPal to lfs-paypal. Added support for Celery (for mailing) Using South standard features for migration See README.txt for more changes. Information You can find more information and help on following locations: Documentation on PyPI Demo Releases on PyPI Source code on bitbucket.org and github. Google Group lfsproject on Twitter IRC -
Django 1.6 最佳实践: 如何正确进行 Unit Tests
为什么我们要写Unit test? 因为随着代码量的增加, 开发人员会忘记, 因此需要Unit test帮助我们保证程序的可靠性. 尤其是我们的程序涉及到医疗信息, 关乎生命安全, 或关乎其他人的资金. 1. test文件准备 当我们使用manage.py startapp创建新的Django app时, django会为我们创建test.py. 我们需要做的第一步是删除该文件, 然后建立test_models.py, test_forms.py, test_views.py文件: myapp/ __init__.py admin.py forms.py models.py test_forms.py test_models.py test_views.py views.py 如果项目中出现其他代码文件, 则建立相应的test文件. 这样做的原因是使测试文件扁平化, 方便我们更容易浏览和修改. 注意, 则是文件必须以"test_"开头, 否则django无法发现这些测试文件. 2. 如何写 Unit Tests a. 每个method只测试一项 每个test method应当尽量减少其测试的范围, 不要尝试在一个method中测试多个views, models, forms. 当然, 这里也会出现难题, 因为通常一个view会涉及到models, forms, 其他methods和functions. 此时我们就最简化我们的环境: # 测试 REST Api # test_api.py import json from django.core.urlresolvers import reverse from django.test import TestCase from myapp.models import Article class ArticleTests(TestCase): def setUp(self): Article.objects.get_or_create(title="A title", slug="a-slug") def test_list(self): url = reverse("article_object_api") response = self.client.get(url) self.assertEquals(response.status_code, 200) data = json.loads(response.content) self.assertEquals(len(data), 1) 以上代码中, 我们使用setUp method, 最简化了我们需要的model. 以下是一个更为完整的例子, 测试使用django_rest_framework构建的REST API: # test_api.py import json from django.core.urlresolvers import reverse from django.test import TestCase from django.utils.http import urlencode from myapp.models import Article class ArticleTests(TestCase): def setUp(self): Article.objects.get_or_create(title="title1", slug="slug1") Article.objects.get_or_create(title="title2", slug="slug2") self.create_read_url = reverse("article_rest_api") self.read_update_delete_url = reverse("article_rest_api", kwargs={"slug": "slug1"}) def test_list(self): response = self.client.get(self.create_read_url) # content中, 两个title是否都有? self.assertContains(response, "title1") self.assertContains(response, "title2") def test_detail(self): response = self.client.get(self.read_update_delete_url) data = json.loads(response.content) content = {"id": 1, "title": "title1", "slug": "slug1"} self.assertEquals(data, content) def test_create(self): post = {"title": "title3", "slug": "slug3"} response = self.client.post(self.create_read_url, post) data = json.loads(response.content) self.assertEquals(response.status_code, 201) content = {"id": "3", "title": "title3", "slug": "slug3"} self.assertEquals(data, content) self.assertEquals(Article.objects.count(), 3) def test_delete(self): response = … -
Translated text images for lazy programmers
In a previous post about django translations in this blog, I shared how to achieve a quick system that allowed me to manage translations stored in models and served using a template tag. In this post I will explain how to serve images that contain translated text and, hence, a localized image exists for each language.In my case, images are referenced from <img> HTML tags in templates and from CSS files. First of all we must create a basic structure in our img/ and css/ media folders, creating inside a directory for each language code we will use. For example, if we have two languages -- english and spanish -- we would create img/en/, img/es/, css/en/ and css/es/. In the CSS folders, the same files must be initially copied. If we have, for instance, just one style.css file, it must be both in css/en/style.css and css/es/style.css: css/ en/ style.css es/ style.css For the images, we should create the images that will be translated into each language code folder. All CSS files will reference the non-translated images in the same way, but their own file path to the translated image. I'll give an example. Let's say we have one background image … -
From LIKE to Full-Text Search (part I)
What do you do when you need to filter a long list of records for your users? We love and use Django so, most of the time, it is just as simple as: >>> Entry.objects.filter(title='Man bites dog') Well, actually that's not very useful. If you don't provide a lookup type it is assumed to be exact, which is not that user friendly. That query would miss 'Man Bites Dog' or "Man Bites Dog's Tail" and many more. That's why one of the most used field lookups is icontains which roughly translates to this SQL1: SELECT ... WHERE title ILIKE '%Man bites dog%'; That is much better. It works most of the time and you get to keep your comfy ORM. But what if you are looking for an Entry titled 'Man Bites Dogs Tails'? You would still miss it! And what about looking up the Entry's body too? Enter PostgreSQL's Full Text Search. Rather than using regular expressions to tackle this problem, we can use the full text search facilities that PostgreSQL offers. From the manual's introduction: Textual search operators have existed in databases for years. PostgreSQL has ~, ~*, LIKE, and ILIKE operators for textual data types, but they … -
Creating a custom user model in Django 1.6 - Part 1
Welcome back to our Django tutorial series. Before Django 1.5 customizing the user model was a bit of a hack as it involved creating a user profile with a one-to-one relationship to the user. All that changed in 1.5. In this tutorial we are goin to see how to substitue Django's default user model with our own and allow the use of a user's e-mail instead of it's username during the login process. Since 1.7 is not officially stable yet, this tutorial is meant for Django 1.6 but should also work with 1.7 (except for the South part which will be replaced in 1.7 by Django's own schema migration mechanism) -
如何开发合格的 Python/Django 第三方 Package
何为合格的Python/Django第三方package, 以下是一个为发布新的Python/Django package准备的Checklist. 1. 目的 你的package应当能做一件事情, 并且能把它做得很好. package名字应当具有描述性. package仓库的根目录应当以"django-"开头(如果是Django的package的话), 方便其他用户查找. 如果该package的部分功能需要借助其他Python package完成, 那么应当将其他package加入到依赖信息中. 2. 范围 你的package功能范围应该专注于一个小的任务(就像UNIX的原则一样), 这意味着该package的逻辑紧凑, 用户也更容易修改或取代这一package. 3. 文档 没有文档的package只能说是测试package, Docstring无法代替说明文档. 我们可以借助ReStructuredText和Sphinx这样优秀的工具撰写文档. 这些文档应到放在https://readthedocs.org上, 并使用webhooks来随时更新. package的依赖, 安装说明,都应当纳入文档中. 4. 测试 你的package应当包含测试代码. 测试代码能提高可靠性, 更能方便其他贡献者提交代码. 如果有必要, 应当将如何运行测试纳入文档中. 如果你和你的贡献者们能在提交pull request运行测试, 那必定会带来更高质量的代码. 5. 维护 你的package应当定期维护更新. 每次更新代码库中的代码时, 如果有必要, 不要忘了上传到Python Package Index中. 6. 社区 良好的package一般都会得到社区的贡献者帮助提交的代码和补丁, 所有贡献者的名单应当列在CONTRIBUTORS或AUTHORS文档中. 尽力管理由你领导的package产生的社区. 如果你的代码被fork了, 应当尽力给与关注, 试着将部分内容merge到你的package中. 如果该fork与原来的package功能上已有分化, 则应提醒该fork开发人员重新命名该fork. 7. 模块化 你的package应当能简单的被应用到任何Django项目中(针对Django package), 并且不会代替其他核心部件(templates, ORM等). 尽量减少对其他package的影响. 8. PyPI 对于 major 和 minor release, 应该将其放置到PyPI, 方便其他开发人员下载获得源代码. 对各release使用适当的版本号. 9. 依赖 package中所依赖的其他package应当使用宽松版本号写入requirements中, 而不是用绝对版本号: # requirements # 不使用 Django==1.5.2, 而是用 Django>=1.5,=1.2.3, 10. 版本号 对于Python/Django package, 可以参考PEP 386对package进行版本编号, 形式如A.B.C: A代表着major release, B代表minor relsean, C代表bugfix release. 11. 名字 package的名字至关重要. 恰当的命名使得package容易被发现. 12. 使用协议 License 每个package都应当有合适的License, 对于没有特殊的package可以使用BSD或MIT license, 这两个license允许大多数商用和非商用. 将License的内容拷贝黏贴到LICENSE文档中. 13. 代码 你的package中的代码应当清晰易懂, 不要使用奇怪的python语法. 14. URL Namespaces 对于Django package, 为了避免与其他package的url设置重提, 可以使用的URL namespaces. -
The SaaS methodology
Hey guys! This one's not a tutorial. So just sit back with a cup of coffee and relax. I assure you this is going to be fun.Up until now we've seen two names associated with programming in Django. The first one is Web Design, which is very mundane. Any Tom, Dick and Harry can visit a CMS like Wordpress nowadays and make a website for themselves.Then we saw the slightly more colorful and yet highly misunderstood name Web Application Design, or simply Web App Design.I'm finally going to tell you a name that is not only prestigious, but one that will blow your mind whole. It's SaaS, or Software as a Service.I'll give you a minute to let the awesomeness sink in.Done?Good.Yes, Django programming falls under software. People think that software only means the ones we open on our computers.The Service in SaaS is not service as in social service. It means the service you provide to computers.SaaS pieces are hosted on servers and can be accessed from anywhere with an Internet connection. They may be free or charged. The charged ones are called Proprietary Software. Also note that the free ones are not called Open Source. That's completely different. … -
An important thing
Hey guys! This is an important one. This had me stymied for a day and a half. Do not forget to commit the changes before closing the connection in the particular view if that view contains any of insert, update or delete queries. It doesn't matter with select queries, but for the aforementioned it is a must. -
A Trekking Expedition through the Chandrakhani Pass Part 2
This post is the continuation of the Part 1 of the experience. To read Part 1 please click here. Day 5- Behali(8300 ft) to Waching(9300 ft) This was probably the easiest stretch of the trek. We had an estimated time of 3 hours to cover about 5 kms. We had a couple of problems before starting off from Behali. Firstly, one of the participant Ananth had his shoe sole come off. In spite of inquiring around, we couldn’t find an extra pair of shoes for him. So, he just performed a temporary hack by using some glue and rope. The second issue was another participant Prateek fell ill and had high fever. He consumed a lot of paracetamol to help him trek for the remaining journey. After we left Behali, we got to see some glacial left overs on the way. This was our first encounter with ice. After trekking for about two hours upwards, we reached a flat land where we halted for lunch. We were running well ahead of schedule and hence, decided to take a break of atleast 2.5 hours. One particular sport unites everyone in India. And that is the game of cricket. We managed to … -
Magnificent Meetup for Bangalore Django Users!
"Krace played a key role in bringing back the almost dead Bangalore Python Users Group into action."- Shreyansh Singhal on YourStory.Few weeks back, while I was searching for Python I came across Krace's blog. Then I checked his Github, Stackoverflow, Quora profiles and I was amazed.Last week when I found there was a Django users workshop by him & his friends, without a second thought I decided to go.Since the organizers marked the location (ThoughtWorks Technologies) on Google Maps, its quite easy to reach there w/o any trouble.Workshop took place from 10 A.M. to 5 P.M. The goal was to build a simple phone book app to add/view/edit contacts with Django & SQLite.Before starting of workshop, organizers helped with installation of requirements(Django & South).Krace showed the agenda. At each & every step, he first explained what he is going to do. Then he would do it and gives us time to complete the task. All organizers patiently helped in troubleshooting the errors at each and every step. In the end we had little Q & A session.Overall it was a great hands on experience with great content & crew! Looking forward for more meetups!! Thank You very much!!!If you are form Bangalore & love Python, don't … -
Django的秘密武器: 第三方模块/插件
Django真正的强大之处不在于他是一个web framework, 而在于开源社区提供的庞大的持续增长的第三方模块. 这些模块是由来自不同领域的的程序员创建的, 因此能大大减少你的工作量. 大多数的Django项目都由类似或相同的模块经过不同组合而成, 因此大多数的Django开发时关于将已存在的第三方模块整合到一起. 如果你想尝试自己一个一个的创建出这些模块, 那你可得相当努力才行了. 接下来, 我们介绍以下渠道来获取第三方模块: 1. PyPI PyPI是Python Package Index的简称, 其官方网址是https://pypi.python.org/pypi. 截止2014年初, 已有37,000个django相关的第三方模块. 对于大多数的Python社区而言, 只有在PyPI上发布了的项目才算做正式发布. PyPI不光是一个模块目录, 它更是世界上最大的python模块信息中心. 每次你使用pip安装python模块时, pip便会从PyPI上下载相应的模块. (如果你在中国大陆, 你可能需要使用阿里云或豆瓣的PyPI镜像网站) 2. DjangoPackages.com Django Package是一个可重复利用的app和工具的目录. 不像PyPI, django package不会储存模块本身, 而是提供了相似模块的比较表格, 方便用户比对查找需要的模块. 3. 不要重复自己 作为一个Python开发人员, 我们应当了解这些工具, 否则就是白白浪费了这些已存在的资源. 更为重要的是, 我们不应当重复发明轮子(don't reinvent the wheel). 那些最好的第三方模块都是由世界上最具竞争力的开发人员, 花费大量时间创造, 撰写文档, 经过全面测试而来的. 站在这些人的肩膀上可以学到更多的东西. 但是, 如何识别好的第三方模块也是十分重要的! 花时间去了解, 测试那些第三方模块是一件值得我们做的事情. -
Django 1.6 最佳实践: 如何正确使用 User Model
本篇主要讨论一下User Model的使用技巧. 注意, 由于Django 1.5之后user model带来了很大的变化, 本篇内容只针对django 1.5之后的版本. 1. 确定 User Model 我们推荐一下方式来确定某一django项目使用的user model: # 使用默认User model时 >>> from django.contrib.auth import get_user_model >>> get_user_model() <class 'django.contrib.auth.models.User'> # 使用自定义User model时 >>> from django.contrib.auth import get_user_model >>> get_user_model() <class 'xxx.models.UserProfile'> 2. 使用settings.AUTH_USER_MODEL 自从django 1.5之后, 用户可以自定义User model了, 如果需要外键使用user model, 官方推荐的方法如下: 在settings中设置AUTH_USER_MODEL: # settings.py # 格式为 "<django_app名>.<model名>" AUTH_USER_MODEL = "myapp.NewUser" 在models.py中使用 # models.py from django.conf import settings from django.db import models class Article(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL) title = models.CharField(max_length=255) 还有需要注意的是, 不要在外键中使用get_user_model(). 3. 自定义 User Model 方法1: 扩展 AbstractUser类 如果你对django自带的User model刚到满意, 又希望额外的field的话, 你可以扩展AbstractUser类: # myapp/models.py from django.contrib.auth.models import AbstractUser from django.db import models class NewUser(AbstractUser): new_field = models.CharField(max_length=100) 不要忘了在settings.py中设置: AUTH_USER_MODEL = "myapp.NewUser" 方法2: 扩展 AbstractBaseUser类 AbstractBaseUser中只含有3个field: password, last_login和is_active. 如果你对django user model默认的first_name, last_name不满意, 或者只想保留默认的密码储存方式, 则可以选择这一方式. 方法3: 使用OneToOneField 如果你想建立一个第三方模块发布在PyPi上, 这一模块需要根据用户储存每个用户的额外信息. 或者我们的django项目中希望不同的用户拥有不同的field, 有些用户则需要不同field的组合, 且我们使用了方法1或方法2: # profiles/models.py from django.conf import settings from django.db import models from flavors.models import Flavor class EasterProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) favorite_ice_cream = models.ForeignKey(Flavor, null=True, blank=True) class ScooperProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) scoops_scooped = models.IntergerField(default=0) class InventorProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) flavors_invented = models.ManyToManyField(Flavor, null=True, blank=True) 使用以上方法, 我们可以使用user.easterprofile.favorite_ice_cream获取相应的profile. 使用这一方法的坏处可能就是增加了代码的复杂性. -
A Trekking Expedition through the Chandrakhani Pass Part 1
This is my first non-technical post on my blog. I going to describe my experiences of the trek through the Chandrakhani pass. This trek was organised by the Youth Hostels Association of India. The post is divided into two parts – The experiences of the first few days in the first post and the experiences of the remaining days in the second post. We were a group of 19 people from IIT Madras who set off on our last group trip before graduating from college. The 7 days that followed was filled with fun, adventure and excitement. I will describe a day-by-day account of the entire trek in this post. Day 0 – Reporting Day This day was reserved for the participants to arrive at the Seobagh Base Camp near Kullu. This base camp, at any given time, housed 5 groups of trekkers. This is where the orientation and the initial activities took place. This place is about 4 km from center of Kullu town. Plenty of buses ply from Kullu to this camp. We arrived on the morning of May 23, 2014 from Delhi. The journey past Chandigarh, through the hill section, is exotic and is in … -
Displaying images
As I mentioned in a previous post, <img src = ""> does not work in Django. I mean, it does work, and that's how we are going to display images, but it doesn't work if you give local machine addresses like /home/foo/bar or C:/images/foo/bar. This is actually a good thing. Django has a very sophisticated method of handling images and other files, often called as static files.If you open your settings.py file, you'll see two URLs: STATIC_URL and MEDIA_URL. These can be used to render static files and media in general.Now there are two ways of doing this:Using the in-built {{ STATIC_URL }} or {{ MEDIA_URL }} variables. But as I have not posted about Django's templating language, we'll put this one on the back burner. But rest assured, once you understand the templating language, how to use these will be self-evident.Using full URLs, including the values specified in {{ STATIC_URL }} and {{ MEDIA_URL }}. We'll be using the second method. The only disadvantage of this method is that if the directory containing static files changes then you have to make sure that change reflects in all templates. In the first case, this would happen automatically.Let's assume you're running your … -
Django 1.6 最佳实践: 如何正确使用 Django Admin
当有人问起, Django相对于其他web framework有什么优势吗, Django admin总是能第一时间出现在回答中. 在本篇中, 我们讨论一下如何正确使用admin. 1. Django Admin 不适合最终用户使用 Django admin是为管理员设计的, 而不是给最终用户使用的. Django admin的存在是为了方便管理员添加修改删除数据和管理站点任务. 2. 列表显示 如上图, 因为model的默认文本显示是 xxx object, 所以在admin列表页中默认显示的也是xxx object. 如果希望显示更有用的信息 我们可以进行如下设置: 为model写__unicode__()方法 如果希望model在列表页中显示更多项, 则需要使用list_display __unicode()__例子: # models.py from django.db import models class Article(models.Model): title = models.CharField(max_length=100) slug = models.CharField(max_length=100) content = models.TextField() is_published = models.BooleanField(default=False) def __unicode__(self): return self.title # admin.py from django.contrib import admin from .models import Article admin.site.register(Article) 结果: 如果希望显示其他项: # admin.py from django.contrib import admin from .models import Article class ArticleAdmin(admin.ModelAdmin): list_display = ('title', 'is_published') admin.site.register(Article, ArticleAdmin) 结果: 3. 为ModelAdmin增加动作 我们可以为ModelAdmin增加method或function, 以此使admin界面更符合我们的需求. 例如, 我们希望在在admin界面中显示一个明确地URL, 但当我们在model中定义了get_absolute_url()方法后, django admin默认给我们的却是一个与我们想要的URL完全不同的URL. 于是我们可以通过以下方法定义该URL: # admin.py from django.contrib import admin from django.core.urlresolvers import reverse from django.utils.html import format_html from .models import Article class ArticleAdmin(admin.ModelAdmin): list_display = ('title', 'is_published',) readonly_fields = ('show_url',) def show_url(self, instance): url = reverse('article_detail', kwargs={'pl': instance.pk}) response = format_html("""<a href="{0}">文章预览preview</a>""", url) return response show_url.short_description = u"文章预览" # 显示HTML tag # 对于用户提交的数据, 永远不要这么设置! show_url.allow_tags = True 注意, allow_tags属性, 其默认值是False, 如果错误使用将会带来安全隐患. 如果设置为True, 在admin中会允许显示HTML tag. 因此我们使用的原则是, 对于用户输入的信息, 永远不设置allow_tags=True. 只有当其内容是系统生成, 用户无法修改的时, 才能使用allow_tags=True. 4. 不在多用户编辑环境使用list_editable django admin为我们提供了在列表页修改model属性的功能, 这样方便管理员一次修改多个属性. 如果管理员只有一个人的话, 那就没问题, 但在多用户环境中时, 却是会存在一个很严重的潜在问题. 因为在list页提交的修改信息, 记录的是位置, 而不是model的主键. 举个例子, 文章列表页默认按照创建顺序逆序排列, 用户A打开文章列表页, 并开始修改, 同时用户B增加了一篇新文章, 此时, 当用户A提交修改后其后的文章信息都会出错. 这是一个一致的django bug, 可见ticket 11313, 相信在将来这一bug会得到修正. -
Django 1.6 最佳实践: 替换Django关键部件
许多程序员会问, 我能不能替换掉django中的某些部件, 简单而言, 我们不赞成这么做. 因为替换之后: 可能无法使用Django第三方模块 无法使用django admin 可能会无法升级Django 如果你已经尝试了使用各种方法, 比如使用debug自己的code, 降低query次数, caching, 违反标准化数据库原则, 并且你的用户数达到一定数量级时, 我们才会建议尝试替换掉django自身的关键部件. 常见的部件替换 在Django项目开发过程中, 最常见到的替换应该就是将SQL数据库替换为NoSQL数据库, 和将django template引擎替换为Jinji2引擎了: NoSQL 如果你使用Memcached或Redis的话, 你已经在使用NoSQL数据库了, 但是当你想使用NoSQL完全代替SQL数据库时, 可能会出现问题. 如果项目的已经达到优化的极限, 已经使用数据库index, caching, query优化, 用户访问数超过50000000, 并且你很了解NoSQL的话, 那么可以考虑使用NoSQL数据库代替SQL数据库. NoSQL最大的问题是可能会引起数据出错, 因为NoSQL没有ACID机制; 也千万不要使用NoSQL来做SQL的任务; 在切换到NoSQL之前, 应当做好充分的调查, 而不是去相信那些不实的宣传. Jinjia2 不要因为别人说jinja2比django template性能优异而盲目的切换到jinja2. 我们完全可以在个别会产生大于1MB HTML的view中使用jinja2, 而在其他view中使用django template. 有人以Jinja2性能优于django template为借口. Django已经进行了诸多改进, 因此这一借口已经无法成立了. 新的测试也显示django template的性能已得到大幅度提升. 在切换到Jinja2之前, 请确保, 不要在template中使用大量业务逻辑, 试着将它们移到其他正确的代码位置, 比如model, view中. 只有当单一页面HTML数据大于1MB时, 你可能需要切换到Jinja2: # mysite/views.py import os from django.conf import settings from django.http import HttpResponse from jinja2 import Environment, FileSystemLoader from syrup.models import Syrup JINJA2_TEMPLATES_DIR = os.path.join( settings.PROJECT_ROOT, "template", "jinja2" ) JINJA2_LOADER = FileSystemLoader(JINJA2_TEMPLATES_DIR) JINJA2_ENV = Environment(loader=JINJA2_LOADER) TEMPLATE = JINJA2_ENV.get_template("big_syrup_list.html") def big_syrup_list(request): object_list = Syrup.objects.filter() content = TEMPLATE.render(object_list=object_list) return HttpResponse(content) 正如以上代码那样, 我们可以简单地替换单个view中的template模板. -
Django 1.6 最佳实践: 如何在 Django Template 中正确使用 REST API
之前的博文中, 我们已经提到创建REST API和使用django tenplate的最佳实践, 接下来我们将两者结合起来, 如何在django中使用现代JavaScript框架显示REST API内容. 随着JavaScript引擎的速度越来越快, 和JavaScript社区的日趋成熟, 使用JavaScript框架来显示由REST API提供的内容也越来越方便. 目前较为流行的几个JS框架包括: Angular.js Backbone.js Ember.js jQuery 以上这些JS库能大大提高用户体验. 但是, 我们还需要考虑到其他方面: 1. Debug debug前台JS代码不仅仅是console.log()和console.dir(). 许多工具都可以用来debug前台JS, 有些工具还是专门针对某一JS框架的. 一旦选中一个工具 那么最好是花几天的时候好好学习一下. 你可以使用Chrome developer tools或Firefox web developer. 2. 搜索引擎 现在由REST API为前台提供内容的单页式网站也已经很常见了, 但是如果不注意, 网站的内容可能无法被Google, 百度, Bing等搜索引擎抓取到. 如果这些内容都是需要验证后才能查看的, 这样可能没有什么问题. 但如果你希望搜索引擎为你带来流量, 那就需要一些额外的步骤来解决这一问题了. sitemap.xml 首先你可能无法使用django内置的sitemap app了, 你必须手动写好你的sitemap.xml. 使用第三方服务 你也可以选择使用第三方服务, 使你的网站可被抓取, 比如brombone.com. 等待搜索引擎进化 如果SEO对于你而言不重要, 那么你可以慢慢等待搜索引擎能够识别这样的网站. 实际上, 各大搜索引擎已经注意到这种变化, 部分已经具备抓取能力. 3. 延迟 http请求的传输是需要时间的, 很不幸的, 这一时间是人类能够察觉到的. 再加上前台后台处理数据的时间, 整个web app总会有延迟现象的发生. 为了更好的用户体验, 我们需要修饰或减少延迟的时间: 使用动画效果 我们可以在延迟发生时使用动画效果, 来分散用户的注意力. 假装成功了 还有一种方式是装作http request成功了. 我们使用JS来处理失败错误, 由于JS可以是异步的, 使得用户可以感知不到这一延迟. 但这样做可能很复杂. 地理位置 尽量使服务器位置接近用户, 比如使用CDN等. 如果你有充分的资金和时间, 那这是我们推荐的解决方法. 限制用户 有时, 由于资金或其他问题, 无法解决延迟问题, 那么还有一个选择就是按照地理位置屏蔽用户. 这虽然不是一个好的选择, 但却能避免不好的用户体验. 正确使用JavaScript 以下是JavaScript的一些常见的错误模式: 一律使用单页式 单页式的网站建设既有挑战性又很有趣, 但是传统的网站都需要转为单页式的吗? 传统网站完全可以只包含一两个单页式的网页, 但完全转为单页式网站却没有这个必要. 缺少测试 当我们使用新的框架时, 我们倾向于跳过写测试. 一句话, 请不要这样. 随着时间的增加, 前台将会变得越来越复杂, 当缺少测试程序时, 这种复杂性就难以使用人工的方式去debug了. 不理解JS内存管理 单页式的网站很棒, 但有时这类网站需要在用户的浏览器中停留很久. 如果没有良好的内存管理, 我们的网站就会拖慢浏览器的速度, 设置导致浏览器崩溃. 每个javascript框架都包含了如何处理这些问题的工具和意见, 因此我们需要事前了解这些内容. 在DOM中储存数据 在使用jQuery一段时间后, 我们可能倾向去将数据储存于DOM中. 但是对于其他JavaScript框架, 这种方法可能不是最好的解决方法. 每个框架都有其自身的处理用户数据的方法, 如果我们舍弃这些方法不用, 那我们可能就无法完全使用这些框架的所有功能和特性. 4. AJAX和CSRF 如果你同时使用Django和AJAX, 那么你会发现AJAX也会触发CSRF保护. Django的CSRF保护看似为我们带来了很多不便, 如果你使用jQuery 1.5+, 你可以创建以下csrf.js, 并在使用AJAX网页上使用: // csrf.js // 使用jQuery 1.5+ function csrfSafeMethod(method) { // 以下http动作不需要csrf保护 return (/^(GET|HEAD|OPTION|TRACE)$/.test(method)); } $.ajaxSetup({ crossDomain: false, beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type)) { xhr.setRequestMethod("X-CSRFToken", csrftoken); } } }); -
How to learn Django without installing anything
Here is way of learning to create a website using the Django web framework without having to install anything on your local computer. This might be useful if: you are intimidated by all the hurdles you need just to get to the beginning of the tutorial. you can't install things on your own computer. or you want to be able to carry on with the learning from a different computer, without copying your progress or installing things on the other computer. Prerequisites I'm assuming you already know how to program in Python, or are sufficiently experienced with programming that you don't mind learning Python while learning Django at the same time. If not, have a look at these starting points: If you don't know much about programming, try Learn Python The Hard Way. If you are experienced with other programming languages, but not Python, try, Dive Into Python. I'm assuming you are reasonably comfortable with typing things into a command prompt or terminal. Thankfully, even if you are not, you'll be doing everything in a virtual machine somewhere on the internet, so you can't break anything! Steps Go to http://runnable.com/ and sign up for an account. Create a new project, … -
Backing up
Backing up your files is extremely important. If the server you've hosted your site on crashes and you don't have a copy of the files then your goose is cooked. You'll have to start from scratch.I've written the code for backing up files and your MySQL database. Here's the link:https://github.com/AgentK1729/File-BackupIn case you have an SQLite database, there's no need to back up the database as shown in the code, there'll be a readymade .db file. Just copy it somewhere reliable. -
Troubleshooting
More often than not, your site will generate an error that will cripple its functioning. This is not a bad thing, however. Not only does it let you grow as a programmer, but also it is said that if your code executes the first time without any errors, you're not a good programmer!I'm currently developing a commercial website and this happened to me today. I did some resizing and suddenly all my webpages showed the same message: 'Unhandled Exception'.After hours of hunting down the source, I discovered that I deleted two apps but forgot to remove them from the INSTALLED_APPS in the settings.py.The point of this story is that such things happen to everyone without exception. The important thing is to not panic. Here's what you do:Close your eyes and take a deep breath.Recall the last point where it was working.Retrace the steps you took from that point till now and evaluate what might have caused the error.The error can also be caused by some very insignificant things, which make you want to kick yourself.The one I described.Forgetting to 'Reload' the site in case you have hosted it on a server.Not saving a file you made changes to.So guys, remember …