我是django和python的初学者,目前我被Django教程的Creating our home page所困。我收到“ TemplateDoesNotExist错误”错误。我也在使用Windows。我在做什么错了?
Settings.py:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
import os
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'cg#p$g+j9tax!#a3cup@1$8obt2_+&k3q+pmu)5%asj6yjpkag')
DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False'
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'catalog.apps.CatalogConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'locallibrary.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
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',
],
},
},
]
WSGI_APPLICATION = 'locallibrary.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Chicago'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
StackTrace:
TemplateDoesNotExist at /catalog/
index.html
Request Method: GET
Request URL: http://127.0.0.1:8000/catalog/
Django Version: 2.1.5
Exception Type: TemplateDoesNotExist
Exception Value:
index.html
Exception Location: C:\Users\AjitGoel\Envs\my_django_environment\lib\site-packages\django\template\loader.py in get_template, line 19
Python Executable: C:\Users\AjitGoel\Envs\my_django_environment\Scripts\python.exe
Python Version: 3.7.2
Python Path:
['C:\\Users\\AjitGoel\\django-projects\\locallibrary',
'C:\\Users\\AjitGoel\\Envs\\my_django_environment\\Scripts\\python37.zip',
'C:\\Users\\AjitGoel\\Envs\\my_django_environment\\DLLs',
'C:\\Users\\AjitGoel\\Envs\\my_django_environment\\lib',
'C:\\Users\\AjitGoel\\Envs\\my_django_environment\\Scripts',
'c:\\users\\ajitgoel\\appdata\\local\\programs\\python\\python37\\Lib',
'c:\\users\\ajitgoel\\appdata\\local\\programs\\python\\python37\\DLLs',
'C:\\Users\\AjitGoel\\Envs\\my_django_environment',
'C:\\Users\\AjitGoel\\Envs\\my_django_environment\\lib\\site-packages']
Server time: Sun, 10 Feb 2019 23:21:43 -0600
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.filesystem.Loader: C:\Users\AjitGoel\django-projects\locallibrary\templates\index.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\AjitGoel\Envs\my_django_environment\lib\site-packages\django\contrib\admin\templates\index.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\AjitGoel\Envs\my_django_environment\lib\site-packages\django\contrib\auth\templates\index.html (Source does not exist)
base_generic.html:
<!DOCTYPE html>
<html lang="en">
<head>
{% block title %}<title>Local Library</title>{% endblock %}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<!-- Add additional CSS in static file -->
{% load static %}
<link rel="stylesheet" href="{% static 'css/styles.css' %}">
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-sm-2">
{% block sidebar %}
<ul class="sidebar-nav">
<li><a href="{% url 'index' %}">Home</a></li>
<li><a href="">All books</a></li>
<li><a href="">All authors</a></li>
</ul>
{% endblock %}
</div>
<div class="col-sm-10 ">{% block content %}{% endblock %}</div>
</div>
</div>
</body>
</html>
Views.py:
from django.shortcuts import render
from catalog.models import Book, Author, BookInstance, Genre
def index(request):
# Generate counts of some of the main objects
num_books = Book.objects.all().count()
num_instances = BookInstance.objects.all().count()
# Available books (status = 'a')
num_instances_available = BookInstance.objects.filter(status__exact='a').count()
# The 'all()' is implied by default.
num_authors = Author.objects.count()
context = {
'num_books': num_books,
'num_instances': num_instances,
'num_instances_available': num_instances_available,
'num_authors': num_authors,
}
# Render the HTML template index.html with the data in the context variable
return render(request, 'index.html', context=context)
index.html:
{% extends "base_generic.html" %}
{% block content %}
<h1>Local Library Home</h1>
<p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
<h2>Dynamic content</h2>
<p>The library has the following record counts:</p>
<ul>
<li><strong>Books:</strong> {{ num_books }}</li>
<li><strong>Copies:</strong> {{ num_instances }}</li>
<li><strong>Copies available:</strong> {{ num_instances_available }}</li>
<li><strong>Authors:</strong> {{ num_authors }}</li>
</ul>
{% endblock %}
答案 0 :(得分:1)
如果要在应用内放置模板,请遵循以下目录结构
templates/<app_name>/your_template
然后在view.py
中以这种方式使用
返回render(request,'/ your_template',context = context)
如果您要将模板放置在templates
根目录中,请遵循以下结构
templates/<app_name>/your_template
然后在view.py
中以这种方式使用
return render(request, '<app_name>/your_template', context=context)
答案 1 :(得分:0)
os.path.join(BASE_DIR, 'templates')
通过这行代码,您添加的模板应该位于项目的根文件夹中。在项目的根目录中创建templates
文件夹。
答案 2 :(得分:0)
templates
目录,您应该像这样在settings.py
的{{1}}中添加
TEMPLATES_DIRS
它会做什么,它将在此处指定的目录中查找您创建的模板,即TEMPLATE_DIRS = (
os.path.join(BASE_DIR, "/localllibrary/templates"),
)
。如果看到它是一个元组或可以是一个列表,则可以在此处添加多个目录。 index.html
是您的django项目的根,相对而言,它不是硬编码的。
答案 3 :(得分:0)
您的文件结构应如下所示:
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.example.finaldemo.Model.Users;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class LoginActivity extends AppCompatActivity {
private EditText Email,pswrd;
private Button Login;
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Email= (EditText)findViewById(R.id.loginemail);
pswrd=(EditText) findViewById(R.id.loginpswrd);
Login=(Button)findViewById(R.id.loginbtn);
progressBar=(ProgressBar)findViewById(R.id.loginprogressbar);
Login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LoginUser();
}
});
}
private void LoginUser(){
String email = Email.getText().toString().trim();
String pwd = pswrd.getText().toString().trim();
if (email.isEmpty()) {
Email.setError("Email Required");
Email.requestFocus();
}
else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
Email.setError("Enter a valid Email Address");
Email.requestFocus();
}
else if (pwd.isEmpty()) {
pswrd.setError("Password Required");
pswrd.requestFocus();
}else{
progressBar.setVisibility(View.VISIBLE);
AllowAccess(email,pwd);
}
}
private void AllowAccess(final String email, final String pwd) {
final DatabaseReference Rootref;
Rootref = FirebaseDatabase.getInstance().getReference();
Rootref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child("Users").child(email).exists()){
Users userdata = dataSnapshot.child("Users").child(email).getValue(Users.class);
if(userdata.getEmail().equals(email)){
if(userdata.getPassword().equals(pwd)){
Toast.makeText(LoginActivity.this, "Logged in Successfully", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
}else{
progressBar.setVisibility(View.GONE);
Toast.makeText(LoginActivity.this, "Account Invalid", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
现在,如果您的模板/静态文件位于项目根目录的模板/静态文件夹中,则可以轻松地将其称为import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
import java.util.regex.Pattern;
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
private EditText fname,email,pswrd,cpswrd,phone;
private static final Pattern PASSWORD_PATTERN = Pattern.compile("^" + "(?=.*[0-9])" + "(?=.*[a-z])" + "(?=.*[A-Z])" + "(?=.*[a-zA-Z])" + "(?=.*[@#$%^&+=])" + "(?=\\S+$)" + ".{8,32}" + "$");
//private FirebaseAuth mAuth;
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
fname = (EditText) findViewById(R.id.regfname);
email = (EditText) findViewById(R.id.regemail);
pswrd = (EditText) findViewById(R.id.regpassword);
cpswrd =(EditText) findViewById(R.id.regcpassword);
phone = (EditText) findViewById(R.id.regphone);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
findViewById(R.id.regbtn).setOnClickListener(this);
// mAuth = FirebaseAuth.getInstance();
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.regbtn:
createAccount();
break;
}
}
private void createAccount() {
String name = fname.getText().toString().trim();
String emailid = email.getText().toString().trim();
String pwd = pswrd.getText().toString().trim();
String cpwd = cpswrd.getText().toString().trim();
String phoneno = phone.getText().toString().trim();
if (name.isEmpty()) {
fname.setError("Name Required");
fname.requestFocus();
}
else if (emailid.isEmpty()) {
email.setError("Email Required");
email.requestFocus();
}
else if (!Patterns.EMAIL_ADDRESS.matcher(emailid).matches()) {
email.setError("Enter a valid Email Address");
email.requestFocus();
}
else if (pwd.isEmpty()) {
pswrd.setError("Password Required");
pswrd.requestFocus();
}
else if (!PASSWORD_PATTERN.matcher(pwd).matches()) {
pswrd.setError("Password should contain atleast 1 upper and lowercase, 1 special char,1 number and should be between 8-32 charcters");
pswrd.requestFocus();
}
else if (cpwd.isEmpty()) {
cpswrd.setError("Password Required");
cpswrd.requestFocus();
}
else if (!pwd.equals(cpwd)) {
cpswrd.setError("Password and Confirm Password did not match");
cpswrd.requestFocus();
}
else if (phoneno.isEmpty()) {
phone.setError("Phone Number is Required");
phone.requestFocus();
}
else if (phone.length() != 10) {
phone.setError("Enter Valid Phone Number");
phone.requestFocus();
}
else{
progressBar.setVisibility(View.VISIBLE);
validateUser(name,emailid,pwd,phoneno);
}
}
private void validateUser(final String name, final String emailid, final String pwd, final String phoneno) {
final DatabaseReference Rootref;
Rootref = FirebaseDatabase.getInstance().getReference();
Rootref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(!(dataSnapshot.child("Users").child(phoneno).exists() || dataSnapshot.child("Users").child(emailid).exists())){
HashMap<String, Object> Userdata = new HashMap<>();
Userdata.put("Name", name);
Userdata.put("Email", emailid);
Userdata.put("Password", pwd);
Userdata.put("Phone", phoneno);
Rootref.child("Users").child(phoneno).updateChildren(Userdata).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(RegisterActivity.this, "Congratulations, Your account has been created", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}else{
progressBar.setVisibility(View.GONE);
Toast.makeText(RegisterActivity.this,"Network Error", Toast.LENGTH_SHORT).show();
}
}
});
}else{
Toast.makeText(RegisterActivity.this, "The entered credentials are already Registered", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Toast.makeText(RegisterActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
}
}
或myProject
├── myProject
| ├── __init__.py
| ├── settings.py
| ├── urls.py
| ├── wsgi.py
├── myApp
| ├── static <-- Static files can go here
| | ├── myApp <-- Create a folder with the same name as the app name, recommended but not required
| | | ├── css
| | | | ├── style.css
| | | ├── js
| | | | ├── some.js
| ├── templates <-- Templates can be here
| | ├── myApp <-- Create a folder with the same name as the app name, recommended but not required
| | | ├── index.html
| | | ├── other.html
| ├── __init__.py
| ├── models.py
| ├── urls.py
| ├── views.py
├── templates <-- Templates can be here too
| ├── sometemplate.html
├── static <-- Static files can go here too
| ├── css
| | ├── somecss.css
| ├── js
。
如果它位于您应用程序的模板文件夹中,则如下所示:
someplace.html
然后您可以像这样使用它:css/somecss.css
。但是建议您在模板文件夹中使用应用名称创建另一个文件夹,以避免混淆,例如:
myApp --> templates --> myTemplate.html
现在,您将这样称呼它:myTemplate.html
,这样可以避免混淆,因为您将知道来自哪个应用程序模板,并且还可以使用具有相同名称的模板(例如{{1} }或myApp --> templates --> myApp --> myTemplate.html
)。静态文件也是如此。