Posts

Showing posts from 2011

Django: Instalation of Dev environment on a clear Lion Mac OS X

Image
Like lots of Apple fans around the world I've finally decided to upgrade my OS to Lion release. I have bought a new laptop and it was the case. I've waited for a weekend to prepared myself for sex. And it was it. Now I want to share my experience with you guys. For you not to spend to much time on those issues, I've did. Anyway what I'm usually using is a Fresh 2.7 Python , Django , PIL , virtualenv and many many minor tools which exceed scopes of this article. I also use Eclipse IDE for Python Dev. So all this I had to install and make spinning till monday. If anybody tells me that Macs do not have good tools for this. He will not be right. Maybe there some itches and scratches of head about: "Why is not those things working" or "Why do they work not as preferred". But there always is a good "Googled" decision to handle that. Anyway lets go to installing stuff. Short brief Plan of out work: 1. Install Apple Development SDK +

Python: Debugging/Developing SMTP mail things

Image
You often have 'situations' when you developing Contact forms, or any other forms which have to send emails with python. You have to install or have working SMTP server on your Dev machine like say 'monstrous' Sendmail or something like it. It can cause errors in Django/Python like [Errno 61] Connection refused: [ Errno 61 ] Connection refused But python has it handled for you. Python's standard distribution has a test SMTP server that you can test sending mail with. It actually does not sends anything. But you can examine outgoing email message like you've actually send it. Type something like: python - m smtpd - n - c DebuggingServer localhost : 1025 It will start a command line server on this console and it will print everything your server should send through SMTP. Also make sure to modify mail sending code to use your non standart port number like so: server = smtplib . SMTP ( SERVER , 1025 ) server . sendmail ( FROM , TO , message

Django: Adding news archive. Querying models with date and time filtering.

Image
Today I had some practice with filtering Django models by date. Task was to archive old entries of the news. I've made 2 separate views for those. I was displaying actually news and another was ment to display archived items. Quite common task I guess. Also those 2 views are under wired buggy CMS, but we are not talking about that now. Will save some examples for future of mine/someones usage. Time. Subtracting a year from today with Python dateutil : from datetime import date , timedelta d = date . today ( ) - timedelta ( days = days_to_subtract ) This example returns 'd' that has less days than specified in 'days_to_subtract' . timedelta function also can be fed with 'months' , 'years' and so on. Becomes handy during time calculations. If you change this minus into plus you can calculate future time. Filtering Querysets. Filtering by date ranges. samples = Sample . objects . filter ( date__gte = datetime . date ( 2011 , 1

Django: compressing CSS/JS files with django-compressor

Image
There are 2 main usual tasks with web project's deployment and about .css and .js files. First one - size minimization. But there are lot's of utilities helping you to compress CSS files. Delete unused spaces, comments and so on... Second one - Version control. For e. g. When you've updated the script on your deployment server, but user's browser uses old one until user manually hits 'Refresh'. That's where Static files compressor comes in to mind. Upon selecting among available one's found top "google" results: - django-compress - django-compressor - webassets Project uses 'django.contrib.staticfiles', so django-compress was not compatible... It does not support Django's static files gently. Webassets s a good lib. but project has a huge amount of different static. Maybe it's ok for e small project, but when you need to specify/change a 100's javascript in python module for certain templates... Nothing good comes

Django: 'ManyRelatedManager' object is not iterable

Upon development proces you often meet ManyToMany relations that throw errors in templates. I prefer to feed everything to context and play with it there. This kind of error appears when you iterate through a model's ManyToMany field. To fix it just add a related 'all' manager through dot syntax. Like so: Model: class BannerImage ( models . Model ) : image = models . ImageField ( upload_to = "somedir" ) def get_image_url ( self ) : return 'Image url here' class Banner ( models . Model ) : name = models . CharField ( max_length = 250 , null = True ) images = models . ManyToManyField ( BannerImage ) View/Tag or else, that creates context: banner = get_object_or_404 ( Banner , pk = 1 ) return { 'banner' : banner , } Template causing the error: {% for image in banner . images %} < img src = "{{ image.get_image_url }}" /> {% endfor %} Template without the error: {%

Django: Virtualenv with Eclipse befrending

Image
Hi! Many people use Virtualenv. It has become common pattern now days. I like Virtualenv but it has no debugger. You can run ' python manage.py runserver ' but it will newer help you see somthing like runtime variables and code flow. I like PyDev  debugger. It helps me a lot. Anyway I faced a problem recently. My employer wants me to run code at virtualenv. I needed to download and run project. I made it creating New virtualenv called 'venv' inside a project folder. Command is: virtualenv - - no - site - packages venv It will create dir 'venv' inside current directory. So you should be at where you need to store your virtualenv (your project directory for e.g.). --no-site-packeges  parameter says that your new virtual environment will not have packages installed in system. It's a must if you want to avoid collisions with newer versions of code. Now we have a dir inside your project called venv  containing our separated python environment. Lets activ

Django: How and why to use migrations. Django-South.

Image
Hi there guys and we're here to talk about migrations today. My app grown to complex app with profiles, social registration permits and so on. First time I've decided to make myself a simple app. Now it became complex enough and contains enough code to need code comments :). Anyway Migrations is a process anybody someday will need. I thought it's hard to learn or understand, but it's not. Main point is that you: - save your current database tables structure - change your model tables - scan for differences and create script - then write changes to your database with automatically generated python script. Sound's simple? I't not all so simple in fact. App that you need to learn is Django-south . Its main objectives are to provide a simple, stable and database-independent migration layer to prevent all the hassle schema changes over time bring to your Django applications. It has quite understandable tutorial here . So if you're tired of ALTER'in

