Django學(xué)習(xí)總結(jié) 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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市窜觉,隨后出現(xiàn)的幾起案子谷炸,更是在濱河造成了極大的恐慌,老刑警劉巖禀挫,帶你破解...
    沈念sama閱讀 218,546評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件旬陡,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡语婴,警方通過(guò)查閱死者的電腦和手機(jī)描孟,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)忍饰,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)燕垃,“玉大人,你說(shuō)我怎么就攤上這事萍肆〔迹” “怎么了廉羔?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,911評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)僻造。 經(jīng)常有香客問(wèn)我憋他,道長(zhǎng),這世上最難降的妖魔是什么髓削? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,737評(píng)論 1 294
  • 正文 為了忘掉前任竹挡,我火速辦了婚禮,結(jié)果婚禮上立膛,老公的妹妹穿的比我還像新娘揪罕。我一直安慰自己,他們只是感情好宝泵,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,753評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布好啰。 她就那樣靜靜地躺著,像睡著了一般鲁猩。 火紅的嫁衣襯著肌膚如雪坎怪。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,598評(píng)論 1 305
  • 那天廓握,我揣著相機(jī)與錄音搅窿,去河邊找鬼。 笑死隙券,一個(gè)胖子當(dāng)著我的面吹牛男应,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播娱仔,決...
    沈念sama閱讀 40,338評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼沐飘,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了牲迫?” 一聲冷哼從身側(cè)響起耐朴,我...
    開(kāi)封第一講書(shū)人閱讀 39,249評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎盹憎,沒(méi)想到半個(gè)月后筛峭,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,696評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡陪每,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,888評(píng)論 3 336
  • 正文 我和宋清朗相戀三年影晓,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片檩禾。...
    茶點(diǎn)故事閱讀 40,013評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡挂签,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出盼产,到底是詐尸還是另有隱情饵婆,我是刑警寧澤,帶...
    沈念sama閱讀 35,731評(píng)論 5 346
  • 正文 年R本政府宣布戏售,位于F島的核電站啦辐,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏蜈项。R本人自食惡果不足惜芹关,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,348評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望紧卒。 院中可真熱鬧侥衬,春花似錦、人聲如沸跑芳。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,929評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)博个。三九已至怀樟,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間盆佣,已是汗流浹背往堡。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,048評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工械荷, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人虑灰。 一個(gè)月前我還...
    沈念sama閱讀 48,203評(píng)論 3 370
  • 正文 我出身青樓吨瞎,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親穆咐。 傳聞我的和親對(duì)象是個(gè)殘疾皇子颤诀,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,960評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容