Джанго не применяет JS и CSS Ive связаны - PullRequest
0 голосов
/ 16 марта 2019

Ниже приведен код моего проекта, который также включает в себя 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-страницу так, как я хочу. Изображение Изображение

Ответы [ 3 ]

0 голосов
/ 16 марта 2019

попробуйте

в settings.py

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

в базовых URL проекта

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

для более подробной информации см. это

надеюсь, это поможет

0 голосов
/ 17 марта 2019

В ваших settings.py добавьте это,

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

Удалите строку STATICFILES_DIRS=[STATIC_DIR,] из settings.py.

Теперь ваш статический корень указывает на вашу статическую папку внутри вашего приложения. Вы можете указать ваши статические файлы в соответствии с вашей папкой css или js и т. Д.

Примечание. Это будет работать только в том случае, если отладка имеет значение true. Если отладка ложна, вам нужно изменить статический корень в соответствии с вашим рабочим сервером.

0 голосов
/ 16 марта 2019

Я полагаю, в вашем проекте есть несоответствие пути.Сначала попробуйте

python manage.py collectstatic

. Он соберет все ваши статические файлы в статической папке, которую вы упомянули в файле settings.py.Затем в шаблоне, когда вы делаете {% static ...%}, это означает, что / static / (как видно из вашего setting.py) уже применено, теперь вы должны передать путь внутри статической папки.Предположим, у вас есть style.css внутри папки css, которая находится внутри статической папки, вы должны написать

{%static 'css/styles.css'%}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...