Regular expressions in django url - python

My URL regular expression is r'^admin.*/static/admin/(?P<path>.*)$', now it can match admin/static/admin/css/base.css or admin/123/static/admin/js/actions.js, but I want it match url like admin/blog/post/static/static/admin/js/actions.js (now it doesn't match that)
How could i do that?
Thanks for everyone's comments.
My problem is I set up static url path in django to store my css/js file,like this url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT,}),
settings.STATIC_ROOT is os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static')
But when I access admin interface, all css/js files are missing. because admin css file store in django\contrib\admin\static\admin and its url in html file is 'static/admin/css/base.css'. there is no this file in my static path I set in settings.
My solution is set another url like r'^admin.*/static/admin/(?P<path>.*)$', and set document root to django admin static file path. but just as i mentioned, when i go admin main page, everything is ok, my when i go deep like "add User" page, css file is still missing.
I also found a solution is change my url regular to r'.*/static/admin/(?P<path>.*)$', that's fine for everything, but is there any better solution?
After I run collectstatic,in my static path, i can found admin folder and its css/js files. then i set my url path to url(r'^admin/static/(?P.*)$','django.views.static.serve',{'document_root'‌​:settings.STATIC_ROOT}), ,it works for main admin page, but when i access http://localhost/admin/sites/site/static/static/admin/js/admin/RelatedObje‌​ctLookups.js it still doesn't work, how could I write my url path?

