2017-07-05 22 views
2

私は自分のウィジェットテンプレートを置き換えようとしていますが、TemplateDoesNotExistエラーが発生しています。アプリの\のforms.pyでDjango 1.11カスタムウィジェットテンプレートTemplateDoesNotExist

class SelectPlus(Select): 
    template_name = 'selectplus.html' 


class SimpleForm(ModelForm): 
    somefield = ModelChoiceField(
     queryset=SomeObjects.objects.all(), 
     widget=SelectPlus(attrs={'url': 'custom_url_to_context'}) 
    ) 

私はテンプレートローダがアプリケーションフォルダまたはメインテンプレートフォルダを検索しないことがわかりデバッグトレースで

TEMPLATES = [ 
{ 
    'BACKEND': 'django.template.backends.django.DjangoTemplates', 
    'DIRS': [ROOT_PATH, 'templates'], 
    'APP_DIRS': True, 
    'OPTIONS': { 
     'context_processors': [ 
      'django.template.context_processors.debug', 
      'django.template.context_processors.request', 
      'django.contrib.auth.context_processors.auth', 
      'django.contrib.messages.context_processors.messages', 
     ], 

    }, 
}, 

settings.pyで:

enter image description here

しかし、他のすべてのテンプレートが正常に動作します。

+1

テンプレートフォルダはアプリまたはプロジェクトレベルにありますか? –

+0

テンプレートフォルダはプロジェクトのルートフォルダにあります –

+0

あなたは正しい方向に私を指差しました!私は、アプリケーションフォルダ内のテンプレートフォルダを作成し、テンプレートが見つかりました! –

答えて

0

これを解決するには2通りの方法があります。

1)このようにテンプレートパスを修正してください。

TEMPLATES = [ 
{ 
    'BACKEND': 'django.template.backends.django.DjangoTemplates', 
    'DIRS': [ROOT_PATH, os.path.join(BASE_DIR, 'templates')], 
    'APP_DIRS': True, 
    'OPTIONS': { 
     'context_processors': [ 
      'django.template.context_processors.debug', 
      'django.template.context_processors.request', 
      'django.contrib.auth.context_processors.auth', 
      'django.contrib.messages.context_processors.messages', 
     ], 

    }, 
} 

2)アプリ内にテンプレートフォルダを追加します。ジャンゴ1.11で

1

# app/widgets.py 
from django.forms.widgets import DefaultWidget 

class SelectPlus(DefaultWidget): 
    template_name = 'app/selectplus.html' 

は、変更したいウィジェットをインポートします。あなたの選択はここにあります:https://docs.djangoproject.com/en/1.11/ref/forms/widgets/#built-in-widgets

サブクラスを作成し、テンプレート名を指定します。

# app/templates/app/selectplus.html 
<select name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}>{% for group_name, group_choices, group_index in widget.optgroups %}{% if group_name %} 
    <optgroup label="{{ group_name }}">{% endif %}{% for option in group_choices %} 
    {% include option.template_name with widget=option %}{% endfor %}{% if group_name %} 
    </optgroup>{% endif %}{% endfor %} 
</select> 

テンプレートを作成します。これはdjango/forms/widgets/select.htmlから正確にコピーされますが、ここに必要なものを置くことができます。インスピレーションのために他の既存のウィジェットテンプレートを参照することもできます。あなたの選択は、ここで見つけることができます:https://github.com/django/django/tree/master/django/forms/templates/django/forms/widgets

# app/forms.py 
from .widgets import SelectPlus 

class SimpleForm(ModelForm): 
    my_field = forms.ExampleField(widget=SelectPlus()) 

顧客ウィジェット(SelectPlus)をインポートして、フォームのフィールドに追加します。

最後に、テンプレート内でメインフィールドをレンダリングし、app/templates/app/selectplus.htmlを参照します。

関連する問題