Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
The End of an Era
Django migrations have come a long way, but it stands on the shoulders of one project that has come just a little bit further. It's been a long while since I posted news of the Django migrations work; my apologies for that, and I'll write about what's been going on there (and the upcoming 1.7 release) soon. For now, though, I want to focus on the past, rather than the future. Today I've released what is probably the last version of South, version 1.0. South has had very few changes for a couple of years now, and the only reason it's getting a release at all is one new feature to aid in the upgrade to Django 1.7. Easier Upgrades This feature is that South will now look first for a south_migrations directory, before falling back to migrations. This one small change means that third-party libraries and apps can support both South and the new-style 1.7 migrations, by moving their legacy South migrations into the south_migrations directory, and having the Django migrations in the migrations directory. This is the end result of the attempt to try and introduce a forwards-compatible "South 2" that would read the new migration format but … -
在 Selenium 中设置不同的浏览器进行 web application 测试
通常我们当我们需要测试JavaScipt, 兼容性或模拟用户行为时, 我们会用使用 Selenium 和 django 的 LiveServerTestCase Class. 默认情况下 Selenium 的 WebDriver 启动的是 Firefox 浏览器, 那么如何使用 Selenium 配合其他浏览器呢? 当然 Selenium 是支持其他浏览器的, 但如果想要使用其他浏览器, 需要要我们做一点不同的设置. 接下来, 我们就演示一下如何设置: 1. Firefox 首先我们演示一下默认情况下如何打开 google.com 并截图: from selenium import webdriver browser = webdriver.Firefox() browser.get('http://www.google.com') browser.save_screenshot('screen.png') browser.quit() 2. Chromium 或 Chrome 首先你要安装有 Google Chrome 浏览器. 你还需要chromedriver, 你可以在Chrome Driver官网上下载到 在 Selenium 中使用 Chrome: from selenium import webdriver browser = webdriver.Chrome(executable_path='/usr/lib/chromium-browser/chromedriver') browser.get('http://www.google.com/') browser.save_screenshot('screen_chromium.png') browser.quit() 3. Android 浏览器 在 Android 设备上运行 Selenium 的话, 你必须安装 Selenium server APK, 并启动该APK. 如果是在虚拟机中运行的话, 则需要使用 adb 安装 Selenium server APK: 显示所有 Android 虚拟机: ./adb devices 记下你想要安装的虚拟机ID, 并安装: ./adb -s ID_NUMBER -e install -r android-server-*.apk 再启动该虚拟机. 我们还需要为已经启动的虚拟机设置端口映射, 这是为了让 Selenium 能够与服务器交流: ./adb -s ID_NUMBER forward tcp:8080 tcp:8080 如果使用的是真实的设备, 那我们只需要使用设备的真实IP地址即可: from selenium import webdriver desired_capabilities = webdriver.DesiredCapabilities.ANDROID desired_capabilities['deviceOrientation'] = 'landscape' #portrait browser = webdriver.Remote("http://localhost:8080/wd/hub", desired_capabilities=desired_capabilities) browser.get('http://www.google.com') browser.save_screenshot('screen_android.png') browser.quit() 4. iOS (iPad, iPhone) iOS只能在OSX上使用. 你可以查看ios-driver. 5. 在线 Selenium 服务 如果你想方便的使用 Selenium, 那么也可以尝试 saucelabs.com 或 testingbot.com. 他们提供了在线 Selenium 测试 API. -
Webby stuff
Latest Evennia come with a range of improvements, mainly related to its integration with the web.New and improved ways to expand the website/webclientThanks to the work of contributor Kelketek, Evennia's Django-based web system (website and webclient) has been restructured to be much easier to expand. Previously you had to basically copy the entire web/ folder into your game and modify things in-place. This was not ideal since it made it inherently harder to update when things changed upstream. Now Evennia makes use of Django's collectstatic functionality to allow people to plugin and overload only the media files and templates that they need. Kelketek wrote a new and shiny web tutorial explaining just how things work. Websocket-based webclient with OOBEvennia's webclient was an ajax-based one using a long polling ("comet") paradigm to work. These days all modern browsers support websockets though, a protocol that allows asynchronous server-client communication without the cludgery of long polling. So Evennia's new webclient will now use websockets if the browser supports it and fall back to the old comet client if it does not.The new client also has full support for OOB (Out-of-band) communication. The client uses JSON for straight forward OOB messaging with the server. As part of this, … -
学习Python Django的一些资料
本篇中将列举一些较新的学习python和django的资源. 以下资源主要针对Django 1.6, Python 2.7.x或Python 3.4.x: Python 初学者 Learn Python the Hard Way: http://learnpythonthehardway.org, 如果你不了解Python, 那么这是一个既有免费的HTML资料, 又有付费课程的网站. Django 初学者 Django 官方文档: https://docs.djangoproject.com/en/1.6/, 从django 1.5开始, 官方文档有了非常大的改进和补充, 如果你使用过早期版本的Django, 那么请确保阅读过正确版本的官方文档. Tango with Django: http://www.tangowithdjango.com, 使用django 1.5.4 和大量例子的教程. Test-Driven Web Development Python: http://chimera.labs.oreilly.com/books/1234000000754/, Harry Percieval撰写的, 如何在Django开发过程中使用敏捷/TDD开发的流程, 其HTML资源是免费的! Getting Started with Django: 由Django Software Foundation赞助, 针对django 1.5的免费视频课程, 制作者是Kenneth Love. Django 中高级 Pro Django, 第二版: Pro Django, 一本带你深入了解Django的书. ccbv.co.uk: ccbv.co.uk, 针对Django Class based view提供了详细的method和attribute介绍. GoDjango: http://godjango.com, 一系列关于django的视频教程. Python 其他资料 Python Cookbook 第三版: Python Cookbook, 关于Python 3.3+的书, 其中含有大量优秀的代码. Treading on Python Volume 2: Treading on Python Volume 2: Intermediate Python, 书中包含了许多高级Python结构. Writing Idiomatic Python 3.3: Writing Idiomatic Python 3.3, 书中包含了很多代码优化, 增加可读性的技巧. Writing Idiomatic Python 2.7.3: , 针对python2.7.3. Effective Django: effectivedjango.com, 包含了Nathan Yergler在PyCon 2012, PyOhio 2012, PyCon 2013中的演讲和笔记. JavaScript 资料 Secrets of the JavaScript Ninja: Secrets of the JavaScript Ninja JavaScript: The Definitive Guide: JavaScript: The Definitive Guide JavaScript: The Good Parts: JavaScript: The Good Parts JavaScript Patterns: JavaScript Patterns -
Python语言的一小点优雅表现
本篇中, 我们展示一下一段非常小的代码, 这段代码十分吸引我们, 因为它使用十分优雅和直接的方式解决了一个常见的问题. 比如, 我们希望希望检测"一段string是否以特定的字符串结尾?", 通常我们使用: if needle.endswith('ly') or needle.endswith('ed') or needle.endswith('ing') or needle.endswith('ers'): print('Is valid') else: print('Invalid') 十分丑陋是吧? 如果我们检测变量needle是否是以下特定字符串之一的话, 会这样写: if needle in ('ly', 'ed', 'ing', 'ers'): print('Is valid') else: print('Invalid') 但是, 我们无法在 endswith function 中使用 in, 但我们换一种想法, 我们需要检查的其实是"一段string的结尾是否是以下字符串的任意一个?", 我们会发现python有内部函数any, 于是我们的代码可以改为: if any([needle.endswith(e) for e in ('ly', 'ed', 'ing', 'ers')]): print('Is valid') else: print('Invalid') 相信很多读者在此会不同意我的做法, 或者有更好的写法存在. 但这已经不重要. 我明白你们大多数都会使用类似的写法面对这一相似的问题. 我真正的目的其实是展示一下Python的优雅之处. -
Django 1.6 最佳实践: 如何搜索查找并解决Django相关的问题
每个程序员都会在开发过程中遇到这样或那样的问题, 有时光靠一个人是无法解决所有问题的, 所以我们应该找到适当的地方提问. 1. 卡住是怎么办 按照以下步骤, 前提是你需要懂点英文: 尽可能自己想办法解决 仔细阅读相关文档, 确保不错过任何相关内容 在Google, 百度, mailing lists或StackOverFlow上查看是否有人遇到相同问题 找不到? 在StackOverFlow上问问题, 需要使用小例子说明该问题, 并列出你的开发环境, 使用的软件版本 过了几天都没人回答? 到Django-users mailing list 或 django IRC中再提问 2. 如何问问题 IRC代表Internet Relay Chat, 在Freenode IRC网络中存在#python和#django频道, 其中都是python和django的开发人员. 对于新手而言, 有时你提的问题会被忽略, 有时甚至会被嘲笑, 但请不要感到沮丧, 这是对事不对人的. 这些IRC都是由志愿者维护的, 因此在你提问的同时, 也应当尽量回答别人的问题. 在你提问前, 请先确保你做过功课, 将其作为最后一根救命稻草 将相关的代码放入https://gist.github.com/中 问题尽可能的详细, 并提供联想gist的链接 当别人提供帮助时, 应当感谢别人 我们也应当在社区中变得更积极, 投入越多, 回报也会多. 参与社区的途径: 参加Python和Django会议, 可以通过https://wiki.python.org/moin/LocalUserGroups找到你当地的小组 对开源的Django package贡献代码 参加IRC频道, 并提供帮助 在StackOverFlow上回答问题 订阅planet django博客 等的呢 -
Release 1.1.1
-
Django 1.6 最佳实践: Continuous Integration
Continuous integration (CI) 是一种软件开发实践, 常用于团队间频繁合并工作使用. 每一次合并都要经过自动构建和测试尽快验证其正确性. 许多团队都发现这一方式能大大降低合并中出现的麻烦和, 并增强软件统一性. 以下是一个典型的开发流程: 程序员写代码, 运行本地测试, 将代码推至代码库, 通常最少一天一次 代码库变化触发自动构建工具 自动构建工具运行构建程序. 其间发生任何错误就将本次推送驳回 自动构建工具运行测试程序. 其间发生任何错误就将本次推送驳回 自动构建工具将结果通知开发人员 这一过程有以下优势: 能以最快速度发现bug 便于发现其他问题 每天合并代码的结果导致不会有一次性大规模的改变代码的情况发生 利于对项目的反馈 减轻许多麻烦的事物 1. Continuous Integration 的原则 接下来, 我们讨论一下Continuous Integration的原则: 大量测试 Continuous Integration的前提是构写大量的测试代码. 没有完整的测试就无法做到Continuous Integration. 有些人可能会不同意, 觉得没有测试, 照样可以完成Continuous Integration, 而且也能带给团队同样的优势: 测试开发过程是否成功, 将每个人的代码都同步. 但这一情况是建立在编译语言上的, 因为编译语言在编译时就保障了代码的正确性(不包括其功能性). 保持快速构建 随着开发时间的进行, 测试可能会变得越来越慢, 为此我们提供了一下技巧: 避免使用fixture 没有必要时便面使用TransactionTestCae 避免构写大量setUp()代码 构写小而专一的测试代码 学习数据库优化 2. Continuous Integration 的工具 可以使用以下工具: Tox Tox是一个virtualenv管理和测试用命令行工具, 可以帮助我们使用一个简单的命令对多个Python和Django版本进行测试. 对于不同的数据库, 也应当进行测试. 这是全世界的程序员测试不同版本python兼容性的通用工具. Jenkins Jenkins是一个Continuous Integration的引擎, 也是一个Continuous Integration的标准. 也有许多在线工具继承了Jenkins供我们方便的使用, 有些更是可以方便的集成到类似GitHub, BitBucket等的代码管理库中, 例如Travis-CI, CircleCI和Drone.io. -
Ansible thoughts (plus questions for which I need your input)
Now... how do we structure our servers? How do we put our software on them? How do we configure them? I've done my share of server maintenance and devops and what have you. On linux, that is. Maintaining my own (web)server since 1996 or so. Done a lot with buildout (which means grabbing everything together for a site that has to do with python). Automated much of our installation with Fabric so that $ bin/fab update production was more or less the standard way to update a site. So I know my way around reasonably and I normally keep everything pretty neat and tidy. Now Ansible has come along and several of our sites are managed with that tool. It feels like a much more elaborate version of Fabric. "Elaborate" is meant very positively here. And I want to dive into it and start using it too. Fabric is great for executing commands via ssh on a remote server (including copying files, modifying files etc). Ansible also executes commands via ssh, but comes with a complete system for storing your configuration, handling variables, dividing up the workload into libraries and also for sharing those libraries (called "roles" in ansible-speak). Problem … -
Adding CKEditor to your Django Admin
How much hard work are those standard textareas in your Django Admin? Lets change that by adding a full HTML text editor…. ckeditor, anyone? Yeah, I know, there are a lot of packages that already do this. However, if all you require is a simple WYSIWYG editor within your admin, it's so easy and far more elegant to just add one in yourself. In jut 3 steps: 1) Download the latest version of CKEditor. 2) Place all the CKEditor files you just downloaded into your static root so it can be served. 3) In your admin.py add something like the following... from django.contrib import admin from django.db import models from django import forms from .models import Entry class EntryAdmin(admin.ModelAdmin): formfield_overrides = { models.TextField: {'widget': forms.Textarea(attrs={'class':'ckeditor'})}, } list_display = ['title', 'creation_date', 'status'] class Media: js = ('ckeditor/ckeditor.js',) admin.site.register(Entry, EntryAdmin) Done! You now have an HTML text editor on your textarea. So what did we just do? All that’s happened is we told Django to replace any textareas with the ckeditor code. When ckeditor starts up it knows to replace any textareas with the ckeditor code becuase we added the class=ckeditor to them. The Class Media will add the required … -
My Blog Search: Haystack and Whoosh
The observant of you may have noticed I finally have search functionality on my blog, yeah!!! After doing a bit of research I decided that SOLR would be far too ambiguous for my simple requirements. With this considered I decided to implement Haystack utilising the Whoosh engine for the search backend. If you don’t know, Whoosh is a pure Python search backend, which means familiarity, perfect! Here is a quick example of how I set this up. First I installed Whoosh and Haystack using pip. sudo pip install Whoosh sudo pip install django-haystack Then in my settings.py I added the haystack application. INSTALLED_APPS = [ # Added. 'haystack', 'blog', ] Next, my settings.py I then needed to tell Haystack what backend I’m using. # Search Haystack import os HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine', 'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'), }, } At the same level as my setings.py I created a new file called 'search_sites.py' and added the following to it. import haystack haystack.autodiscover() This will cause haystack to look for any search_indexes.py files inside each app in my project site. I needed the appropriate URL's of course. (r'^search/', include('haystack.urls')), Now the configuration is out of the way, Haystack needed to … -
Project: Maintenance Mode App - django-time-out
Time out: A reusable Django application that that allows you to put your Django site into maintenance mode. This application simply runs middleware that checks to see if the site is down for maintenance based on scheduled maintenance dates/times added to the DB. Check it out. Installation To get the latest stable release from PyPi pip install django-time-out To get the latest commit from GitHub pip install -e git+git://git.com:sparky300/django-time-out.git#egg=time_out Add time_out to your INSTALLED_APPS NSTALLED_APPS = ( ..., 'time_out', ) Add down_time middleware class to your settings. 'time_out.middleware.DownTimeMiddleware', Don't forget to migrate your database ./manage.py migrate time_out Don't forget to migrate your database ./manage.py migrate time_out Contribute If you want to contribute to this project, please perform the following steps. # Fork this repository # Clone your fork $ mkvirtualenv -p python2.7 django-time-out $ python setup.py install $ pip install -r dev_requirements.txt $ git co -b feature_branch master # Implement your feature and tests $ git add . && git commit $ git push -u origin feature_branch # Send us a pull request for your feature branch -
Project: SagePay payment gateway package for django-oscar
SagePay payment gateway package for django-oscar provides a direct integration that enables you to collect your customers’ payment information on your own secure servers and securely pass card details across to SagePay. This means that you can completely tailor the payment process to suit your business requirements. Documentation Visit Pypi -
Installing Python and Django on Windows
For my own reference I just wanted to document my first time installing Python and Django on Windows 8.  I have installed Python before on a Mac, but never on Windows. To begin with I installed the Python 2.7 (the version Django is compatible with at this point in time). First, I downloaded and installed Python. Python has an ‘installer’ so this was straightforward. I would recommend the install location to be short and simple c:/python27. It's a lot easier on your command prompt typing later on. Python is not added to the DOS path by default. I needed to tell windows the PATH environment variable to include paths to Python executable and additional scripts.  Under My Computer > Properties > Advanced System Settings > Environment Variables > I created a new variable called "PythonPath” and added the following… C:\Python27\;C:\Python27\Scripts; Above being my location to the Python executable. Now that I had Python installed, it was time to install Django. I download the Django files then opened the command prompt. Using the Command Prompt I changed directory (“cd”) into the extracted Django directory. I then typed the following... python setup.py install This installs Django into Python’s site-packages directory. The download … -
Resetting migration history Django South
Just something useful when it comes to resetting migration history using Django South. rm -r appname/migrations/ ./manage.py reset south ./manage.py convert_to_south appname I had to do this recently and I was somewhat apprehensive at first. No need to be tho. I just opened up terminal removed the migration folder from the app , used the reset command and then converted the app just like it was an existing one. Doing this does mean that South assumes your database is identical to the app models.py. -
Fix: vertualenv EnvironmentError: mysql_config not found
Have you ever had what should be a simple task just drive you insane? For me, it's setting up a new Django project using virtualenv on my home Mac running 10.8! For some reason this Mac likes to misbehave! I get the same error every time I try to install MySQL-python within virtualenv vertualenv EnvironmentError: mysql_config not found I cannot take any credit for this fix, after many searches I found the solution here. It's a simple fix just to edit the /bin/activate file from the virtualenv directory and add the following lines, _OLD_VIRTUAL_PATH="$PATH" PATH="$VIRTUAL_ENV/bin:$PATH" PATH="$PATH:/usr/local/mysql/bin/" export PATH That's it, just make sure you match your paths to your own configuration. Now MySQL-python installs under virtualenv as normal. -
Django 1.5 deployment on Amazon EC2 Ubuntu
Introduction Six months ago I began my Django journey. Since then I have setup, installed and utilised many different deployment mechanisms for projects. This tutorial demonstrates the installation and deployment solution I found to be the most fitting for my own Django projects. So, I’d like to share… Why Git? I’ve been using Git for deployment within our company for sometime. It was a natural fit since all our projects already used GIT for version control and our development team understands it. What’s best, it's completely free! Prerequisites One will assume you are already familiar, perhaps even using GIT and have a basic understanding of Apache, Ubuntu Server and Django. I tend to use Cloud computing such as Amazon AWS. I have tested this tutorial on a EC2 instance running Ubuntu 12. Installing our Server Software So as mentioned above I’ll be using an EC2 instance for this writeup. So first ssh in and do any updates. apt-get update apt-get upgrade Next, you will need to install Apache2, Python, and PIP using the following commands... apt-get -y install apache2-mpm-worker apache2-dev apt-get -y install python python-dev python-setuptools sudo apt-get install python-pip pip install --upgrade pip We will wget the latest mod_wsgi, … -
Adding CKEditor to your Django Admin
How much hard work are those standard textareas in your Django Admin? Lets change that by adding a full HTML text editor…. ckeditor, anyone? Yeah, I know, there are a lot of packages that already do this. However, if all you require is a simple WYSIWYG editor within your admin, it's so easy and far more elegant to just add one in yourself. In jut 3 steps: 1) Download the latest version of CKEditor. 2) Place all the CKEditor files you just downloaded into your static root so it can be served. 3) In your admin.py add something like the following... from django.contrib import admin from django.db import models from django import forms from .models import Entry class EntryAdmin(admin.ModelAdmin): formfield_overrides = { models.TextField: {'widget': forms.Textarea(attrs={'class':'ckeditor'})}, } list_display = ['title', 'creation_date', 'status'] class Media: js = ('ckeditor/ckeditor.js',) admin.site.register(Entry, EntryAdmin) Done! You now have an HTML text editor on your textarea. So what did we just do? All that’s happened is we told Django to replace any textareas with the ckeditor code. When ckeditor starts up it knows to replace any textareas with the ckeditor code becuase we added the class=ckeditor to them. The Class Media will add the required … -
My Blog Search: Haystack and Whoosh
The observant of you may have noticed I finally have search functionality on my blog, yeah!!! After doing a bit of research I decided that SOLR would be far too ambiguous for my simple requirements. With this considered I decided to implement Haystack utilising the Whoosh engine for the search backend. If you don’t know, Whoosh is a pure Python search backend, which means familiarity, perfect! Here is a quick example of how I set this up. First I installed Whoosh and Haystack using pip. sudo pip install Whoosh sudo pip install django-haystack Then in my settings.py I added the haystack application. INSTALLED_APPS = [ # Added. 'haystack', 'blog', ] Next, my settings.py I then needed to tell Haystack what backend I’m using. # Search Haystack import os HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine', 'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'), }, } At the same level as my setings.py I created a new file called 'search_sites.py' and added the following to it. import haystack haystack.autodiscover() This will cause haystack to look for any search_indexes.py files inside each app in my project site. I needed the appropriate URL's of course. (r'^search/', include('haystack.urls')), Now the configuration is out of the way, Haystack needed to … -
Project: Maintenance Mode App - django-time-out
Time out: A reusable Django application that that allows you to put your Django site into maintenance mode. This application simply runs middleware that checks to see if the site is down for maintenance based on scheduled maintenance dates/times added to the DB. Check it out. Installation To get the latest stable release from PyPi pip install django-time-out To get the latest commit from GitHub pip install -e git+git://git.com:sparky300/django-time-out.git#egg=time_out Add time_out to your INSTALLED_APPS NSTALLED_APPS = ( ..., 'time_out', ) Add down_time middleware class to your settings. 'time_out.middleware.DownTimeMiddleware', Don't forget to migrate your database ./manage.py migrate time_out Don't forget to migrate your database ./manage.py migrate time_out Contribute If you want to contribute to this project, please perform the following steps. # Fork this repository # Clone your fork $ mkvirtualenv -p python2.7 django-time-out $ python setup.py install $ pip install -r dev_requirements.txt $ git co -b feature_branch master # Implement your feature and tests $ git add . && git commit $ git push -u origin feature_branch # Send us a pull request for your feature branch -
Project: dajngo-stencil
dajngo-stencil is a a boilerplate project for starting development based on my own setup. I start my projects in the same way and django-stencil is a way for me to jump start it. If you would like to give it a go run the following command: $ django-admin.py startproject --template=https://github.com/sparky300/django-stencil/zipball/master project_name Where project_name is the name of the project you'd like to create. -
Project: SagePay payment gateway package for django-oscar
SagePay payment gateway package for django-oscar provides a direct integration that enables you to collect your customers’ payment information on your own secure servers and securely pass card details across to SagePay. This means that you can completely tailor the payment process to suit your business requirements. Documentation Visit Pypi -
Tutorial: Using AngularJS with Django
I’m hoping to write a quick tutorial to get you started using Angular with Django What it turned into was a tutorial fueled by Red Bull. My apologies if it gets sloppy towards the end! Having read posts on the subject of using Django and Angular together, I felt most were reinventing the wheel, so to speak. Although the example code I have given is crude it should highlight how I've been using them on projects. Models Lets start with a typical Model. /jobs/models.py class Job(models.Model): name = models.CharField(max_length=50) description = models.TextField(null=True, blank=True) Alright, nothing special so far. All you have done is create a simple model to contain basic job details. The REST API (Tastypie) AngularJS is built to consume webservices, so your gonna need a way to expose the Job Model you just created. Django has a good set of choices to create RESTful APIs. TastyPie is an awesome webservice framework built for the Django framework. It's incredibly powerful, yet easy to setup and use. However, personal preference aside, the same results could be achieved using Django REST framework, or even constructing your own API responses directly using Django. The choice is entirely yours. For the purposes of this tutorial we'll be using TastyPie. If you're not … -
Django 1.6 最佳实践: 如何确保相同的开发环境
如何保证各个程序员之间的开发环境相同是个复杂的问题, 我们可能存在以下问题: 1.操作系统不同, 2.python配置不同. 有的程序员用的是windows, 也有使用mac和Linux的, 有些程序员甚至不知道自己使用的是哪个版本的python. 每次换了新的硬件, 都需要重新安装和设置相同的操作系统, 这样十分麻烦, 以下是当前可有的解决这一问题的选项: 在虚拟机中开发: 以前这一选择是无法想象的, 因为虚拟机设置复杂, 速度又慢. 但现在却不同了, 使用Vagrant配合虚拟机, 这一选择变得十分方便. 在Docker管理的LxC容器中开发: 类似于在虚拟机中开发, 但更轻量级. LxC容器可以共享host主机的硬件资源, 使其效率更高. 1. Vagrant Vagrant是VirtualBox或其他虚拟机的一个wrapper, 它可以让你使用一个命令行就配置好你想要的VM(虚拟机). 通过Vagrant创建的VM可以使用命令行访问和控制, 免去了GUI的繁琐. Vagrant的优势是, 其创建的VM可以通过scripts, Salt, Ansible, Chef或Puppet管理, 使得我们可以在不同的环境中设置相同的开发环境. Vagrant可能的劣势则是, 自动化的配置可能会降低我们队底层架构的理解, 在较老的电脑上, 虚拟机可能运行较慢. 2. Docker Docker是一个允许我们轻松创建Linux container(LxC)的开源项目. 这与许多PaaS使用的部署环境类似. Docker的优势是使用host资源, 因此部署十分迅速. 但需要注意的是, Docker正在开发中, 处于测试阶段可能还不能用于正式服务器上. -
PUT and DELETE HTTP requests with Django and jQuery
Sometimes it could be useful and elegant to have a Django view responding to more that GET and POST requests, implementing a simple REST interface. In this post I’ll show how you can support PUT and DELETE HTTP requests in Django. Table of Contents Your goal The problems The solution What about the function based views? Conclusion Your goal To put it in examples your goal is to have a View like this: from django.views.generic import View from django.shortcuts import redirect, render from django.forms.models import modelform_factory from django.http import HttpResponse from .models import MyModel class RestView(View): def get(self, request): # retrieve some object and render in template object = MyModel.objects.get(pk=request.GET['pk']) return render(request, 'object_detail.html', {'object': object}) def put(self, request): # create an object and redirect to detail page modelform = modelform_factory(MyModel) form = modelform(request.PUT) if form.is_valid(): form.save() return redirect('restview') def delete(self, request): # delete an object and send a confirmation response MyModel.objects.get(pk=request.DELETE['pk']).delete() return HttpResponse() And accessing the view by jQuery Ajax methods like this: $.ajax({ type: 'DELETE', url: '/restview', data: { pk: pk }, success: function() { alert('Object deleted!') } }); The problems Unfortunately there are two problems that restrict you to implement the view and the javascript like described above: …