Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Mastering Django: Core

You're reading from   Mastering Django: Core The Complete Guide to Django 1.8 LTS

Arrow left icon
Product type Paperback
Published in Dec 2016
Publisher
ISBN-13 9781787281141
Length 694 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Nigel George Nigel George
Author Profile Icon Nigel George
Nigel George
Arrow right icon
View More author details
Toc

Table of Contents (33) Chapters Close

Mastering Django: Core
Credits
About the Author
www.PacktPub.com
Preface
1. Introduction to Django and Getting Started FREE CHAPTER 2. Views and URLconfs 3. Templates 4. Models 5. The Django Admin Site 6. Forms 7. Advanced Views and URLconfs 8. Advanced Templates 9. Advanced Models 10. Generic Views 11. User Authentication in Django 12. Testing in Django 13. Deploying Django 14. Generating Non-HTML Content 15. Django Sessions 16. Djangos Cache Framework 17. Django Middleware 18. Internationalization 19. Security in Django 20. More on Installing Django 21. Advanced Database Management Model Definition Reference Database API Reference Generic View Reference Settings Built-in Template Tags and Filters Request and Response Objects Developing Django with Visual Studio

Fields


The most important part of a model-and the only required part of a model-is the list of database fields it defines.

Field name restrictions

Django places only two restrictions on model field names:

  1. A field name cannot be a Python reserved word, because that would result in a Python syntax error. For example:
            class Example(models.Model): 
            pass = models.IntegerField() # 'pass' is a reserved word! 
    
  2. A field name cannot contain more than one underscore in a row, due to the way Django's query lookup syntax works. For example:
        class Example(models.Model): 
            # 'foo__bar' has two underscores! 
            foo__bar = models.IntegerField()  

Each field in your model should be an instance of the appropriate Field class. Django uses the field class types to determine a few things:

  • The database column type (for example, INTEGER, VARCHAR)
  • The widget to use in Django's forms and admin site, if you care to use it (for example, <input type="text">, <select>)
  • The minimal validation requirements, which are used in Django's admin interface and by forms

Each field class can be passed a list of option arguments, for example when we were building the book model in Chapter 4, Models, our num_pages field looked like this:

num_pages = models.IntegerField(blank=True, null=True) 

In this case, we are setting the blank and null options for the field class. Table A.2 lists all the field options in Django.

A number of fields also define additional options specific to that class, for example the CharField class has a required option max_length which defaults to None. For example:

title = models.CharField(max_length=100) 

In this case we are setting the max_length field option to 100 to limit our book titles to 100 characters.

A complete list of field classes is in Table A.1, sorted alphabetically.

Field

Default Widget

Description

AutoField

N/A

An IntegerField that automatically increments according to available IDs.

BigIntegerField

NumberInput

A 64-bit integer, much like an IntegerField except that it is guaranteed to fit numbers from -9223372036854775808 to 9223372036854775807

BinaryField

N/A

A field to store raw binary data. It only supports bytes assignment. Be aware that this field has limited functionality.

BooleanField

CheckboxInput

A true/false field. If you need to accept null values then use NullBooleanField instead.

CharField

TextInput

A string field, for small- to large-sized strings. For large amounts of text, use TextField.CharField has one extra required argument: max_length. The maximum length (in characters) of the field.

DateField

DateInput

A date, represented in Python by a datetime.date instance. Has two extra, optional arguments: auto_now which automatically set the field to now every time the object is saved, and auto_now_add which automatically set the field to now when the object is first created.

DateTimeField

DateTimeInput

A date and time, represented in Python by a datetime.datetime instance. Takes the same extra arguments as DateField.

DecimalField

TextInput

A fixed-precision decimal number, represented in Python by a Decimal instance. Has two required arguments: max_digits and decimal_places.

DurationField

TextInput

A field for storing periods of time-modeled in Python by timedelta.

EmailField

TextInput

A CharField that uses EmailValidator to validate the input. max_length defaults to 254.

FileField

ClearableFileInput

A file upload field. For more information on FileField, see the next section.

FilePathField

Select

A CharField whose choices are limited to the filenames in a certain directory on the filesystem.

FloatField

NumberInput

A floating-point number represented in Python by a float instance. Note when field.localize is False, the default widget is TextInput

ImageField

ClearableFileInput

Inherits all attributes and methods from FileField, but also validates that the uploaded object is a valid image. Additional height and width attributes. Requires the Pillow library available at http://pillow.readthedocs.org/en/latest/.

IntegerField

NumberInput

An integer. Values from -2147483648 to 2147483647 are safe in all databases supported by Django.

GenericIPAddressField

TextInput

An IPv4 or IPv6 address, in string format (for example, 192.0.2.30 or 2a02:42fe::4).

NullBooleanField

NullBooleanSelect

