New to Django and web development in general. But I have followed a tutorial for creating my first site. Everything worked fine, until I finished it and wanted to edit the info using the Django admin panel.
The main issue is that I have a model shown below that uses FilePathField to describe the image locations. The tutorial had me place the images in /home/pi/mysite/projects/static/img.
from django.db import models
class Project(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
technology = models.CharField(max_length=20)
image = models.FilePathField('/img')
def __str__(self):
return self.title #or self.title for blog posts
This worked fine at first for displaying the images on the website, but once I tried to navigate to the /change/ url from the admin panel, I would get FileNotFoundError at /admin/projects/project/1/change/ [Errno 2] No such file or directory: '/img'
So I looked around and found that FilePathField is an absolute path, so tried defining it absolutely with /home/pi/mysite/projects/static/img/. This stopped the error from occurring which let me at least access the /change/ url from the admin panel. The panel now showed the image field with a dropdown that I could use to choose between the different images I had up there, which were located at /home/pi/mysite/projects/static/img/. But from the admin panel, once I hit save, the images would no longer show up on the site. Upon using inspect element on the website, it seems it was trying to pull the images from /static/projects/static/img. I then tried to move the images to /static/projects/static/img but then they no longer showed up in the dropdown box from the admin panel, and also weren't displaying on the website.
So at this point I am just a bit confused where I should be pointing FilePathField too that will allow me to display the images on the website and also change them through the admin panel.
A much better approach is to use django's FileField like so:
image = models.FileField(null=True, blank=True)
In your settings.py you need to include the media path. Check you have this in your settings.
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')
MEDIA_URL = '/media/'
Last step is to extend the urlpatterns in your urls.py:
urlpatterns = [
# your paths
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This will generate a /media/ directory where your uploaded media files will point to. Then in your frontend you can simply use the model property image.url to get the absolute url of the image.
Related
this is my first question so please point me to the right direction in case I miss something of importance ☺️
So my problem is the following:
I'm currently creating a website with Django, which is supposed to list a variety of projects from the database. Each project has a picture associated with it. The path to this picture is saved in the database (each picture is added as models.ImageField() to the projects model). In order to serve them, I added MEDIA_ROOT = os.path.join(BASE_DIR, 'main/media') to my settings.py and added the following snippet to my urlpatternsin urls.py: + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Now to the crux of it: Everything works fine, except I can't open my admin panel now. The media files are served as expected in the projects overview, but at soon as I try to open the /admin page, I get following error message:
Page not found (404)
“/Users/.../main/media/admin” does not exist
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/
Raised by: django.views.static.serve
as soon as I remove + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) from my url patterns, the admin page works fine again, however the media files are not served anymore.
Can someone show me what I've broken here?
Thank you very much!
I had the same problem. I had a link on my site, that when pressed took me to admin panel.
The mistake was that I was missing a trailing slash.
This did not work:
Admin
This worked:
Admin
You might not have added the MEDIA_URL path in setting.py.
In your case:- add this to settings.py:- MEDIA_URL = "/main/media/". If it doesn't work, try removing one of the two corner slashes. Hope it will work.
I am trying to save images from my Form to my database in django. All of my other CharFields seem to save from my form but not the images. When I go to admin I can upload and save images to a specified media folder and it works however, the images dont seem to save. Please help very confused, also new to this so my code may be a mess, much help is needed. Thanks. Links to my code below:
[updated models][1]
[updated settings][2]
[updated urls][3]
[updated views.py][1]
links to code:
[1]: https://i.stack.imgur.com/Td7Mv.png
[2]: https://i.stack.imgur.com/31vNB.png
[3]: https://i.stack.imgur.com/BXhg7.png
[4]: https://i.stack.imgur.com/fu5BC.png
In your models.py file you need to change all your ImageField to this
media_gallery = models.ImageField(blank=True, null=True, upload_to='photos/%Y/%m/%d/')
This saves the location of the image in the database
Later you can access the image in templates like this
src = "{{ model_name.media_gallery.url }}"
After everything lastly add this code to your settings.py file
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Please update your main project's urls.py file by adding this code at the end
urlpatterns = [] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
A part of my website allows users to upload pictures and videos, just like facebook or instagram, a user can upload either video or picture and it will be rendered on the template depending on the file extension type. Whatever the user uploads either picture or video should be rendered on the template. Am using Django.
models.py
views.py
index.html
First You Need To Join Your Media directory to your app
Here is the Way You Can Do That:
First You Need To Add This in Your Setting.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASEDIR,'your folder directory')
for example app/media or something
Then You Need To Create Media Url Here is The Way:
Then You Need To Add in your root and app urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('your_url_link', views.your_view_name,name='your_url_name'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Then You Need To Add This in Your Html File
<img src='{{ context.Image.url }}'>
#Context mean your returning object Dictionary In Image Add Your Model Image Field Name
You Can See More Details Here:
https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.fields.files.FieldFile.url
So I've spent more than 24 hours trying to figure out how to store an image into my model.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
avatar = models.FileField(null=True, upload_to='www-avatar/')
My Profile Model has an attribute avatar which stands for the profile picture.
What I want to do is after the User has finished the sign-up process, the Profile Model would then be assigned a default image from my static folder.
Here is my Settings.py for static
STATIC_ROOT = '/srv/foo/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, "bar/resource/"), )
And the image that I want to load and store into the model is in bar/resource/profile_light.png
So far, the solution I've come up is with this
file = File()
url = static("bar/resource/profile_light.png")
file = urllib.request.urlopen(url).read()
r = File(file)
authbox.profile.avatar = File(file)
authbox.profile.save()
To no avail. I am new to Django and I would very much appreciate any form of help.
EDIT: I may have worded my question poorly, but I need to add a default image on the profiles that are created. The snippet i gave above of the saving of the avatar is located after the sign up process. So basically I want to access the image every time someone signs up, and the image gets stored as their default avatar.
Firstly change the field type in your models.py as:
avatar = models.ImageField(upload_to='www-avatar/', null=True)
secondly, in your settings file you should define a media directory
MEDIA_DIR = os.path.join(BASE_DIR, "www-avatar")
then, you should modify your urls.py file as
urlpatterns = [
url(r'^admin/', admin.site.urls),
.......
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
last but not least do not forget to install pillow library pip install Pillow (https://pypi.org/project/Pillow/2.2.1/)
In your model:
avatar = models.ImageField(upload_to='www-avatar', default='path/to/my/default/image.jpg')
I am using MySql and Django. I need to select the image route stored in the database, I can't use the url property of an ImageField, It must be the route stored in the database.
First of all, this is my configuration in settings:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
MEDIA_ROOT = PROJECT_ROOT + '/archivos/'
MEDIA_URL = '/archivos/'
My first try on the model was this:
foto = models.ImageField(upload_to = settings.MEDIA_ROOT)
And the URL saved on the database was this:
/home/developer/project/mysystem/archivos/hombre.png
Later I tried this on the model:
foto = models.ImageField(upload_to = '')
And the new URL is this:
./pantalonazul_pXNLcuF.jpg
In both cases the image is uploaded to the MEDIA_ROOT folder, but when I try to use the URL saved on the database, the image doesn't shows. I am changing the src with jquery, I thougth that was the problem, but no, because I putted by hand both URL's in an image, and none of them worked. Also tried this: ../../archivos/pantalonazul_pXNLcuF.jpg but produced the same bad results.
When I enter to the admin, it shows this:
And if I click on that link I get this URL on Address bar:
http://127.0.0.1:8000/archivos/pantalonazul_pXNLcuF.jpg
I also tried to use that URL in the image, written by hand on the src property, but didn't worked.
As an extra, when I click on the link to get that last URL, I have an error that says that the URL is not registered on the urls.py file, shows me a list of my URL's and at the end says this:
The current URL, archivos/pantalonazul_pXNLcuF.jpg, didn't match any of these.
What I'm doing wrong? Why I cant get the image? Is something in the settings or where?
P.S.: The folder where I save the images is outside my app folder, is on the "general" folder, or I don't know how to call it, is in the same folder where settings.py is located, the folders are something like this:
-MyAppFolder
-MySystem
-archivos
-image1.jpg
-image2.jpg
-settings.py
-urls.py
-wsgi.py
I have found a partial solution, reading this Settings Media URL and after it redirected me to this Servinge files during development.
I'm using the last model, the one with the empty uploaded_to and just added the line that the docs recommend on the second link to the urls.py file, and also call the image on this way: ../../archivos/image.jpg but it says that the urls.py solution only works for development, not for serving it as a web page/application, so, someone knows how to make it work in a real server? without using DEBUG=true on settings?