Django: adding code execution on your app syncdb, or how to use Django Signals.

Hi there and let's talk about app initialization in Django. There are some cases when you want to initialize a Django app with creating some default values in database. In my case it was necessity to create default album in database to post user photos to. Sometimes you could just use get_or_create for those purposes. But it will be a good example if we will need something more complex in our app initialization; for e.g. generating thumbnails for photos or cleaning unused temporary files etc. So let's get started: Good place to put your initialization scripts is your app's __init__.py file. You can examine Djangoproject wiki for more info. Anyway here is my code for making this: from  django. db . models . signals   import  post_syncdb import  models from  models  import  Album   def  create_first_album ( sender,  ** kwargs ) :      """    Create your album sequence to create default album to post photos to    checks for existence of this album a

Django: Beautiful multiple files Upload Plugin using jQuery UI.

Image
After successful developing python back-end for Sebastian Tschan jQuey Plugin  I've decided to make a reusable app for that purpose. So: This is a plugin, made using multiupload form from Sebastian Tschan. It uses jQuey UI and jQuery instead of Flash uploader. On Django side it uses sorl-thumbnails and PIL. You can use it in your applications with simple inclusion tag jQuery Features it has: Multiple file upload: Allows to select multiple files at once and upload them simultaneously. Drag & Drop support: Allows to upload files by dragging them from your desktop or filemanager and dropping them on your browser window. Upload progress bar: Shows a progress bar indicating the upload progress for individual files and for all uploads combined. Cancelable uploads: Individual file uploads can be canceled to stop the upload progress. Resumable uploads: Aborted uploads can be resumed wi

Django: Creating multi upload form without using Flash

Image
Hi there! Today I want to tell you about my experience of adding Multiple files upload form to my  Django project Photoblog.  I searched google for lots of plugins, but found only Flash usage examples. I dislike Flash technology, as for my personal usage, and want to build some more quickly working UI. Personally I have flash blocker installed on my browser. So that's main ideas pf my jQuery plugin selection. I found IMHO the best for my case plugin by  Sebastian Tschan . It had only one problem - No available Django examples. Let's try to fill the gap here... So my experience on befriending  Sebastian Tschan's jQuery File Upload Plugin  with Django is the topic of this article. Let's finally get started. :) Sebastian has built an important plugin IMHO. I want to thank him for his noble work of helping people with their tasks. It uses only jQuery UI and no flash, making it work more programmers way... So enough with the lyrics. Let's try to adapt his example to