How to get the link of the file in a FileField? - django

how can I get the link of a FileField? I tried the url field, but it gives the file path:
In [7]: myobject.myfilefield.path
Out[7]: u'/home/xxxx/media/files/reference/1342188147.zip'
In [8]: myobject.myfilefield.url
Out[8]: u'/home/xxxx/media/files/reference/1342188147.zip'
I was expecting to get http://<mydomain>/media/files/reference/1342188147.zip
How can I get that? Do I have to build the string manually?
EDIT
My MEDIA_URL was not set, but I still can't get it to work:
settings.py
MEDIA_ROOT = '/home/xxx/media/'
MEDIA_URL = 'http://xxx.com/media/'
models.py
class Archive(models.Model):
#...
file = models.FileField(upload_to="files")
in shell
a = Archive()
a.file = "/some/path/to/file.txt"
a.save()
Then I get for a.path:
"/some/path/to/file.txt"
and for a.url:
"http://xxx.com/media/some/path/to/file.txt"
When done programmatically, a.file = "/some/path/to/file.txt", the file is not uploaded to MEDIA_ROOT. How can I upload a file in the directory defined by upload_to, i.e. in my case /home/xxx/media/file.txt?

The output is based on your settings file, have a look here for an understanding on serving staticfiles in development and/or production:
Confusion in Django admin, static and media files

I'm guessing you have the field defined as:
picture = models.ImageField(upload_to="/home/xxx/media/files/reference")
in other words is it possible you have defined an absolute path for the upload_path property of the field ?
Try something like
from django.conf import settings
picture = models.ImageField(upload_to=settings.MEDIA_ROOT + "files/reference")

Related

Accessing .csv data from views file

I have a small Django app, and I'm trying to access data from a CSV file (static/blog/dat.csv, the static folder is at the same level as the templates folder and views.py; and everything is inside my blog app) so I can use it to plot a graph on the browser using Chart.js. Aside from not being able to do that, the app is working fine.
I know I'm gonna need to pass some sort of context to the view function, but I don't know how I'd do that. Also, I have a couple of similar csv files, and using them as static files in my app seems simpler and easier than to add everything to a database to access them that way.
# views.py
from django.shortcuts import render
from django.contrib.staticfiles.storage import staticfiles_storage
import csv
def rtest(request):
url = staticfiles_storage.url('blog/dat.csv')
with open(url, 'r') as csv_file:
csv_reader = csv.reader(csv_file)
for line in csv_reader:
context += line
return render(request, 'blog/r.html', context)
# urls.py
urlpatterns = [
# ...
path('r-test/', views.rtest, name='blog-r-test'),
]
Here is the error I'm getting:
FileNotFoundError at /r-test/
[Errno 2] No such file or directory: '/static/blog/dat.csv'
I'm sure this is not the only error.
I know that the way I'm using the context variable is wrong, but that's just to kind of show what I'm trying to do. If I could just print one cell from the csv, I would view this as a win. Please help, thank you!
------Edit1-------
After using staticfiles_storage.path() instead of staticfiles_storage.url()
ImproperlyConfigured at /r-test/
You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path.
------Edit2------
I'm now able to find my csv file:
STATIC_URL = '/static/'
STATIC_ROOT = 'C:/Users/riccl/Documents/richie/Python/nuclear/main/book/static/book'
But my context variable still doesn't make any sense.
You need to use staticfiles_storage.path() to read the file. staticfiles_storage.url() will return the URL that a user will use to load the static file on your site
STATIC_ROOT is where all static files will be stored after you run collectstatic, most of the time this is set to <root of the project>/static/. This is also where staticfiles_storage.path() will look for static files.
You will also need to set STATICFILES_DIRS so that your file(s) can be found by collectstatic. I usually have a folder located at <root of the project>/<project name>/static/ which I add to STATICFILES_DIRS

Incorrect URL to file in Django admin

