简体   繁体   中英

django can't find template when trying to use forms

I am trying to follow the django documentation howto create a form using sjango form class. I am doing every step but when trying to access my form it says that is cannot find the template:

django.template.exceptions.TemplateDoesNotExist: lform

heres is my forms.py:

class LoginForm(Form):
    
    uname=CharField(label='user name',max_length=20)
    passw=CharField(label='password', max_length=20)

the template lform.html:

<form action="ulogin" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">
</form>

and my view. I think the problem is in the render function:

def testform(request):

    if request.method=='POST':
        form=LoginForm(request.POST)
        
        if form_is_valid():
            return render('index')
        else:
            HttpResponseRedirect('index')

    else:
        form=LoginForm()
    
    return render(request,'lform',{'form':form})

and url.py:

path('lform',views.testform,name='lform')

the last line in the view function,

return render(request,'lform',{'form':form})

gives the error any suggestions?

You are trying to render the template lform . Your template is lform.html .

You need to provide complete path to your template relative with your template path settings.

Correct your template name:

def testform(request):

if request.method=='POST':
    form=LoginForm(request.POST)
    
    if form_is_valid():
        return render('index')
    else:
        HttpResponseRedirect('index')

else:
    form=LoginForm()

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

In your settings.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ["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',
            ],
        },
    },
]

ok, the error was simply that the path to templates was missing somehow. I moved the template further up in the directory and now it displays the form. Thanks for all answers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM