Django model object creation and template language variable filters

1. The establishment of Django model objects;

Example 1.

from django.db import models
from django.utils import timezone


class Post(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(
            blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title
class: indicates the creation of an object.

 

Post is the object name.

models.Model: Indicates that it is a Django model.

models.CharField - This is how you define a text with a limited number of characters.

models.TextField - this is long text with no length limit. This sounds like a good idea for blog post content

models.DateTimeField - This is the date and time.

models.ForeignKey - This is a link to another model. 

defindicates that this is a function.

2. After the object is created, let Django know about the changes to the model

python manage.py makemigrations blog
3. Migrate the database.
python manage.py migrate blog
 two. template language

 

1. Variables

 

{{ variable }}
 Variables include alphanumerics and underscores, no spaces or punctuation.

 

2. Filters, which change the display of variables.

{{ name|lower }}
filter parameter; 
{{ item.content |truncatewords:30 }} <!-- only display the first 30 words of the content variable-->
 default
{{ value|default:"nothing" }} <!--If a variable is false or empty, use the given default value. Otherwise, use the value of the variable -->
 length
{{ value|length }} returns the length of the value. It works for both strings and lists
 add adds a value to a variable.
{{ value|add:"2" }} <!--If value is 4, it will output 6.-->
 capfirst capitalizes the first letter.
{{ value|capfirst }} <!--If the value is test, it will be filtered and converted to Test-->
dictsort sorts the list dictionary according to the specified key value and returns 
{{ value|dictsort:"name" }}
 random returns a value at random
{{ value|random }}<!--If value=[1,8,6,9,6], a random number returned may be 6.-->
 slice slice
{{ value|slice:":2" }}<!---->If value is ['a', 'b', 'c'], the output result is ['a', 'b']
 truncatewords string truncation
{{ some_list|slice:":2" }}<!--如果value是 "Joel is g",输出"Joel is ...".value-->
 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326941754&siteId=291194637