The pattern matches just fine:
>>> import re
>>> p = re.compile(r'^admin.*/static/admin/(?P<path>.*)$')
>>> p.match("admin/blog/post/static/static/admin/js/actions.js").groups()
('js/actions.js',)
so not clear why it didn't work for you. Have you double-checked that the problematic URL doesn't match some other, earlier regexp?
EDIT: Based on updates above, it may be that STATIC_URL isn't properly set (an empty string, perhaps?). It should point to where the static files are served from (URL, not directory) and must end with a slash. See Settings: STATIC_URL.
(And as a footnote, you should be a bit careful with having your URL regexps do too much; you're not there yet with this one, but Wikipedia's ReDoS article is good to read before you go beyond what you're doing here.)

Related

How To Render An HTML With Css + JavaScript File In Django

Hay,
I Have An HTML with Css + JavaScript Page When I Try Rendring This Page In Django Like This:
def about(request):
return render(request, 'about/index.html')
but I Only Get The Html Content Without The Css And JavaScript.
I Thought This Might Be Because Of The Statics.. So I Run:
python manage.py collectstatic
But I Get This:
0 static files copied to 'C:\Users\Ammar\Desktop\Python Learning\vidly\static', 128 unmodified.
What Should I Do,
I Wish Someone Can Help.
Django has a feature of managing a good directory structures
i.e. project->apps->templates/views/urls
In a Django project all static files example images,css files,(designing part) is stored in a directory named static.
This helps in leveraging the same static properties over several apps and keeping the code structure clean.
The collect static command helps to get all static files present in the project to a static folder and we need to mention the static path in settings.py file .
Django documentation might clear your doubts further I am putting link here that might help you .
https://docs.djangoproject.com/en/3.2/howto/static-files/
What's the point of Django's collectstatic?

Django server side caching of uploaded file

I am running a server in django and I want to serve a file. I am storing the file under '/upload/directory/filename' and I return it using
from django.shortcuts import redirect
file_path = '/upload/directory/filename'
return redirect(file_path)
However, the file appears to have been cached to the first version that had been placed locally and is never updated. Even if I remove the file, the file is still served. I checked that if I change the path to 'upload/directory_2/filename then I correctly get my new file. What is going on and how can I fight this ?
This is happening locally and I am making a direct server request (hence there is no possibility of browser caching or anything else).
Additional information:
I understand that maybe I should be using static files, although for instance this answer suggests that it is quite debatable for files that I am uploading myself.
When I say "I want to serve files with django" I just mean that I have associated a file path to a particular entity in my database (using models.FileField) and based on what the user requests I want to return this file. I kind of doubt this is a clear cut for using static files in that case.
There are many workarounds to my issue, like generating unique filenames every time I want to "clear my cache" or explicitly opening the file:
with open(absolute_file_path) as file:
response = HttpResponse(file.read(), content_type='application/octet-stream')
My question was about understanding why the particular piece of code above does what it does, i.e. leads to data caching, and how to prevent this.
If you must do this using Django itself, I would suggest skipping the redirect and setting up your app according to these directions:
https://docs.djangoproject.com/en/1.11/howto/static-files/#serving-files-uploaded-by-a-user-during-development
Make your MEDIA_URL something like /media/ or if you want it to match your current case /upload/ or something. MEDIA_ROOT could point to os.path.join(BASE_DIR, 'upload') and your FileField(upload_to='directory').
You must use django static facility to serve static files. On your local machine this is setup properly in settings to point a folder static in your app then you can point to the file using the static function.
All is explained here:
https://docs.djangoproject.com/en/1.11/howto/static-files/
In an url you access the code:
from django.templatetags.static import static
url_to_file = static('some_app/path/to_file')
On a production machine the static files are served by a web server or a specific service like aws S3 or similar but not from django! For this reason the static facility is a must.
To avoid the cache, in case you have this problem, have a look at the never_cache decorator: https://docs.djangoproject.com/en/1.11/topics/http/decorators/#caching
There is a special HttpResponse in Django that can help you to serve a file easily.
def file_dowload(request):
file_name = request.GET.get('file_name', '')
try:
temp = open(file_name, 'rb')
except IOError:
temp = None
if not temp:
return HttpResponse("Not found")
response = FileResponse(temp, content_type='text/plain')
return response

Django: static files vs. other data files

If I want to display images in a template, the path I specify is relative to the static folder in my app directory. But if I want to load a file from a view function, then the path I specify seems to be relative to the project directory. Should these files all be in the same directory? Or is it typical to separate them out in this way? Is a file loaded by a view function (such as a text file containing human-readable settings) considered to be "static" in the same sense as image, css and js files for rendering my template?
Django supports two different things: static and media files. Static files (CSS, JavaScript, Images) are the files that are part of your website. User uploaded content like images or videos are uploaded to MEDIA_ROOT. You can use these two settings to control this:
MEDIA_ROOT = '/absolute/path/to/media'
MEDIA_URL = '/media/'
Using dev server, you might need to add this to your URLs,
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Using file upload fields (FileField, ImageField), you can get the file url using url property which will include the defined MEDIA_URL.
No, you should not mix up true static content with package data files. Among other things, you generally don’t want users to be able to read those data files directly. Instead, place your files somewhere else within your package’s directory, then use pkgutil.get_data to read them.

I'm using django framework. i'm stuck up with how to show image on my home page

I'm new to django framework .I just want to show simple image on my home page (localhost:8000). I'm getting confused how to use models.py, views.py and urls.py. Can you help me to show just simple image file.
Thank you.
If you just want to display static image, django docs for managing static files and django.contrib.staticfiles may help.
You can
edit your project's settings.py and add appropriate static files settings
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = '/path/to/static/root/directory'
# URL prefix for static files.
STATIC_URL = '/your_static_url_prefix/'
STATICFILES_DIRS = (
'/path/to/your/static/directory',
)
put your image somewhere under you STATICFILES directory, example at
'/path/to/your/static/directory/images/theimage.png'
Display the image from your home page template, example by
<img src="{{STATIC_URL}}images/theimage.png"/>
You can also read tutorials from the official django documentation to know the basics on how models,views,urls and templates work.
I think you should read something about it. There are some good tutorials in the net. First of all check django book, you can also watch this video tutorial

can't figure out serving static images in django dev environment

I've read the article (and few others on the subject), but still can't figure out how to show an image unless a link to a file existing on a web-service is hard-coded into the html template.
I've got in urls.py:
...
(r'^galleries/(landscapes)/(?P<path>.jpg)$',
'django.views.static.serve', {'document_root': settings.MEDIA_URL}),
...
where 'landscapes' is one of the albums I'm trying to show images from. (There are several more of them.)
In views.py it calls the template with code like that:
...
<li><img src=160.jpg alt='' title='' /></li>
...
which resolves the image link in html into:
http://127.0.0.1:8000/galleries/landscapes/160.jpg
In settings.py I have:
MEDIA_ROOT = 'C:/siteURL/galleries/'
MEDIA_URL = 'http://some-good-URL/galleries/'
In file system there is a file C:/siteURL/galleries/landscapes/160.jpg and I do have the same file at http://some-good-URL/galleries/landscapes/160.jpg
No matter what I use in urls.py — MEDIA_ROOT or MEDIA_URL (with expectation to have either local images served or from the web-server) — I get following in the source code in the browser:
<li><img src=160.jpg /></li>
There is no image shown in the browser.
What am I doing wrong?
This is a long post, basically summarizing all the things I learned about Django in order to get static files to work (it took me a while to understand how all the different parts fit together).
To serve static images in your development server (and later, your real server), you're going to have to do a few things (note specifically the third and fourth steps):
Set MEDIA_ROOT
MEDIA_ROOT is a constant which tells Django the physical path of the file (on your filesystem). Using your example, MEDIA_ROOT needs to be set to 'C:/siteURL/galleries/', like you wrote. MEDIA_ROOT is going to be used in one of the following steps, which is why we set it.
Set MEDIA_URL
MEDIA_URL is the "url" at which your images sit. In other words, whenever you want to get an image, the url to look for starts with MEDIA_URL. Usually this is not going to start with "http", since you're serving from your own server (my MEDIA_URL is usually set to '/site_media/', meaning to start from the root domain, then go to site_media etc.)
Use MEDIA_URL
MEDIA_URL doesn't work by magic, you actually have to use it. For example, when you're writing the HTML which gets a file, it needs to look like this:
<li><img src="{{MEDIA_URL}}/160.jpg" /></li>
See how I'm telling the template to use the MEDIA_URL prefix? That eventually translates to 'http://some-good-URL/galleries/160.jpg'.
Note that to be able to actually use the MEDIA_URL in your templates, you're going to have to add the line 'django.core.context_processors.media' to your TEMPLATE_CONTEXT_PROCESSORS setting in your settings.py file, if I'm not mistaken.
Make your dev server serve static files
In a real environment, you will configure files with addresses like "static_media" to be served without going through Django. But in a dev environment, you'll want to server them from Django as well, so you should add this generic line to the end of your urls.py file:
if settings.DEBUG:
# Serve static files in debug.
urlpatterns += patterns('',
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT,
'show_indexes' : True}),
)
Note how that takes anything with the url "site_media/*" (which is actually my MEDIA_URL) and serves it from my MEDIA_ROOT folder, which is the place where the MEDIA_ROOT setting comes into play.
Final note
What confused me is that a lot of the things here are for convenience. For example, MEDIA_ROOT is only used in your debug url pattern, to tell Django where to load from. And MEDIA_URL is only there to encourage you not to put in absolute URLs in all your HTML files, because then when you decide to move the files to a different server, you'd have to manually change them all (instead of just changing the MEDIA_URL constant).
Of course, none of this is necessary: you can hard-code the debug url patter with your own folder, make sure that the static files really are being server from the url (by visiting it in your browser), and then hand-code that without using the MEDIA_URL setting into the HTML file, just to make sure things work.
This looks buggy...:
r'^galleries/(landscapes)/(?P<path>.jpg)$'
this RE will only match image names with a single character begore the jpg suffix, not four (as in, e.g., '160.jpg'). Maybe you meant...
r'^galleries/(landscapes)/(?P<path>.*jpg)$'
...?
Take this as a cross between the two previous answers, both of which are good. First, your regex is incorrect as Alex pointed out. I would suggest setting it as:
(r'^local_media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}), # static content
Because you're probably going to want to server css and js files too, not just images. This regex takes care of any and every static file you might want to serve.
Next, you'll want to specify the MEDIA_URL for your img tags. You currently have:
<img src=160.jpg />
Instead, it needs to be something like:
<img src=[YOUR MEDIA_URL]160.jpg />
The trick I use is easy. At the top of my views.py, I have the following code:
from django.conf import settings
resp = {}
resp['MEDIA_URL'] = settings.MEDIA_URL
and then I just pass the resp dictionary to every template I render. Now I can write those same img tags as:
<img src={{MEDIA_URL}}160.jpg />
Best of all, this part of your code can be used in production as well (not the regexes, just the MEDIA_URL bit).

Categories

Resources