2016-07-03 9 views
-2

誰でもの簡単な例を提供することができますので、これがどのように行われるかの基本的な慣用句を理解できますか?私はそのトピックについて理解できる参考資料を見つけることができません。自分のDjangoフォームウィジェットを作成するにはどうすればいいですか?

もう少しコンテキストを提供するために、私は自分のラジオボタンを作成したいと思います。それは特定の方法でレンダリングされます。

私はこの概念を理解するのを助けるために、非常にの簡単な例を探しています。

+0

その質問には次のようなコメントがあります。http://tothinkornottothink.com/post/10815277049/django-forms-i-custom-fields-and-widgets-in –

答えて

1

「非常に簡単な例」とは何を意味するのかは分かりません。ここでは非常に単純な例です:

from django.forms.widgets import Input 

class TelInput(Input): 
    input_type = 'tel' 

しかし、私は、これはずっとあなたを助けるとは思いません。

例をお探しの場合は、まだdjango source codeをご覧ください。

私は、これは、それがどのように動作するかを理解するのに十分であるべきだと思う:

from django.utils.encoding import force_text 
from django.utils.html import format_html 
from django.forms.utils import flatatt 

class Widget(...): 

    def __init__(self, attrs=None): 
     if attrs is not None: 
      self.attrs = attrs.copy() 
     else: 
      self.attrs = {} 

    def subwidgets(self, name, value, attrs=None, choices=()): 
     """ 
     Yields all "subwidgets" of this widget. Used only by RadioSelect to 
     allow template access to individual <input type="radio"> buttons. 
     Arguments are the same as for render(). 
     """ 
     yield SubWidget(self, name, value, attrs, choices) 

    def render(self, name, value, attrs=None): 
     """ 
     Returns this Widget rendered as HTML, as a Unicode string. 
     The 'value' given is not guaranteed to be valid input, so subclass 
     implementations should program defensively. 
     """ 
     raise NotImplementedError('subclasses of Widget must provide a render() method') 

    def build_attrs(self, extra_attrs=None, **kwargs): 
     "Helper function for building an attribute dictionary." 
     attrs = dict(self.attrs, **kwargs) 
     if extra_attrs: 
      attrs.update(extra_attrs) 
     return attrs 

    def value_from_datadict(self, data, files, name): 
     """ 
     Given a dictionary of data and this widget's name, returns the value 
     of this widget. Returns None if it's not provided. 
     """ 
     return data.get(name) 


class Input(Widget): 
    """ 
    Base class for all <input> widgets (except type='checkbox' and 
    type='radio', which are special). 
    """ 
    input_type = None # Subclasses must define this. 

    def format_value(self, value): 
     if self.is_localized: 
      return formats.localize_input(value) 
     return value 

    def render(self, name, value, attrs=None): 
     if value is None: 
      value = '' 
     final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) 
     if value != '': 
      # Only add the 'value' attribute if a value is non-empty. 
      final_attrs['value'] = force_text(self.format_value(value)) 
     return format_html('<input{} />', flatatt(final_attrs)) 

最も関連性の高い方法はPOSTデータ・ディクショナリからのウィジェットの値を抽出HTMLコードとしてウィジェットをレンダリングしrender()、およびvalue_from_datadict()あります。

関連する問題