Like a BooleanField, but allows NULL as one of the options.

PositiveIntegerField

NumberInput

An integer . Values from 0 to 2147483647 are safe in all databases supported by Django.

SlugField

TextInput

Slug is a newspaper term. A slug is a short label for something, containing only letters, numbers, underscores or hyphens.

SmallIntegerField

NumberInput

Like an IntegerField, but only allows values under a certain point. Values from -32768 to 32767 are safe in all databases supported by Django.

TextField

Textarea

A large text field. If you specify a max_length attribute, it will be reflected in the Textarea widget of the auto-generated form field.

TimeField

TextInput

A time, represented in Python by a datetime.time instance.

URLField

URLInput

A CharField for a URL. Optional max_length argument.

UUIDField

TextInput

A field for storing universally unique identifiers. Uses Python's UUID class.

Table A.1: Django model field reference

FileField notes

The primary_key and unique arguments are not supported, and will raise a TypeError if used.

  • Has two optional arguments: FileField.upload_to
  • FileField.storage

FileField FileField.upload_to

A local filesystem path that will be appended to your MEDIA_ROOT setting to determine the value of the url attribute. This path may contain strftime() formatting, which will be replaced by the date/time of the file upload (so that uploaded files don't fill up the given directory). This may also be a callable, such as a function, which will be called to obtain the upload path, including the filename. This callable must be able to accept two arguments, and return a Unix-style path (with forward slashes) to be passed along to the storage system.

The two arguments that will be passed are:

  • Instance: An instance of the model where the FileField is defined. More specifically, this is the particular instance where the current file is being attached. In most cases, this object will not have been saved to the database yet, so if it uses the default AutoField, it might not yet have a value for its primary key field.
  • Filename: The filename that was originally given to the file. This may or may not be taken into account when determining the final destination path.

FileField.storage

A storage object, which handles the storage and retrieval of your files. The default form widget for this field is a ClearableFileInput. Using a FileField or an ImageField (see below) in a model takes a few steps:

  • 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. Make sure that this directory is writable by the web server's user account.
  • Add the FileField or ImageField to your model, defining the upload_to option to specify a subdirectory of MEDIA_ROOT to use for uploaded files.
  • 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 convenient url attribute provided by Django. For example, if your ImageField is called mug_shot, you can get the absolute path to your image in a template with {{ object.mug_shot.url }}.

Note that whenever you deal with uploaded files, you should pay close attention to where you're uploading them and what type of files they are, to avoid security holes. Validate all uploaded files so that you're sure the files are what you think they are. For example, if you blindly let somebody upload files, without validation, to a directory that's within your web server's document root, then somebody could upload a CGI or PHP script and execute that script by visiting its URL on your site. Don't allow that.

Also note that even an uploaded HTML file, since it can be executed by the browser (though not by the server), can pose security threats that are equivalent to XSS or CSRF attacks. FileField instances are created in your database as varchar columns with a default max length of 100 characters. As with other fields, you can change the maximum length using the max_length argument.

FileField and FieldFile

When you access a FileField on a model, you are given an instance of FieldFile as a proxy for accessing the underlying file. In addition to the functionality inherited from django.core.files.File, this class has several attributes and methods that can be used to interact with file data:

FieldFile.url

A read-only property to access the file's relative URL by calling the url() method of the underlying Storage class.

FieldFile.open(mode='rb')

Behaves like the standard Python open() method and opens the file associated with this instance in the mode specified by mode.

FieldFile.close()

Behaves like the standard Python file.close() method and closes the file associated with this instance.

FieldFile.save(name, content, save=True)

This method takes a filename and file contents and passes them to the storage class for the field, then associates the stored file with the model field. If you want to manually associate file data with FileField instances on your model, the save() method is used to persist that file data.

Takes two required arguments: name which is the name of the file, and content which is an object containing the file's contents. The optional save argument controls whether or not the model instance is saved after the file associated with this field has been altered. Defaults to True.

Note that the content argument should be an instance of django.core.files.File, not Python's built-in file object. You can construct a File from an existing Python file object like this:

from django.core.files import File 
# Open an existing file using Python's built-in open() 
f = open('/tmp/hello.world') 
myfile = File(f) 

Or you can construct one from a Python string like this:

from django.core.files.base import ContentFile 
myfile = ContentFile("hello world") 
FieldFile.delete(save=True)

Deletes the file associated with this instance and clears all attributes on the field. This method will close the file if it happens to be open when delete() is called.

The optional save argument controls whether or not the model instance is saved after the file associated with this field has been deleted. Defaults to True.

Note that when a model is deleted, related files are not deleted. If you need to clean up orphaned files, you'll need to handle it yourself (for instance, with a custom management command that can be run manually or scheduled to run periodically via for example, cron).

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime
Visually different images