How to Set Date and field options in the Django framework of Python

Source: Internet
Author: User
set field optional

After fiddling with it for a while, you might find that the management tool has a limit: Editing a form requires you to fill in every field, but in some cases you want some fields to be optional. For example, we want the email field in the author module to be optional, which allows you to not fill it. In the real world, you may not have registered an email address for each author.

In order to specify an optional email field, you simply edit the book module (recall the fifth chapter, which is in the mysite/books/models.py file) and add blank=true to the email field. The code is as follows:

Class Author (models. Model):  first_name = models. Charfield (max_length=30)  last_name = models. Charfield (max_length=40)  email = models. Emailfield (**blank=true**)

The code tells Django that the author's e-mail address allows for a null value to be entered. All fields are blank=false by default, which makes them not allowed to enter null values.

Something interesting is going to happen here. Until now, in addition to the __unicode__ () method, our module acts as a table-defined role in the database, essentially using the Python syntax to write the CREATE TABLE statement. In the process of adding blank=true, we have begun to extend our modules on a simple definition data table. Now our module class is starting to become a collection of properties and behaviors that are rich in author objects. Email not only presents as a varchar type field in a database, it is also an optional field in the page, as seen in the administration tool.

After you add blank=true, refresh the page Add author edit form (http://127.0.0.1:8000/admin/books/author/add/), you will find the email label is no longer bold. This means that it is not a required field. Now you can add an author without having to enter an email address, even if you submit a null value for this field, you will never get that dazzling red message "this field is required".
Set date and Number fields are optional

Although Blank=true also applies to date and numeric fields, there are some background details that need to be explained here.

SQL has a unique way of specifying an empty value, which is called NULL. Null can be expressed as an unknown, illegal, or other program-specified meaning.

In SQL, the null value differs from an empty string, just as none in Python is different from an empty string (""). This means that the value of a character field (such as varchar) cannot contain both null and an empty string.

This can lead to unnecessary ambiguity or confusion. Why does this record have a null, and that record has an empty string? Are there differences between them, or are data input inconsistent? Also: How can I get all the records with null values, should I find them by null and empty strings? Or just search by string?

To disambiguate, the Django Generation CREATE TABLE statement automatically adds not NULL for each field. Here is an example of generating a author module:

CREATE TABLE "Books_author" (  "id" serial NOT NULL PRIMARY KEY,  "first_name" varchar (+) NOT NULL,  "last_name "varchar (+) NOT NULL,  " "Email" varchar (+) not NULL);

In most cases, this default behavior is best for your application because it allows you to no longer have headaches due to data consistency. And it works well with other parts of Django. In the administrative tool, if you leave a character field blank, it inserts an empty string (and * not *null) for this purpose.

However, there are exceptions to other data types: date, time, and numeric fields do not accept empty strings. If you try to insert an empty string into a date or integer field, you may get an error returned by the database, depending on the type of the database. (PostgreSQL is strictly forbidden, will throw an exception; MySQL may or may not be accepted, depending on the version you are using and your luck.) In this case, NULL is the only method that specifies a null value. In the Django module, you can specify that a field is allowed to be null by adding null=true.

So this is a bit complicated: if you want to allow a date type (Datefield, Timefield, Datetimefield) or numeric (Integerfield, Decimalfield, Floatfield) fields to be empty, You need to use null=true * and * blank=true.

For illustrative purposes, let's modify the book module to allow Publication_date to be empty. The modified code is as follows:

Class book (Models. Model):  title = models. Charfield (max_length=100)  authors = models. Manytomanyfield (Author)  publisher = models. ForeignKey (Publisher)  publication_date = models. Datefield (**blank=true, null=true**)

Adding null=true is more complex than adding blank=true. Because Null=true changed the semantics of the data, the CREATE TABLE statement was changed, and not NULL on the Publication_date field was deleted. To complete these changes, we also need to update the database.

For some reason, Django does not attempt to automatically update the database structure. So you must execute the ALTER TABLE statement to update the module's changes to the database. As before, you can use manage.py Dbshell to enter the database service environment. Here's how to remove not NULL in this particular case:

Alter TABLE Books_book ALTER COLUMN publication_date DROP not NULL;

(Note: The following SQL syntax is specific to PostgreSQL.) )

We will detail the database structure changes in the tenth chapter.

Now let's go back to the admin tool and add the book's edit page to allow for an empty publication date.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.