I am trying to get the CSS sheet to load on my development computer. It is in the media directory as media/base.css. In my base/base.html template, I have:
<link href="media/base.css" rel="stylesheet" type="text/css" />
I found this page, but that didn't fix it. Any ideas?
if media/ is your project media directory, then in the template use
<link href="{{ MEDIA_URL }}base.css" rel="stylesheet" type="text/css" />
this is considering you have passed RequestContext to your template,
ex:
def some_view(request):
# ...
return render_to_response('my_template.html',
my_data_dictionary,
context_instance=RequestContext(request))
You will also need to have static urls served when running on the localdev server.
Include this in your urls.py:
from django.conf import settings
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^%s(?P<path>.*)$' % settings.MEDIA_URL[1:],
'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True})
)
Related
I have made a ML model which I am deploying in a website using Flask. This is the code for it:
main.py
#imports
app = Flask(__name__)
def check(url):
#function to check whether the URL entered by user is Phishing or not and return the result
#app.route('/')
def home():
return render_template("home.html") #renders homepage template
#app.route('/phish/<url>')
def phish(url):
for i in range(0,len(url)):
if url[i]=="$":
url = url[:i]+"/"+url[i+1:] #changing url back to original
return render_template("phish.html", url=url)
#app.route('/safe/<url>')
def safe(url):
for i in range(0,len(url)):
if url[i]=="$":
url = url[:i]+"/"+url[i+1:] #changing url back to original
return render_template("safe.html", url=url)
#app.route('/', methods=['POST'])
def results():
url = request.form['url']
result = check(url)
for i in range(0,len(url)):
if url[i]=="/":
url = url[:i]+"$"+url[i+1:] #changing "//" to "$$"
if result==1 :
return redirect(url_for("phish", url=url))
else :
return redirect(url_for("safe", url=url))
if __name__ == '__main__':
app.run()
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<!-- bunch of meta tags -->
<title>PhishLearn</title>
<link href="{{ url_for('static', filename='css/bootstrap.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='css/main.css') }}" rel="stylesheet"> <!-- for loading
css -->
</head>
<body>
<!-- body code -->
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="static/js/bootstrap.min.js"></script>
</body>
</html>
The code for phish.html and safe.html is also exactly same except for some changes in the body part.
Now when I initially run my main.py file the home page is loaded perfectly. But when I input a URL and click submit the page that is then rendered according to the result (phish or safe) does not display any image. Here are the screenshots of the pages:
Homepage
Result Page
As you can see when safe.html is rendered it does not shows any images. Can anyone tell me why this is happening and how to solve this issue?
I just use the src attribute of img tag to specify the path of file. Since all my html resources (css, js, images, etc.) are inside the static folder so I write src = "static/img/image-name.jpg"
That's your problem (as I kind of guessed).
When the URL in your browser is /phish/foople.blarp.quux, then static/img/image-name.jpg relative to that path is /phish/foople.blarp.quux/static/img/image-name.jpg which obviously 404s.
You need to
use the {% url_for("static", filename=...) %} form so Flask will deal with forming the correct static URL,
or alternately but less preferably (since changing the static files' root path will then require you to edit every template you have) use an absolute path /static/img/image-name.jpg.
or if you feel like using esoteric and often-forgot-about HTML features, set <base> and never worry about relative paths, but really please don't do that.
UPDATE: This solved. I didn't write the correct CSS!
I am trying to render a few things in HTML. Multiple things are causing problems but I've included the most basic part I want to get working. If I can get this to work, I can get the rest to work.
Very simple app structure:
app
api.py
static
styles.css
templates
index.html
This is the contents of index.html:
<html>
<h1>
Title here
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="{{ url_for('static', path='/styles.css') }}" rel="stylesheet">
</h1>
</html>
This the the CSS I'm using:
h1 {
color: red
text-align: center
}
Relevant code in api.py:
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
app = FastAPI()
templates = Jinja2Templates(directory="templates")
app.mount("/static", StaticFiles(directory="static"), name="static")
#app.get("/", response_class=HTMLResponse)
def read_mean_cpu(request: Request, device_id):
return templates.TemplateResponse("index.html", {"request": request}))
Any idea why the CSS isn't taking?
I use django1.10
i reference the official doc
https://docs.djangoproject.com/en/1.10/intro/tutorial06/
my project name:mysite
structure:
mysite-
- mysite - urls.py
-views.py
...
- templates - index.html
- images
- static - mysite - assets - css - main.css
- js
...
In my index.html
add
{% load staticfiles % }
<link rel="stylesheet" text = 'html/css' href="{% static 'mysite/static/main.css' %}" />
it said i have a Invalid block tag about TemplateSyntaxError
<link rel="stylesheet" type = 'text/css' href="{% static 'mysite/static/assets/css/main.css' %}" />
views.py (about static files part)
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
'/mysite/static/',
]
STATIC_URL = '/static/'
STATIC_ROOT='/mysite/static/'
what's part should i notice?
Hi dear try to make python manage.py collectstatic...
hope it solves your problem 😊
I'm not sure why my favicon won't be shown. I followed the exact code other people use to show favicon, not anything special.
so my guess why this won't work is; location of image is wrong. or the size, type of image is wrong. or maybe because I'm still in local.
This is my folder structure and what I tried
----project
------------project
-------------------project
--------------------------settings
----------------------------------settings.py
-------------------template
---------------------------base.html
-------------------static
--------------------------image
--------------------------------logo.png
--------------------------css
---------------------------js
------------gitignore
------------env
-------------static
In my django setting
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "media")
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
so here are my attempts,
<link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/>
<link rel="shortcut icon" type="image/png" href="{{static_url/favicon.png}}">
<link rel="shortcut icon" type="image/png" href="project/project/static/image/logo.png">
<link rel="shortcut icon" type="image/png" href="project/static/image/logo.png">
Edit
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^accounts/', include('userena.urls')),
url(r'^', include('main.urls')),
]
if settings.DEBUG:
urlpatterns += patterns('',) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += patterns('',) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I have aws like this
AWS_FILE_EXPIRE = 200
AWS_PRELOAD_METADATA = True
AWS_QUERYSTRING_AUTH = True
DEFAULT_FILE_STORAGE = 'project.utils.MediaRootS3BotoStorage'
STATICFILES_STORAGE = 'project.utils.StaticRootS3BotoStorage'
AWS_STORAGE_BUCKET_NAME = 'realproject'
S3DIRECT_REGION = 'ap-northeast-2'
S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME
MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME
MEDIA_ROOT = MEDIA_URL
STATIC_URL = S3_URL + 'static/'
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'
import datetime
date_two_months_later = datetime.date.today() + datetime.timedelta(2 * 365 / 12)
expires = date_two_months_later.strftime("%A, %d %B %Y 20:00:00 GMT")
AWS_HEADERS = {
'Expires': expires,
'Cache-Control': 'max-age=86400',
}
Is this blocking my static setting maybe?in production and in local, css and javascript works. and I can post image through admin. but only not in static way(I drag photo to the folder and trying to display that image)
You should display fav icon with the following tag:
<link rel="icon" href="demo_icon.png" type="image/png">
the rel attribute must be equal to "icon" in order to work.
Make sure that your icon size is 16x16 or 32x32 and if it is still not working then a suggest that you should run "./manage.py runserver" and check the output to find the error
according to your setting, the file path should be '/project/static/image/logo.png' instead of '/project/project/static/image/logo.png'
and in the template it should be {static '/image/logo.png'}
don't forget to load static in the template first
It's not because of local project. You can see favicon even if your project is not live/ not hosted.
I think you have added wrong link type.
It should be "img/ico"
Try with this code:
<link rel="shortcut icon" href="images/favicon.ico" type="img/ico"/>
Add your image path in href.
This is a bit embarrassing, but I don't know how to solve this problem:
First off, my project directory looks like this (there are more directories, but we aren't concerned with them):
projectfolder/
wsgi/
openshift/
templates/
home/
simple-sidebar.html
static/
css/
fonts/
js/
And the file we are concerned with is simple-sidebar.html which looks like the following :
{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<title>Starter Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link href= "{% static "css/bootstrap.css" %}" rel="stylesheet">
<!-- Add custom CSS here -->
<link href="{% static "css/simple-sidebar.css" %}" rel="stylesheet">
<link href="{% static "font-awesome/css/font-awesome.min.css" %}" rel="stylesheet">
</head>
Now for some reason my static template tags are not working, but that's probably because I don't know how to set up my static template stuff in my settings.py:
STATIC_ROOT = os.path.join(PROJECT_DIR, '..', 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = () <--- dont know if I need this one?
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
PS: Also how would you do this without the {% static %} tag? I am not sure how my style sheets href would look like.
Try removing the dots from your STATIC_ROOT, for example
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
STATICFILES_DIRS are there for you if you'd like to map additional folders to your application that can be anywhere on your machine. When you run ./manage.py collectstatic you're essentially asking python to find all the files within said directories and drop them into the static folder defined in STATIC_ROOT
If you would like to map your files manually (without the static tag) you'd have to write out the full path of your file, for example /some/directory/path/css/style.css.
Lastly if you're running with DEBUG = True you are required to add your static and media urls to urls.py so there is an actual path in place. For example
from django.conf import settings
# ... your normal urlpatterns here
if settings.DEBUG:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}),
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.STATIC_ROOT}))