首页 > 解决方案 > django.template.exceptions.TemplateDoesNotExist: nouveaucontact.html

问题描述

我正在学习如何使用 Django,但我遇到了一个问题……我不知道为什么它告诉我我的 Template nouveaucontact.html 不存在……(我已将 os.path.join(BASE_DIR, 'templates') 放入我的设置中.py) 谢谢你的帮助:)

你可以看到我的代码:blog\urls.py

from django.urls import path, re_path
from . import views

urlpatterns = [
    path('accueil', views.accueil, name='accueil'),
    path('article/<int:id>-<slug:slug>', views.lire, name='lire'),
    path('article/<int:id_article>', views.view_article, name='afficher_article'),
    path('redirection', views.view_redirection, name='redirection'),
    path('contact/', views.contact, name='contact'),
    path('nouveaucontact/', views.nouveau_contact, name='nouveau_contact'),
    path('date', views.date_actuelle, name='date'),
    path('addition/<int:nombre1>/<int:nombre2>', views.addition, name='addition'),
    # autre manière d'écrire (d4 attend un nombre à 4 chiffres que la vue disposera sous le nom year
    re_path(r'^articles/(?P<year>\d{4})/(?P<month>\d{2})', views.list_articles, name='afficher_liste_articles')
]

视图.py

def nouveau_contact(request):
    sauvegarde = False
    form = NouveauContactForm(request.POST or None, request.FILES) #request.POST => pour els donnés textuelles et request.FILES pour les fichiers comme les photos
    if form.is_valid():
        contact = Contact()
        contact.nom = form.cleaned_data["nom"]
        contact.adresse = form.cleaned_data["adresse"]
        contact.photo = form.cleaned_data["photo"]
        contact.save()
        sauvegarde = True

    return render(request, 'nouveaucontact.html', {
        'form': form,
        'sauvegarde': sauvegarde
    })

表格.py

class NouveauContactForm(forms.Form):
    nom = forms.CharField()
    adresse = forms.CharField(widget=forms.Textarea)
    photo = forms.ImageField()

模型.py

class Contact(models.Model):
    nom = models.CharField(max_length=255)
    adresse = models.TextField()
    photo = models.ImageField(upload_to="photos/")

    def __str__(self):
        return self.nom

nouveaucontact.html

<h1>Ajouter un nouveau contact</h1>

{% if sauvegarde %}
    <p>Ce contact a bien été enregistré.</p>
{% endif %}

<p>
    <form method="post" enctype="multipart/form-data" action="."> <!-- # enctype ici permet au navigateur de pouvoir envoyer les fichiers au serveur web -->
       {% csrf_token %}
       {{ form.as_p }}
       <input type="submit"/>
    </form>
</p>

这里是黄屏

Django尝试加载

nouveaucontact.html 在我的项目中的位置

标签: pythondjango

解决方案


错误消息告诉您 Django 正在寻找模板crepes_bretonnes\templates\nouveaucontact.html,和crepes_bretonnes\blog\templates\nouveaucontact.html(以及 Django 安装中您可以忽略的其他几个位置)。

如果您将模板移动到其中任何一个位置并重新启动 runserver,那么 Django 应该会找到它。

如果使用blog\templates目录,则无需在设置'DIRS': os.path.join(BASE_DIR, 'templates')中进行TEMPLATES设置。


推荐阅读