Friday, September 10, 2010

Django : FileField() or ImageField()

In Django its very simple to handle images and file field.

First you define the ImageField and FileField in Class.
for example :
Class File(models.Model):
image =models.ImageField(upload_to = 'path')
File =models.FileField(upload_to = 'path')

Using a FileField or an ImageField in a model takes a few steps:
  1. In your settings file, you'll need to define MEDIA_ROOT as the full path to a directory where you'd like Django to store uploaded files. (For performance, these files are not stored in the database.) Define MEDIA_URL as the base public URL of that directory. For Example :MEDIA_ROOT = "/media/"  , MEDIA_URL = 'http://localhost/media/'
  2. Add the FileField or ImageField to your model, making sure to define the upload_to option to tell Django to which subdirectory of MEDIA_ROOT it should upload files.
  3. All that will be stored in your database is a path to the file (relative to MEDIA_ROOT). You'll most likely want to use the convenience url attribute provided by Django. For example, if your ImageField is called file, you can get the absolute URL to your image in a template with {{ object.file.url }}.

Facing problem With ImageField() and FileField()
#python manage.py runserver
Error :Unhandled exception in thread started by 

<function inner_run at 0x912348c>
Traceback (most recent call last):
  File "/usr/local/lib/python2.6/dist-packages/django/core/management
/commands/runserver.py", line 48, in inner_run
    self.validate(display_num_errors=True)
  File "/usr/local/lib/python2.6/dist-packages/django/core
/management/base.py", line 249, in validate raise CommandError
("One or more models did not validate:\n%s" % error_text)
django.core.management.base.CommandError:
One or more models did not validate:
ukieri.participants: "logo": To use ImageFields, 
you need to install the Python Imaging Library. 

Need to Install Python Imaging Library in server 
Link for Download :http://www.pythonware.com/products/pil/



Second Problem is  when i use {{ object.file.url }} in templates
Error in template is :

TemplateSyntaxError at /file/

Caught ValueError while rendering: The 'file' attribute has
no file associated with it.
The problem is solve to use IF statments in template :-
For example :-
{% if object.file %} 
     <img src="{{ object.file.url }}" />
{% endif %} 


No comments:

Post a Comment