Django学习总结 2

1. Model - defines the data (database)

In this section, it is really about implementation. However, the database design also requires a whole new chapter to talk about. I have learnt basic relational database design (1-3 normalisation rules) from Udemy.

a) Define the table and field.

Simple example:

class Topic(models.Model):
    top_name = models.CharField(max_length=264, unique=True)

class Webpage(models.Model):
    category = models.ForeignKey(Topic)
    name = models.CharField(max_length=264)
    url = models.URLField()
    def __str__(self):
        return self.name

In the above example, topic is a table and top_name is a field (column) of the table. __str__ is a string representation of the model, for example in the result of a print function.

b) Creates the table in the database

Django will do the heavy-lift job and you just need a piece of code:
python manage.py migrate

In normal procedure, for any change made to the models, it is to run in the following sequence:
python manage.py makemigrations
python manage.py migrate

Using console to interact with the database:
python manage.py shell
Exit the shell:
exit() or quit()

c) Register the models in the admin.py (so that you can interact in the admin interface)

Import models first:
from app_name.models import model_name
admin.site.register(model_name)

Create a superuser to access the admin

python manage.py createsuperuser
Using the 'username' and 'password' to login the admin interface.

2 Model - View - Template (MTV) methodology of Django

  • Model: defines the database
  • View: Takes in the request from the client side, query the database if necessary (take or save data), and then send the response (with data) with templates. This is where the main logic is written.
  • Template: The skeleton of the content is defined in static HTML with dynamic content represented by template tag. The dynamic content(variables) is basically the 'end' connected to the back-end.

a) Import models (or forms) into views.py

from app_name.models import model_name

b) Query the database

Create a model instance
  • Inherit the whole table:
    instance = model_name.objects.all()
  • Sort the table by a specified column:
    instance = model_name.objects.order_by('field_name')
Group the data in a dictionary if necessary.

c) Edit the template file

{% for record in Record %}
<tr>
  <td>{{ record.name }}</td>
  <td>{{ record.date }} </td>
</tr>
{% endfor %}

.name and .date are model fields defined in the models.py. 'Record' must be the same as the key of the dictionary defined in the views.py file (end-to-end aligned).

d) Edit the urls.py to connect the view function.

Import the corresponding view module:
from app_name import views
Match url pattern (e.g. home/) with the view function (home):
url(r'^home/', views.home, name='home')

3. Django Forms

Advantages of using django forms:

  • Quickly generate HTML form widgets
  • Validate data and process it into a Python data structure.
  • Create form versions of Models, quickly update models from Forms.

My understandings of django forms:

It is a 'staging' interface (borrow from git) to bridge the client side (front-end HTML) and the server side (Models -
database) . Users provide data and want to write it into the database. The data needs to be validated before actually writing into the database. Therefore, Django forms serve as the 'buffer' layer between the client and the server. In practice, I found by using Django forms, saving data into the database is straightforward and error-free, which makes the implementation very easy for the beginners.

The implementation is very similar to Django models.

a) Create a forms.py file under app folder.

Import forms:

from django import forms

Create a form class:
Class FormName(forms.Form):
  name = forms.CharField()
  text = forms.CharField(widget=forms.Textarea)
Create a Model form class (inherit from the model)

Import models: from app.models import Selection
Create model forms:

class SelectionForm(forms.ModelForm):
    text_content = forms.CharField(widget = forms.Textarea, label='Your content')
    class Meta():
        model = Selection
        fields = ('text_content',)

class Meta() provides metadata to the model; Model metadata is 'anything that is not a table field'.

Inside the above class Meta(): it tells text_content you created to receive data from the client is actually a field of the table named 'Selection'. Therefore, ModelForm connects the client input with the server's database.

b) Create a view for the form

Import forms:

form . import forms - '.' represents the current directory.

Define a view function:
def SelectionFormView(request):
    form = forms.SelectionForm()
    return render(request, 'appname/forms.html', {'form', form})

c) Connect the view function and URL pattern in urls.py

d) Template tags for django forms

A code snippet for form template tag

In above HTML template, it defines a form with method 'post'. In the server side, form validation needs to be added in.

e) Form validation in views.py

if request.method == "POST":
        selection_form = SelectionForm(data=request.POST)

        if selection_form.is_valid() :
            user_selection = selection_form.save()
            user_selection.save()
        else:
            print(selection_form.errors)
        #Empty the form after saving the content into the databaes
        selection_form = SelectionForm()
else:
   selection_form = SelectionForm()
- Adding a check for empty fields/ for a bot

The idea is to define a hidden field, which is not seen by the client user but seen by bot in HTML element. A normal human user will not fill in that 'unseen' field but not the bot. Therefore, by checking whether the field is empty or not, one can distinguish between a human user and a bot.

You can set one field of the form as:

  • Can be empty: required = False
  • Not shown to client users: widget = forms.HiddenInput
Django provides built-in validators:
  1. Import the model:
    from django.core import validators
  2. Add validation into the field arguments:
    validators = [validators.MaxLengthValidator(0)]
    This will check if the maxlength of the field exceeds 0. If so, raise errors.
Self-defined validator:

Firstly, define the validation function:
e.g.

def check_for_z(value):
    if value[0].lower() != 'z':
        raise forms.ValidationError("Name needs to start with Z")

Then, pass the function name into the field's validators:
validators = [function_name]

Double check one field has been inputed correctly (e.g. email address)
def clean(self):
    all_clean_data = super().clean()
    email = all_clean_data['email']
    vmail = all_clean_data[‘verify_email’]

    if email != vmail:
        raise forms.ValidationError("Make sure emails match!")

For more information on this: https://docs.djangoproject.com/en/2.0/ref/forms/validation/#validating-fields-with-clean

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,843评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,538评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,187评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,264评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,289评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,231评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,116评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,945评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,367评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,581评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,754评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,458评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,068评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,692评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,842评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,797评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,654评论 2 354

推荐阅读更多精彩内容