I am trying to deploy my app to heroku.
I successfully deployed to app after dealing with some bugs(the CSS wouldn't load, or images wouldn't load). Now when I deploy the app works fine, when DEBUG = True.
When I change DEBUG = False all the images fail to load.
Here is my code:
settings.py
"""
Django settings for DBSF project.
Generated by 'django-admin startproject' using Django 3.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import django_heroku
import os
from dotenv import load_dotenv
load_dotenv()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['SECRET_KEY']
AUTH_USER_MODEL = 'social.User'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['desolate-lowlands-74512.herokuapp.com', 'localhost', '127.0.0.1']
# Application definition
INSTALLED_APPS = [
'channels',
'social',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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 = 'DBSF.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
WSGI_APPLICATION = 'DBSF.wsgi.application'
ASGI_APPLICATION = 'DBSF.asgi.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'EST'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
MEDIA_ROOT= os.path.join(BASE_DIR, 'media/')
MEDIA_URL= "/media/"
Here's asgi.py
"""
ASGI config for DBSF project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
import social.routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DBSF.settings')
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
social.routing.websocket_urlpatterns
)
),
})
here's wsgi.py
"""
WSGI config for DBSF project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DBSF.settings')
application = get_wsgi_application()
heres the procfile.windows
web: python manage.py runserver 0.0.0.0:5000
heres the procfile
web: gunicorn DBSF.wsgi
heres layout.html
{% load static %}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="https://unpkg.com/#babel/standalone/babel.min.js"></script>
<script crossorigin src="https://unpkg.com/react#17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#17/umd/react-dom.development.js"></script>
<script type='text/babel' src="{% static 'social/javascript/react_components.js' %}"></script>
<script type="text/babel" src="{% static 'social/javascript/layout.js' %}"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie#rc/dist/js.cookie.min.js"></script>
{% block head %}{% endblock %}
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Tangerine">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="{% static 'social/styles/base.css' %}">
<link rel="shortcut icon" type="image/png" href="{% static 'social/favicon/favicon.ico' %}"/>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<nav class='main_nav'>
<a href="{% url 'index' %}" title='homepage'>DBSF</a>
<form action="/find_friends" method="GET">
<input name='search_term' type='text' placeholder='Search for friends'>
<input class='search_friends_button' type="submit" value='🔍'></form>
<a href="{% url 'profile' %}">
{% if user.profile_pic.url != '' %}
<img class="profile_pic_small_icon" src="{{user.profile_pic.url}}" alt="profile_pic">
{% else %}
<img class='profile_pic_small_icon' src="{% static 'social/core_images/no_image.jpg' %}" alt="{{user}} hasn't uploaded an image yet">
{% endif %}
{{user|title}}
</a>
Messages
<form class="logout_form" action="{% url 'logout' %}" method="post">
{% csrf_token %}
<a class='logout_a' href="/logout">Log out</a>
</form>
</nav>
<div class="messages">
<h1>{{message}}</h1>
</div>
<div class="side_bar">
<h4>Friend Requests</h4>
<div id="friendship_request_div"></div>
</div>
<div class="main">
{% block body %}{% endblock %}
</div>
<div class="friends_right_div">
<h4>Friends</h4>
<div id='friendship_div'></div>
</div>
<div id='message_box' class='message_box'>
</div>
</body>
</html>
So basically I need to figure out why DEBUG = False doesn't allow the images to load.
Let me know if it is clear what I am asking or if you need any other files to help me!
Thank you
In deployment mode, you need some bucket(e.g, Amazon S3) to store your static (and media) files and serve them from there. Heroku also has some plugins to do so(needs credit card). Heroku doesnot provide any way to do so without a bucket. That is why, they are not rendering. Also with DEBUG=True, all the media files will still vanish after 30 minutes as heroku runs on dynos and dynos refresh after every 30 minutes thus removing all the media files.
Try putting this in your urls.py:
from django.views.static import serve
and this in your urlpatterns:
url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),
In production you'd typically have nginx or something else serving media files like images. If you just want a quick and dirty way to still see them with DEBUG = True then this should add the media routes to the url patterns.
Related
I am developing a Django Ajax search that searches through a list of college courses. After I finished implementing, I realized that the search doesn't work. However, my shell prints out the updated URL. Here is what I mean.
If I search for BUS, My console would do this, but my HTML file wouldn't change:
Note: If it's easier, I can add a GitHub link to my code
UPDATE: Github link
$ python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
August 13, 2020 - 11:37:25
Django version 3.0, using settings 'smore.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[13/Aug/2020 11:37:28] "GET /courses/ HTTP/1.1" 200 19376
Not Found: /artists/
[13/Aug/2020 11:37:35] "GET /artists/?q=BUS HTTP/1.1" 404 2092
I can't seem to understand where the /artists/ is coming from. I changed the endpoints and the URLs respectively. Here are my files
urls.py
from django.contrib import admin
from django.urls import path
from search import views as v
urlpatterns = [
path('admin/', admin.site.urls),
path('courses/', v.course_view, name = "courses")
]
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__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = blahblahblah
# 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',
'search.apps.SearchConfig',
]
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 = 'smore.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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 = 'smore.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/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/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
# Don't forget to use absolute paths, not relative paths.
os.path.join(BASE_DIR, "static/"),
os.path.join(BASE_DIR, "static/search/"), # for the css file
)
STATICFILES_FINDERS = [
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
]
views.py
from django.shortcuts import render
from .models import collegeCourse
from django.template.loader import render_to_string
from django.http import JsonResponse
# Create your views here.
# core/views.py
def course_view(request):
ctx = {}
url_param = request.GET.get("q")
if url_param:
courses = collegeCourse.objects.filter(course_code__icontains=url_param)
else:
courses = collegeCourse.objects.all()
ctx["courses"] = courses
if request.is_ajax():
html = render_to_string(
template_name="partial-courses.html",
context={"courses": courses}
)
data_dict = {"html_from_view": html}
return JsonResponse(data=data_dict, safe=False)
return render(request, "courses.html", context=ctx)
Base.html
<!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Search | Courses</title>
<!-- Bootstrap-->
<link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"crossorigin="anonymous">
<!-- JQuery -->
<script src="{% static 'javascript/jquery-3.4.1.min.js' %}"></script>
<!-- FontAwesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous">
<link href="{% static "main.css" %}" rel="stylesheet" media="screen">
</head>
<body>
<div class="container">
{% block content %}
{% endblock %}
</div>
{% block footer %}
<script type="text/javascript" src="{% static "javascript/main.js" %}"></script>
{% endblock %}
</body>
</html>
courses.html
{% extends "base.html" %}
{% block content %}
<h3>Courses</h3>
<div class="row">
{# icon and search-box #}
<div class="col-6 align-left">
<i id="search-icon" class="fas fa-search"></i>
<input id="user-input" placeholder="Search">
</div>
{# course section #}
<div id="replaceable-content" class="col-6">
{% include 'partial-courses.html' %}
</div>
</div>
{% endblock %}
partial-courses.html
{# partial-courses.html #}
{% if courses %}
<ul>
{% for course in courses %}
<li>{{ course.course_code }}</li>
{% endfor %}
</ul>
{% else %}
<p>No course found.</p>
{% endif %}
Main.js
const user_input = $("#user-input")
const search_icon = $('#search-icon')
const courses_div = $('#replaceable-content')
const endpoint = '/courses/'
const delay_by_in_ms = 700
let scheduled_function = false
let ajax_call = function (endpoint, request_parameters) {
$.getJSON(endpoint, request_parameters)
.done(response => {
// fade out the courses_div, then:
courses_div.fadeTo('slow', 0).promise().then(() => {
// replace the HTML contents
courses_div.html(response['html_from_view'])
// fade-in the div with new contents
courses_div.fadeTo('slow', 1)
// stop animating search icon
search_icon.removeClass('blink')
})
})
}
user_input.on('keyup', function () {
const request_parameters = {
q: $(this).val() // value of user_input: the HTML element with ID user-input
}
// start animating the search icon with the CSS class
search_icon.addClass('blink')
// if scheduled_function is NOT false, cancel the execution of the function
if (scheduled_function) {
clearTimeout(scheduled_function)
}
// setTimeout returns the ID of the function to be executed
scheduled_function = setTimeout(ajax_call, delay_by_in_ms, endpoint, request_parameters)
})
Kind of a blunder error. But I didn't properly import my model. Instead of from .models import whatever, I needed to do from appname.models import whatever
Anytime I include a link to bootstrap.min.css lying locally in my Django project, my drop-down menu becomes non-clickable. Am a learning Django with no much knowledge of bootstrap. The tutorial am following used cdn to include the bootstrap but I downloaded it manually because of internet connection. Although the downloaded bootstrap is working but the drop-down menu is not working. Can someone help me out.. I can't continue learning at this stage. Thanks in advance.
The code is below.
{% load static %}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-">
<meta name="viewport" content="width=device-width, initial-scale=, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"
integrity="sha-MCw/SFnGEfJTGXwEOngsVZtNXFoaoApmYmi\ uXoPkFOJwJERdknLPMO"
crossorigin="anonymous">
<title>{% block title %}Newspaper App{% endblock title %}</title>
</head>
<body>
<nav class="navbar navbar-expand-md navbar-dark bg-dark mb-">
<a class="navbar-brand" href="{% url 'home' %}">Newspaper</a>
<button class="navbar-toggler" type="button" data-toggle="collapse"
data-target="#navbarCollapse" aria-controls="navbarCollapse"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
{% if user.is_authenticated %}
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link dropdown-toggle" data-toggle="dropdown "href="#" id="userMenu"
aria-expanded="false">
{{ user.username }}
</a>
<div class="dropdown-menu dropdown-menu-right"
aria-labelledby="userMenu">
<a class="dropdown-item"
href="{% url 'password_change'%}">Change password</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="{% url 'logout' %}">
Log Out</a>
</div>
</li>
</ul>
{% else %}
<form class="form-inline ml-auto">
<a href="{% url 'login' %}" class="btn btn-outline-secondary">
Log In</a>
<a href="{% url 'signup' %}" class="btn btn-primary ml-">
Sign up</a>
</form>
{% endif %}
</div>
</nav>
<div class="container">
{% block content %}
{% endblock content %}
</div>
<!-- Optional JavaScript -->
<!-- <jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-...slim.min.js" integrity="sha-qi/X+DzOrTabKJStQIAqVgRVzpbzosmXKp\ YfRvH+abtTEPijizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/\ ../ umd/popper.min.js" integrity="sha-ZMPrVomIykV++JUJjBkWLaUAdnaCwoqbB\ JiSnjAK/ lWvCWPIPm" crossorigin="anonymous"></script>
<script src="{% static 'js/bootstrap.min.js' %}"
integrity="sha-ChfqqxuZUCnJSK+MXmPNIyEZbWhIMqErYiqJxyMiZ\ OW/JmZQstwEULTy"
crossorigin="anonymous"></script>
</body>
</html>
#settings.py
"""
Django settings for helloworld_project project.
Generated by 'django-admin startproject' using Django 3.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
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__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'z0qdn^sf&ill&gg%3myb#q)bzp$!^xnn-3(1po+blyjt1(bxyv'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
#local
'users.apps.UsersConfig',
'pages.apps.PagesConfig',
'articles.apps.ArticlesConfig',
#'blog.apps.BlogConfig',
#'accounts.apps.AccountsConfig',
#'posts.apps.PostsConfig',
#'page.apps.PageConfig',
# 3rd Party
'crispy_forms',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
TIME_ZONE = 'Africa/Lagos'
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 = 'helloworld_project.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 = 'helloworld_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/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/3.0/howto/static-files/
STATIC_URL = '/static/'
AUTH_USER_MODEL = 'users.CustomUser'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
'''EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = 'my_sendgrid_password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
#ACCOUNT_EMAIL_VERIFICATION = 'none'
'''
#views.py
from django.urls import reverse_lazy
from django.views.generic import CreateView
from .forms import CustomUserCreationForm
# Create your views here.
class SignUpView(CreateView):
form_class = CustomUserCreationForm
success_url = reverse_lazy('login')
template_name = 'signup.html
The login ,logout, etc are in templates/registration/
#project_urls.py
"""helloworld_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('users/', include('users.urls')),
path('users/', include('django.contrib.auth.urls')),
path('', include('pages.urls')),
#path('accounts/', include('django.contrib.auth.urls')),
#path('accounts/', include('accounts.urls')),
#path('', include('blog.urls')),
#path('', include('posts.urls')),
#path('', include('page.urls')),
#path('', include('pages.urls')),
]
And finally below is app_level url
#app_urls.py
from django.urls import path
from .views import SignUpView
urlpatterns = [
path('signup', SignUpView.as_view(), name='signup'),
]
Download the Jquery and Popper JS and put it in static folder
I once had an issue like this:
I hope my solution works for you.
The jquery library (jquery-.slim.min.js) you are using in your html file may not contain the functions necessary to create the dropdown effect use the jquery.min.js instead.
Remove this from your html file:
<script src="https://code.jquery.com/jquery-...slim.min.js" integrity="sha-qi/X+DzOrTabKJStQIAqVgRVzpbzosmXKp\ YfRvH+abtTEPijizo" crossorigin="anonymous"></script>
And Use the jquery.min below:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Connect to the internet and refresh.
P:S
You can as well download the jquery.min.js by going to this jquery, it's just about 87kb. Then copy the code and save it as jquery.min.js in your static folder and connect it in your template like this:
<script src="{% static 'jquery.min.js' %}"></script>
And you won't need internet again to use it. I think the jquery library you used is the issue.
This happened to me before.
How I solved it was simply placing Jquery, then Popper js, followed by Boostrap js --- in that order.
I discovered the dropdown feature was dependent on Popper and Jquery.
Looking at your code, I see you followed that order, but I am not sure of the way you loaded boostrap using django.
Kindly get boostrap cdn, (same place you got Popper and Jquery), restart your server, clear browser cache with SHIFT + F5 and try again.
Make sure you have internet connection.
It was an error on line 23. Semicolon was wrongly placed by me.
I am designing a website using django, following the steps of a course that I've enrolled recently. All the code & resources have been provided to me. I'm following each and every step accordingly but the layout of my website is not similar to what I'm following.
I faced similar problem when I was trying on similar project that I tried before the current one. The layout of my website is way too simple. I'm using the latest versions so i guess there maybe something that I've to include. The image is also not displaying on my website.
It would be really helpful if someone let me know what am I missing.
This is what I'm expecting:/
This is what I'm getting:(
This is my main html file:-
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- Font Awesome -->
<link rel="stylesheet" href="{% static 'css/all.css' %}">
<!-- Bootstrap -->
<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">
<!-- Custom -->
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<!-- Lightbox -->
<link rel="stylesheet" href="{% static 'css/lightbox.min.css' %}">
<title>Django Website</title>
</head>
<body>
<!--Top bar-->
{% include 'partials/_topbar.html' %}
<!--Nav bar-->
{% include 'partials/_navbar.html' %}
{% block content %}
{% endblock %}
<!--Footer-->
{% include 'partials/_footer.html' %}
<script src="{% static 'js/jquery-3.3.1.min.js' %} "></script>
<script src="{% static 'js/bootstrap.bundle.min.js' %} "></script>
<script src="{% static 'js/lightbox.min.js' %} "></script>
<script src="{% static 'js/main.js' %} "></script>
</body>
</html>
This is my settings.py:-
"""
Django settings for Django_Project project.
Generated by 'django-admin startproject' using Django 2.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
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__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'gwdbwxvan^9g5z-r$g9rf=!zeqrvu*2#^uye!ae#95my3dqp&t'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'pages.apps.PagesConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'Django_Project.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 = 'Django_Project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/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.2/howto/static-files/
STATIC_ROOT= os.path.join(BASE_DIR,'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'Django_Project/static')
]
You need to collect static files, in your terminal:
django-admin collectstatic
Also here is the official documentation how to handle static files
Unless inside the templates(html files), you did something wrong with extend layout. In that case you might find this link helpful and this
Also if you could provide the code of the HTML files that would be really helpful.
At your settings files at the end add these lines
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
I think you have done something wrong with static files and media file path.
Please check your static file path and media path.
For example you should define the following things in settings.py file
# Static files (CSS, JavaScript, Images)
import os
BASE_DIR = os.path.dirname(__file__)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Also, make sure that the static files and media folder present in the project.
You need to import your static folder in each template
{% load static %}
Then you can access your static files and put it for example in image "scr" tag.
src="{% static 'img/your_image.svg' %}"
i am trying to import my static files (css, js etc.) into my django project. But no matter what i am trying it shows me error 500.
I already read the official documentation here https://docs.djangoproject.com/en/1.9/howto/static-files/ , but i just can't see the problem :/ .
What bothers me is that the template import seems to work.
The GET requests i see in the dev console also seem to be legit e.g.:"http://127.0.0.1:8000/static/css/custom.css" where custom.css is in /project_folder/static/css/custom.css .
My folder structure:
myproject
-> static
-->css
--->custom.css
-> templates
-->base.html(where i request the static file)
-> myproject(app)
-->settings.oy
-->urls.py
-> data_handler(app)
-->static
..
Here is my settings.py:
"""
Django settings for myproject project.
Generated by 'django-admin startproject' using Django 1.9.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
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__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'rest_framework',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myproject',
'info_pages',
'data_handler',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'myproject.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 = 'myproject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/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/1.9/howto/static-files/
STATICFILES_DIRS = (
os.path.join(BASE_DIR,'static/'),
os.path.join(BASE_DIR,'data_handler/static/'),
os.path.join(BASE_DIR,'myproject/static/'),
)
STATIC_URL = '/static/'
STATIC_ROOT= os.path.join(BASE_DIR,'static/')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
the base.html where i import the static files:
{% load staticfiles %}
<!DOCTYPE html>
<head>
<meta name="generator" content=
"HTML Tidy for HTML5 (experimental) for Mac OS X https://github.com/w3c/tidy-html5/tree/c63cc39">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SMGR: Slime Mold Graph Repository</title>
<link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet">
<link href="{% static "css/sticky_footer.css" %}" rel="stylesheet">
<link href="{% static "css/custom.css" %}" rel="stylesheet">
<link href="{% static "css/expandy.css" %}" rel="stylesheet">
<link rel="shortcut icon" type="image/png" href="{% static "favicon/favicon.ico" %}"/>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
{% block content %}
{% endblock content %}
<div class="spacer-huge"/>
</body>
<footer class="footer" style="left:0px;">
<div class="container" style="margin-top:9px">
<a href="http://www.mpi-inf.mpg.de/departments/algorithms-complexity/">
<img src="{% static "images/mpilogo-inf-wide.png" %}" alt="mpi logo"></a>
<div style="float:right">
<p class="small">
Imprint
</p>
</div>
</div>
</footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script> <!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="{% static "js/bootstrap.min.js" %}">
</script>
With django 1.9 You have two ways of doing that.
As you're in DEBUG=True, it's your runserver which emulate a server, but you need to serve your statics.
So you can do :
Use django.contrib.staticfiles in your app, and set the good static dir and url (in a list).
Serve them in your root url file just like
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
When your project will be served by a real server you'll need to do this.
I am trying to run this project on local server and I get the follwoing error:
My url file is as follows:
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from . import views
urlpatterns = [
url(r'^courses/', include('courses.urls', namespace='courses')),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.hello_world, name='hello_world'),
]
urlpatterns += staticfiles_urlpatterns()
And this is the views file
from django.shortcuts import render
def hello_world(request):
return render(request, 'home.html')
This is the setting file
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '&s5%_8r2y$9%pbnph*xy*%v^a_!vc0bmbqz%(+l#pc#k7n2r)+'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'courses',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'learning_site.urls'
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',
],
},
},
]
WSGI_APPLICATION = 'learning_site.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Los_Angeles'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'assets'),
)
And this is the home.html file
{% extends "layout.html" %}
{% block title %}Well hello there!{% endblock %}
{% block content %}
<h1>Welcome!</h1>
{% endblock %}
this is the template file:
{% load static from staticfiles %}
<!doctype html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="{% static 'css/layout.css' %}">
</head>
<body>
<div class="site-container">
<nav>
Home
Courses
</nav>
{% block content %}{% endblock %}
</div>
</body>
</html>
And this is the layout.html file
{% load static from staticfiles %}
<!doctype html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="{% static 'css/layout.css' %}">
</head>
<body>
<div class="site-container">
<nav>
<!-- Home -->
Home
Courses
</nav>
{% block content %}{% endblock %}
</div>
</body>
</html>
Not able to figure out what the problem is. please help. thanks.
You're trying to reverse the url for 'views.helloworld'. But, that's not the name of the url you've defined. That's the view name. Change your urls.py file to:
url(r'^$', views.hello_world, name='hello_world'),
and then use:
Home
I think the problem might be in the urls.py file
Could you try importing the views as
from courses import views
As per Rohits' suggestions above I made the changes and it worked.
Tip: Dont comment out the changes, delete them! Quoting Rohit "Django will try to resolve the {% url %} tags before rendering the HTML page. So, even though you comment that out, it still tries to reverse the url"