Vue.js + vue.router + history mode + Django = Error - python

When I'm using publicPath: '/static/' in my webpack config, my Vue.js app runs fine on a Django Webserver (both dev and production).
However now I'm trying to use history mode. I have to change the publicPath to "/", otherwise the URL always gets a "/static/" in between the domain and actual target.
The Vue.js dev server still runs fine, however both production and development Django server give me these errors in the browser console:
Uncaught SyntaxError: Unexpected token < Resource interpreted as
Stylesheet but transferred with MIME type text/html:
"http://127.0.0.1:8000/6.01a214ce.css".
I've tried several different solutions like:
publicPath: './'
assetsPublicPath: '/static/'
inside base html (gave me an error on compilation)
How can I resolve this issue?

it was actually a framework issue.. im using Quasar..
For some reason you have to change
base: process.env.VUE_ROUTER_BASE,
to
base: "/",
in router/index.js as the default seems to take the static url when you are using Django..
maybe it helps somebody

Related

Django Media images not loading when debug=False [duplicate]

I've tried different solutions already posted by users, but they didn't work for me.
settings.py of Project
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = False
ALLOWED_HOSTS = ["*"]
STATIC_URL = '/static/'
STATICFILES_DIRS=[
os.path.join(BASE_DIR,'static')
]
STATIC_ROOT=os.path.join(BASE_DIR,'assets')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
All my CSS files are in style folder inside the static folder.
And all images are in the media folder.
Browser Consol Logs
Refused to apply style from 'http://127.0.0.1:8000/static/styles/LandingPage_CSS.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
icons8-user-48.png:1
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Doorakart%20icon.png:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error)
apple.jpg:1
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
banana.jpg:1
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
watermelon.jpg:1
.
.
.
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Refused to apply style from 'http://127.0.0.1:8000/static/styles/LandingPage_CSS.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Example of HTML file
{% load static %}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title></title>
<link rel="stylesheet" href="{% static 'styles/LandingPage_CSS.css' %}">
</head>
...
# IMAGES ARE LOADED LIKE THIS
<img src="media/{{item.itemImage}}" alt="img" class=" card-img-top">
...
Also, I want to disable DEBUG because I want to make my custom 404 Error page.
404 page will also contain static Image and CSS, is it possible? Please help me with that too.
This is expected behavior. Django does not serve static files or media files in production. You should configure nginx, etc. to serve files.
As is specified in the Static file development view section of the documentation:
This view will only work if DEBUG is True.
That’s because this view is grossly inefficient and probably
insecure. This is only intended for local development, and should
never be used in production.
Normally you should configure nginx, apache web server to serve static files. These web servers are likely more efficient, and have more dedicated tooling for security.
Django offers some tooling to help you set up static files, for example with the collectstatic command [Django-doc] to collect static files in a single location. The documentation furthermore describes how to make a basic configuration for apache and nginx.
There is also a package whitenoise if you really want to let Django serve static files in production, but as said in the documentation:
Isn’t serving static files from Python horribly inefficient?
The short answer to this is that if you care about performance and
efficiency then you should be using WhiteNoise behind a CDN like
CloudFront. If you’re doing that then, because of the caching headers
WhiteNoise sends, the vast majority of static requests will be served
directly by the CDN without touching your application, so it really
doesn’t make much difference how efficient WhiteNoise is.
That said, WhiteNoise is pretty efficient. Because it only has to
serve a fixed set of files it does all the work of finding files and
determining the correct headers upfront on initialization. Requests
can then be served with little more than a dictionary lookup to find
the appropriate response. Also, when used with gunicorn (and most
other WSGI servers) the actual business of pushing the file down the
network interface is handled by the kernel’s very efficient sendfile
syscall, not by Python.
I had the same issue and you should update your nginx or any another serve configuration. Just add your media and static path like below.
location /media/ {
root /path/to/your/project;
}
location /static/ {
root /path/to/your/project;
}
Project path means where your media and static directories are located. Wish this helps you.

Django uwsgi using css file http1.1 404

I just put my Django application online using uwsgi. I can access it from any computer it working well.. the only thing is uwsgi can't load the css file stored in the /static/myapp/style.css path and I don't why.
The message I get when accessing a page on my site in the uwsgi console is :
GET /static/myapp/style.css => generated 98 bytes in 1msecs (HTTP/1.1 404) 3 header in 100bytes
But the file is actually in /static/myapp/style.css I can see it and it was working well in developpement, but now the website is in production it's not working anymore.
I added these to my settings.py but nothing changed :
STATIC_URL = '/static/' #Was enough in developpement
STATICFILES_FINDERS = (
"django.contrib.staticfiles.finders.FileSystemFinder",
)
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = ("/home/user/Django/mysite/static"),
I also tried to add option in my uwsgi command like
--check-static /home/user/Django/mysite/static
Still not working...
I'm quite new to putting online a Django app so maybe it's not supposed to work like that.
My css file is on the same machine as my Django project.
I'm using django 1.11 and uwsgi 2.5.15.
I also tried to used nginx but I couldn't get it work properly and as I just want to access my app online I concluded that uwsgi alone is enough ( Am I wrong ? )
So if you have any idea that would be great !
Best regards
Gozu09

