【问题标题】:Django not applying the js and css ive linkedDjango没有应用链接的js和css
【发布时间】:2019-03-16 06:54:52
【问题描述】:

以下是我的项目的代码,其中还包括 index.html、css、js、settings.py。 我已经在我的项目文件中正确地制作了这些文件夹,所以它也不是源问题。 我正在尝试从这里应用笔: https://codepen.io/soju22/pen/ZPXLZe

index.html

      <!DOCTYPE html>
{% load static %}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="{% static "clubapp/js/logmain.js" %}">

    </script>
  <link rel="stylesheet" href="{% static "clubapp/css/yo.css" %}"/>
  </head>
  <body>
    <div id="info">
      <h1>Tribute to Matthew Shlian</h1>
      <h2><em>Paper Artist</em> : Cutting Folding Gluing</h2>
      <p>This pen is inpired by <em><a href="https://www.instagram.com/p/BtLYfbOgR8v/" target="_blank">Unholy 132</a></em></p>
      <a class="link" href="https://www.mattshlian.com/" target="_blank"><i class="fa fa-link" aria-hidden="true"></i></a>
      <a class="link" href="https://www.instagram.com/matthewshlian/" target="_blank"><i class="fa fa-instagram" aria-hidden="true"></i></a>
    </div>
  </body>
</html>

CSS

html, body {
  margin: 0;
  width: 100%;
  height: 100%;
  font-family: 'Montserrat', sans-serif;
}

canvas {
  position: fixed;
  width: 100%;
  height: 100%;
}

#info {
  position: absolute;
  width: 100%;
  top: 25%;
  z-index: 10;
  color: #fff;
  text-shadow: 2px 2px 2px #000;
  text-align: center;
}

a {
  color: #fff;
}

.link {
  display: inline-block;
  padding: 4px;
  margin: 0 0.5em;
  border-radius: 8px;
  background-color: rgba(255, 255, 255, 0.1);
  color: #fff;
  text-shadow: none;
  font-size: 24px;
  transition: all 0.4s;
  &:hover {
    color: #FF5649;
    background-color: rgba(255, 255, 255, 1);
  }
}

JS

let scene, camera, cameraCtrl, renderer;
let light, light1;
let width, height, cx, cy;
let rWidth, rHeight;
const TMath = THREE.Math;

let conf = {
  color: 0x9C1E15,
  objectWidth: 30,
  colWidth: 50,
  rowHeight: 50,
  noiseCoef: 50,
  mouseCoef: 0.1,
  lightIntensity: 1.5,
  ambientColor: 0x808080,
  light1Color: 0xffffff,
  light2Color: 0xffffff,
  light3Color: 0xffffff,
  light4Color: 0xffffff,
};

let objects;
const simplex = new SimplexNoise();

let mouseOver = false;
const mouse = new THREE.Vector2();
const mousePlane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
const mousePosition = new THREE.Vector3();
const raycaster = new THREE.Raycaster();

function init() {
  renderer = new THREE.WebGLRenderer({ antialias: true });
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

  camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 0.1, 1000);
  camera.position.z = 200;
cameraCtrl = new THREE.OrbitControls(camera);
  cameraCtrl.enabled = false;

  let size = getRendererSize();
  rWidth = size[0];
  rHeight = size[1];

  initScene();
  initEventHandlers();

  camera.position.z = 300;
  animate();
};

function initScene() {
  scene = new THREE.Scene();
  scene.background = new THREE.Color(0xffffff);

  initLights();
  initObjects();
}

function initLights() {
  light = new THREE.AmbientLight(conf.ambientColor);
  scene.add(light);

  light1 = new THREE.PointLight(conf.light1Color, conf.lightIntensity, 500);
  light1.position.z = 100;
  light1.castShadow = true;
  scene.add(light1);
}

function initObjects() {
  let geo = new THREE.PlaneBufferGeometry(rWidth * 2, rHeight * 2);
  let mat = new THREE.MeshPhongMaterial({ color: conf.color });
  let plane = new THREE.Mesh(geo, mat);
  plane.castShadow = false;
  plane.receiveShadow = true;
  scene.add(plane);

  objects = [];
  geo = new THREE.BoxGeometry(conf.objectWidth, conf.objectWidth, conf.objectWidth);
  mat = new THREE.MeshPhongMaterial({ color: conf.color });
  let nx = Math.round(rWidth / conf.colWidth) + 1;
  let ny = Math.round(rHeight / conf.rowHeight) + 1;
  let x, y, rx, ry, rz;
  for (let i = 0; i < nx; i++) {
    for (let j = 0; j < ny; j++) {
      mesh = new THREE.Mesh(geo, mat);
      x = -rWidth / 2 + i * conf.colWidth;
      y = -rHeight / 2 + j * conf.rowHeight;
      mesh.position.set(x, y, conf.objectWidth);
      mesh.castShadow = true;
      mesh.receiveShadow = true;
      objects.push(mesh);
      scene.add(mesh);
    }
  }
}

