Django入門チュートリアルノート(三)

3045 ワード

共通テンプレートラベル

  • ラベル
  • # if, ifequal, ifnotequal, for(forloop), 
    # cycle
    {% for o in some_list %}
        
            ...
        
    {% 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_ フィールド
  • の検証
    # 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 //