Issues with 'django.contrib.staticfiles',

I have a website that works fine on my 'production server' with the url being something akin to:
https://mymain.site.com
I have had my sys admins build a site out for development and that url is:
https://mymain.site.com/development
It is a different IP address, but I believe the URL is wrecking havoc on django routing. Mostly I notice it in the static section of it.
If I goto the development server settings and change the static url to:
/development/static/
instead of /static/ like it was on production
None of my static files are found. Since the development server is a VM copy the root on the server for static files is the same. So if I run with the /development/static as the dev url it fails to load resources. If I run on my development server with the url being /static/ I am 90% sure it is grabbing the static files from the production server (at a different ip/url). Not totally sure what the fix is here? I am loking for any kind of ideas.
I suspect if the url of my development server was something more akin to:
https://mymain.site.for.development/
then this would work right out of the box from the code copied from the VM just repointing a few things.
So what am I missing to get this to work with the right static files?
I use a CDN for my static file hosting and this is how I have my settings.py file setup:
STATIC_HOST = 'https://cdn.host.com' if not DEBUG else ''
STATIC_URL = STATIC_HOST + '/static/'
When I'm developing I'll set DEBUG = True and everything works as expected. I would imagine you would have to do something like this:
STATIC_HOST = 'https://mymain.site.com' if not DEBUG else 'https://mymain.site.com/development'
STATIC_URL = STATIC_HOST + '/static/'
See if something like that would work.

Restricting access to private file downloads in Django

I have multiple FileFields in my django app, which can belong to different users.
I am looking for a good way to restrict access to files for user who aren't the owner of the file.
What is the best way to achieve this? Any ideas?
Unfortuanately #Mikko's solution cannot actually work on a production environment since django is not designed to serve files. In a production environment files need to be served by your HTTP server (e.g apache, nginx etc) and not by your application/django server (e.g uwsgi, gunicorn, mod_wsgi etc).
That's why restricting file acccess is not very easy: You need a way for your HTTP server to ask the application server if it is ok to serve a file to a specific user requesting it. As you can understand thiss requires modification to both your application and your http server.
The best solution to the above problem is django-sendfile (https://github.com/johnsensible/django-sendfile) which uses the X-SendFile mechanism to implement the above. I'm copying from the project's description:
This is a wrapper around web-server specific methods for sending files to web clients. This is useful when Django needs to check permissions associated files, but does not want to serve the actual bytes of the file itself. i.e. as serving large files is not what Django is made for.
To understand more about the senfile mechanism, please read this answer: Django - Understanding X-Sendfile
2018 Update: Please notice that django-sendfile does not seem to be maintained anymore; probably it should still be working however if you want a more modern package with similar functionality take a look at https://github.com/edoburu/django-private-storage as commenter #surfer190 proposes. Especially make sure that you implement the "Optimizing large file transfers" section; you actuallyu need this for all transfers not only for large files.
2021 Update: I'm returning to this answer to point out that although it hasn't been updated for like 4 years, the django-sendfile project still works great with the current Django version (3.2) and I'm actually using it for all my projects that require that particular functionality! There is also an actively-maintained fork now, django-sendfile2, which has improved Python 3 support and more extensive documentation.
If you need just moderate security, my approach would be the following:
1) When the user uploads the file, generate a hard to guess path for it. For example you can create a folder with a randomly generated name for each uploaded file in your /static folder. You can do this pretty simply using this sample code:
file_path = "/static/" + os.urandom(32).encode('hex') + "/" + file_name
In this way it will be very hard to guess where other users' files are stored.
2) In the database link the owner to the file. An example schema can be:
uploads(id, user_id, file_path)
3) Use a property for your FileFields in the model to restrict access to the file, in this way:
class YourModel(models.Model)
_secret_file = models.FileField()
def get_secret_file(self):
# check in db if the user owns the file
if True:
return self._secret_file
elif:
return None # or something meaningful depanding on your app
secret_file = property(get_secret_file)
This is best handled by the server, e.g. nginx secure link module (nginx must be compiled with --with-http_secure_link_module)
Example from the documentation:
location /some-url/ {
secure_link $arg_md5,$arg_expires;
secure_link_md5 "$secure_link_expires$uri$remote_addr some-secret";
if ($secure_link = "") {
return 403;
}
if ($secure_link = "0") {
return 410;
}
if ($secure_link = "1") {
// authorised...
}
}
The file would be accessed like:
/some-url/some-file?md5=_e4Nc3iduzkWRm01TBBNYw&expires=2147483647
(This would be both time-limited and bound to the user at that IP address).
Generating the token to pass to the user would use something like:
echo -n 'timestamp/some-url/some-file127.0.0.1 some-secret' | \
openssl md5 -binary | openssl base64 | tr +/ -_ | tr -d =
Generally, you do not route private files through normal static file serving directly through Apache, Nginx or whatever web server you are using. Instead write a custom Django view which handles the permission checking and then returns the file as streaming download.
Make sure files are in a special private folder folder and not exposed through Django's MEDIA_URL or STATIC_URL
Write a view which will
Check that the user has access to the file in your view logic
Open the file with Python's open()
Return HTTP response which gets the file's handle as the parameter http.HttpResponse(_file, content_type="text/plain")
For example see download() here.
For those who use Nginx as a webserver to serve the file, the 'X-Accel-Redirect' is a good choice.
At the first, request for access to the file comes to Django and after authentication and authorization, it redirects internally to Nginx with 'X-Accel-Redirect'. more about this header: X-Accel-Redirect
The request comes to Django and will be checked like below:
if user_has_right_permission
response = HttpResponse()
# Let nginx guess to correct file mime-type by setting
# below header empty. otherwise all the files served as
# plain text
response['Content-Type'] = ''
response['X-Accel-Redirect'] = path_to_file
return response
else:
raise PermissionDenied()
If the user has the right permission, it redirects to Nginx to serve the file.
The Nginx config is like this:
server {
listen 81;
listen [::]:81;
...
location /media/ {
internal; can be accessed only internally
alias /app/media/;
}
...
}
Note: The thing about the path_to_file is that it should be started with "/media/" to serve by Nginx (is clear though)

