美文网首页
Django 入门教程笔记(三)

Django 入门教程笔记(三)

作者: v小飞侠v | 来源:发表于2017-04-18 22:07 被阅读0次

    常用模版标签

    • 标签
    # if, ifequal, ifnotequal, for(forloop), 
    # cycle
    {% for o in some_list %}
        <tr class="{% cycle 'row1' 'row2' %}">
            ...
        </tr>
    {% endfor %}
    # {# #} comment, csrf_token, debug, filter, autoescape, firstof, load
    # now, lorem, spaceless, url, verbatim, with ...
    # 更详尽内容查看官方文档
    
    • 过滤器
    {{ value | lower }}
    # upper, add, cut, date, default, default_if_none, escape, dictsort
    # join, length, safe, slice, title, urlencode, truncatechars, striptags
    

    模版包含和继承

    {% include 'sub.html' with val='val' %}
    {% extends 'base.html' %}
    {% block name %} ... {% endblock %}
    {{ block.super }}
    

    admin 配置

    # 注册
    admin.site.register()
    # 扩展模型:
    @admin.register(Publisher)
    class PublisherAdmin(admin.ModelAdmin):
        list_display = ('name','city')
        search_fields
        list_filter
        list_editable
        ordering
        fields/exclude
        fieldsets
    

    Form 使用

    • django.forms.ModelForm
    # forms.py
    from django import forms
    class PublisherForm(forms.ModelForm):
        class Meta:
            model = Publisher
            fields = '__all__'
    # 
    publisher_form = PublisherForm()
    {% publisher_form.as_p %}
    publisher_form = PublisherForm(request.POST)
    #
    publisher_form.is_valid()
        publisher_form.save()
    
    • django.forms.Form
    from django import forms
    class PublisherForm(forms.Form):
        name = forms.CharField(label, error_messages={'required':'请输入'})
        ...
    # 
    publisher_form = PublisherForm()
    {% publisher_form.as_p %}
    publisher_form = PublisherForm(request.POST)
    #
    publisher_form.is_valid()
    name = publisher_form.cleaned_data['name']
    ...
    

    Form 自定义验证

    • validator (适用于多个Form 使用同一个自定义的验证逻辑)
    # forms.py
    #
    from django.core.exceptions import ValidationError
    from django.utils.translation import ugettext_lazy as _
    # 
    def validate_even(value):
        if value % 2 != 0:
            raise ValidationError(
                _('%(value)s is not an even number'),
                params={'value': value},
            )
    #     raise ValidationError('message')
    #     except Publisher.DoesNotExist
    #
    # models.py
    #
    from django.db import models
    # 
    class MyForm(forms.ModelForm):
        even_field = forms.IntegerField(validators=[validate_even])
    
    • clean_<fieldname> 验证某个字段
    # forms.py 中的 ModelForm 中定义函数
    class PublisherForm(forms.ModelForm):
        def clean_name(self):
            value = self.cleaned_data.get('name')
            ... // 验证逻辑
        return value
    
    • clean 对整个表单进行验证
    # forms.py 中的 ModelForm 中定义函数
    class PublisherForm(forms.ModelForm):
        def clean(self):
            cleaned_data = super(PublisherForm, self).clean()
            value = cleanen_data.get('name')
            # 官方例子直接 raise ValidationError
            sefl._errors['name'] = self.error_class(['message']) 
            ...
            return cleaned_data // 官文例子并不需要返回数据
    

    相关文章

      网友评论

          本文标题:Django 入门教程笔记(三)

          本文链接:https://www.haomeiwen.com/subject/ftmqzttx.html