I'm getting the wrong URL to files that have been uploaded to the media-folder in the Django admin.
The URL for the file is:
/media/Users/hammer/Dev/*****/media/attachments/2018/09/12/pdf-test.pdf
But the correct URL to the file is:
/media/attachments/2018/09/12/pdf-test.pdf
It seems like MEDIA_ROOT (/Users/hammer/Dev/*****/media/) is (incorrectly, I guess) added after the first /media/ in the URL.
MEDIA_URL is:
MEDIA_URL = '/media/'
MEDIA_ROOT is:
MEDIA_ROOT = settings.BASE_DIR + '/media/'
The definition of the file-field for the model is:
file = models.FileField(upload_to=settings.MEDIA_ROOT + "attachments/%Y/%m/%d/", null=True)
The incorrect URL for the file-field is appearing on the change-page for the model for the file field.
Any ideas on how to fix this?
You shouldn't include MEDIA_ROOT specifically in your upload_to parameter. See the documentation:
If you are using the default FileSystemStorage, the string value will be appended to your MEDIA_ROOT path to form the location on the local filesystem where uploaded files will be stored.
So, just remove that:
file = models.FileField(upload_to="attachments/%Y/%m/%d/", null=True)
You'll need to recreate the instances with the incorrect value in the db, though.

How to display images from an ImageField in Django?

Before I explain, I have a question. I am making a blog and the posts have a heading image. I upload this image using admin when I create a post for my blog. Is this image 'static' or 'media'?
Anyway, I have my project set up as follows:
mysite is my project, blog is my app. I have a folder named static inside blog. Inside this static folder are four more folders- css, images, fonts, js.
In settings.py, I have this set up:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
My models.py looks like this:
class Post(models.Model):
...
header_image = models.ImageField('article_header_image', upload_to = 'blog/static/images/articleimages')
Now when I try to load this image in a template, it doesn't show up.
I am doing this the following way:
{% for post in posts %}
<img src="{{post.header_image.url}}">
{% endfor %}
Another thing, how can I use the upload_to argument to upload images into the app's static folder without explicitly stating it? I think thats where the issue is. If I use upload_to = 'static/images/articleimages', a new static folder is created in the mysite folder containing manage.py.
Any help is greatly appreciated!
You can import the STATIC_ROOT from settings file, and use that to biuld the path. In addition to that, you can use a callable, and build path there instead:
import os.path
from django.conf import settings
def generate_upload_path(instance, filename):
return os.path.join(settings.STATIC_ROOT, 'images/articleimages/')
class Post(models.Model):
...
header_image = models.ImageField('article_header_image', upload_to = generate_upload_path)
Ok, if you want to upload images to static directory of your app, you can use __path__ attribute of your app:
import blog
def generate_upload_path(instance, filename):
return os.path.join(blog.__path__, 'static/images/articleimages/')

Django model cannot find a static file

in my models.py I have (myfile.txt is 3gb)
with open('/static/myfile.txt', 'rb') as f:
do something..
but it complains
No such file or directory: '/static/myfile.txt'
this is my settings.py
STATIC_ROOT = 'absolute_dir_to_project/app_name/static/'
STATIC_URL = '/static/'
Did I miss any step?
you should prepend the absolute path with SETTINGS's STATIC_URL so that it looks for myfile.txt inside Django:
from django.conf import settings # dont forget to import this guy
with open(settings.STATIC_URL + 'myfile.txt', 'rb') as f:
do something..
The open function is trying to open a file from disk with the path /static/myfile.txt, rather than requesting a file through your Django web app. It doesn't sound like you need to have this file in your static files folder, especially if it's huge and isn't intended for public consumption

Django FileField url not relative

I have something like:
MEDIA_ROOT = '/home/httpd/foo/media/'
MEDIA_URL = 'http://www.example.org/media/'
(...)
file = models.FileField(upload_to='test')
When I create an object with that field in the admin page Django stores in the DB the full file path, like: "/home/httpd/foo/media/test/myfile.pdf". This is contrary to what says in the docs.
All that will be stored in your
database is a path to the file
(relative to MEDIA_ROOT).
When I use the file.url in a template I get something like:
http://www.example.org/home/httpd/foo/media/test/myfile.pdf
instead of what I would like:
http://www.example.org/media/test/myfile.pdf
What am I doing wrong?
I just did a sample FileField in one of my projects and it seemed to work as you are expecting. Here are a couple things to try.
Try making your settings like the following. I know they say it is bad to not end your MEDIA_URL with a / but this is how I do it and I like it better. You just have to remember whenever you use MEDIA_URL in a template to follow it with a slash: href="{{ MEDIA_URL }}/path/to/file"
MEDIA_ROOT = '/home/httpd/foo/media'
MEDIA_URL = '/media'
If that doesn't help anything, create a new simplified model with a FileField nothing customized and see if you are still getting the same problem.