Serving different urlconfs in a single Django project

My question is about how to serve multiple urls.py (like urls1.py, urls2.py and so on) files in a single Django project.
I am using Win7 x64, django 1.4.1, python 2.7.3 and as a server django dev-server tool.
I have decided to use a method which i found by google from
http://effbot.org/zone/django-multihost.htm
I have created a multihost.py file and put in to the django middleware folder:
C:\python27\Lib\site-packages\django\middleware\multihost.py
With the following code:
from django.conf import settings
from django.utils.cache import patch_vary_headers
class MultiHostMiddleware:
def process_request(self, request):
try:
host = request.META["HTTP_HOST"]
if host[-3:] == ":80":
host = host[:-3] # ignore default port number, if present
request.urlconf = settings.HOST_MIDDLEWARE_URLCONF_MAP[host]
except KeyError:
pass # use default urlconf (settings.ROOT_URLCONF)
def process_response(self, request, response):
if getattr(request, "urlconf", None):
patch_vary_headers(response, ('Host',))
return response
Also in my project setting.py file i have added a mapping dictionary like the link above shows:
# File: settings.py
HOST_MIDDLEWARE_URLCONF_MAP = {
"mysite1.com": "urls1",
#"mysite2.com": "urls2"
}
I did not yet implemented the error handling like described by the link above.
My hosts file includes the follwoing:
127.0.0.1 mysite1.com
Project structure is the following:
effbot django project folder:
+ effbot
--- settings.py
--- view.py
--- wsgi.py
--- urls.py
--- urls1.py
+ objex
--- models.py
--- views.py
+ static
--- css
--- images
There is no templates folder, because i dont serve html items from files, they are coming from databsse (i doubt that my problem is in this).
Now the problem is: when i go for the adress
mysite1.com
in my browser with django dev-server launched i get code 301 from the server. And browser shows "cannot display page" message.
Could you please explain me how to use mentioned method? I'm new to django and haven't done any real projects yet. Just have read the docs and launched a couple of sites at home to learn how it works.
I expect that urlconfs will be called in dependance from incoming
request.META["HTTP_HOST"]
The target is to serve different urlconfs for mysite1.com and mysite2.com
in a single django project.
I think this should to work some how.
Thank you for any feedback.
EDIT:
After some research attempts i found that i plugged my multyhost.py incorrectly in settings.
Fixed now. But the same result still.
Also i found out that my django dev-server tool is not reflecting anyhow that it handles any requests from the browser (IE9) except when i do "http://127.0.0.1".
May be i have to try some production server for my task, like nginx?
Your ROOT_URLCONF should be effbot.urls without .pyas you can see in the example in the documentation.
Also, HOST_MIDDLEWARE_URLCONF_MAP should reflect the ROOT_URLCONF so add `effbot. like this:
HOST_MIDDLEWARE_URLCONF_MAP = {
"mysite1.com": "effbot.urls1",
#"mysite2.com": "effbot.urls2"
}
One more thing, please try with another browser (Chrome, Firefox), sometimes I had problems accessing dev server with IE.

Categories

Resources