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.
CodePudding user response:
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.