function animateObjects() {
  const time = Date.now() * 0.00005;
  const mx = mouse.x * conf.mouseCoef;
  const my = mouse.y * conf.mouseCoef;
  const noise = conf.noiseCoef * 0.00001;
  let mesh;
  for (let i = 0; i < objects.length; i++) {
    mesh = objects[i];
    let nx = mesh.position.x * noise + mx + time;
    let ny = mesh.position.y * noise + my + time;
    rx = simplex.noise2D(nx, ny) * Math.PI;
    ry = simplex.noise2D(ny, nx) * Math.PI;
    // rz = simplex.noise2D(nx + ny, nx - ny) * Math.PI;
    mesh.rotation.set(rx, ry, 0);
  }
}

function initEventHandlers() {
  onWindowResize();
  window.addEventListener('resize', onWindowResize, false);

  document.body.addEventListener('mousemove', e => {
    const v = new THREE.Vector3();
    camera.getWorldDirection(v);
    v.normalize();
    mousePlane.normal = v;

    mouseOver = true;
    mouse.x = (e.clientX / width) * 2 - 1;
    mouse.y = - (e.clientY / height) * 2 + 1;

    raycaster.setFromCamera(mouse, camera);
    raycaster.ray.intersectPlane(mousePlane, mousePosition);
    setMapValue(mousePosition.x, mousePosition.y, 50);
  });
  document.body.addEventListener('mouseout', e => { mouseOver = false; });
}

function animate() {
  requestAnimationFrame(animate);

  animateObjects();
  animateLights();

  renderer.render(scene, camera);
};

function animateLights() {
  if (mouseOver) {
    light1.position.x = mousePosition.x;
    light1.position.y = mousePosition.y;
  } else {
    const time = Date.now() * 0.001;
    light1.position.x = Math.sin(time * 0.1) * rWidth / 3;
    light1.position.y = Math.cos(time * 0.2) * rHeight / 3;
  }
}

function onWindowResize() {
  width = window.innerWidth; cx = width / 2;
  height = window.innerHeight; cy = height / 2;
  camera.aspect = width / height;
  camera.updateProjectionMatrix();
  renderer.setSize(width, height);
}

function getRendererSize() {
  mouse.x = 1; mouse.y = 1;
  raycaster.setFromCamera(mouse, camera);
  raycaster.ray.intersectPlane(new THREE.Plane(new THREE.Vector3(0, 0, 1), 0), mousePosition);
  return [mousePosition.x * 2, mousePosition.y * 2];
}

function rnd(max, negative) {
  return negative ? Math.random() * 2 * max - max : Math.random() * max;
}

init();

settings.py

​​>
import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
STATIC_DIR = os.path.join(BASE_DIR,'static')
MEDIA_DIR = os.path.join(BASE_DIR,'media')

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '^ievtzxc470l!@awu+sq&p9^p6x_z1a@o02uc!cis#od*84g$c'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'clubapp',
]

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 = 'clubproj.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR,],
        '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 = 'clubproj.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    'django.contrib.auth.hashers.BCryptPasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
]

# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'OPTIONS':{'min_length':9}
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS=[
STATIC_DIR,
]

`以上是所有文件,请提供解决方案,因为我无法按照我想要的方式获取我的 html 网页。 Image Image

【问题讨论】:

  • 所以不能应用静态文件,主要原因可能是路径不匹配。您的项目中的文件夹结构是什么?
  • 我添加了结构截图,请查看。
  • 嘿,你想用我的笔做什么? ^^

标签: javascript python html css django


【解决方案1】:

我猜您的项目中存在路径不匹配。 首先,尝试

python manage.py collectstatic

它将收集您在 settings.py 中提到的静态文件夹中的所有静态文件。 然后在模板中,当您执行 {%static ...%} 时,这意味着 /static/(如您的 setting.py 中所见)已经应用,现在您必须在静态文件夹中传递路径。 假设您在静态文件夹中的 css 文件夹中有 style.css,您必须编写

{%static 'css/styles.css'%}

【讨论】:

  • 不,它说:系统找不到指定的路径:'C:\\Users\\heerd\\Desktop\\club\\clubproj \\static\\'
【解决方案2】:

试试这个

在 settings.py 中

STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR + '/static/'

在项目基础网址中

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

更多详情请参考this

希望对你有帮助

【讨论】:

  • @HeerDonda 你能显示项目的目录结构吗
  • 是的,我添加了截图,请看一下。
【解决方案3】:

在你的 settings.py 中添加这个,

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

从 settings.py 中删除您的 STATICFILES_DIRS=[STATIC_DIR,] 行。

现在您的静态根目录指向您应用内的静态文件夹。您可以根据您的 css 或 js 文件夹等指向您的静态文件。

注意 - 这只有在调试为真时才有效。一旦 debug 为 false,那么您需要根据您的生产服务器更改您的静态根目录。

【讨论】:

    猜你喜欢
    • 2012-05-17
    • 1970-01-01
    • 2016-07-24
    • 2019-09-20
    • 1970-01-01
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    相关资源
    最近更新 更多