Populating Django SQL Database - python

I would like create a database for my images that I could access using django. For the model I want to create something along these lines of
class Images(models.Model):
Image_loc = models.CharField(max_length = 200)
Image_year = models.CharField(max_length = 200)
Image_date = models.DateTimeField('date taken')
Where image_loc is the image file location and image_year is the year that the image was taken. I would like to populate the database with multiple images. I am new to website design and django and was wondering if anyone knew how would I go about doing this?

For images, you should use ImageField. You'll need to install a library named Pillow for it to work (as per the Django docs I just linked). To do that, just run:
python -m pip install Pillow
You'll also need to set up your MEDIA_ROOT and MEDIA_URL (more on that here). All you need to do is append this to your projects settings.py:
# Media files
# https://docs.djangoproject.com/en/dev/topics/files/
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media/")
MEDIA_URL is the url path of the images.
MEDIA_ROOT is the location of the image files.
Then, add this to your PROJECT'S (not app's) urls.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
...
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
If you set it up this way, you won't need the image_loc field, since that's automatically managed by ImageField. You can just replace that field with the new ImageField.

Related

Django imagefield isn't showing any photo in the template

I'm working on a bookstore using Django. I'm trying to save each book's cover in each book created by the user using imagefield. I implemented every step in Django documentation about using imagefield but it doesn't work.
settings.py(in main project):
MEDIA_DIR = os.path.join(BASE_DIR,'media')
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
in urls.py (main project):
from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("book.urls")),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
in models.py(the book app):
class books(models.Model):
cover = models.ImageField(upload_to='cover/co', blank=True)
When I want go admin I find that the photo is submitted (when I click on the photo url in database nothing is shown to me) but I don't find any created media folders and when I try to request the image in any template It isn't showed to me.
when I try to click on the photo in the database in admin this is shown to me:
enter image description here
These are the paths of the app, project and static:
enter image description here
I don't know where is the problem and how to solve it as this is my first time to use imagefiled in django model,,, it might be from the paths, the model or the urls so if there is any help.
Remove / at the beginning of your MEDIA_URL.
Simply you can try this way:
settings.py file:
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(BASE_DIR,'media')
In models.py file:
class books(models.Model):
cover = models.ImageField(upload_to='cover/', blank=True) #I have removed co from here
After adding above code don't forget to migrate
Try this and see if this is solves your problem

media file not found in a simple django-admin application

I have seen many questions here regarding media files in Django, but honestly I can't find a valid solution for my problem.
So I have decided to streamline the environment to a very simple application.
You can find it here: github project
I have created a project with django-admin and I called 'documents' and then I have created an app called 'docs'.
Then I defined a simple class:
def get_path(instance, filename):
fn, ext = os.path.splitext(filename)
ts = str(int(time.time()))
return os.path.join('{}_{}{}'.format(fn, ts, ext))
class doc(models.Model):
doc_name = models.CharField(max_length=30, verbose_name=u"doc name", help_text=u"name of the doc")
doc_document = models.FileField(upload_to=get_path, verbose_name=u"document", help_text=u"document")
class Meta:
unique_together = ("doc_name", )
def __str__(self):
return f"{self.doc_name}"
This changes the filename and it adds a timestamp.
I also changed the urls.py file adding the following:
path(r'', admin.site.urls),
Now the question is: without using MEDIA_URL and MEDIA_ROOT is it possible to make this working?
I have tried to add a files and it works:
and it properly save the file in the root of the project.
But when I go to the link and click I am getting the following:
Now is it possible to know where is it looking for the file?
Do you think that adding MEDIA_URL and MEDIA_ROOT would help? How should I add it?
I have already tried but without any success.
Additional information
If I set my project in urls.py:
Then I am getting this:
Following the tutorial: https://www.sitepoint.com/django-photo-sharing-app/
I basically changed 3 things:
1-created docs/urls.py and put:
urlpatterns = []
2-changed documents/urls.py to:
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, include
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
# Main app
path('', include('docs.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
3-in documents/settings.py just put the following:
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media/'
it works.

Django model current link not pointing to file in MEDIA_ROOT

My code generates Pandas dataframes. They are big. I save them as files. For this, I have created this Model:
models.py:
class TargetFiles(models.Model):
owner = models.CharField(max_length=25)
csv_file = models.FileField(blank=True, upload_to='target')
file_name = models.CharField(max_length=255)
settings.py:
...
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
mycode.py:
file_content = df.to_csv(index=False, encoding='utf-8')
csvname = 'target1.csv'
csf = ContentFile(file_content, csvname)
TargetFiles.objects.create(owner=self.user, csv_file=csf, file_name=csvname)
urls.py (project):
from django.urls import include, path
from django.contrib import admin
urlpatterns = [
path('dataapp/', include('dataapp.urls')),
]
urls.py (dataapp):
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='dataapp'),
path('welcome/', views.welcome_dataapp, name='welcome_dataapp'),
path('download/<str:file_name>', views.download, name='download'),
]
I don't know if this is the best approach for the problem. This documentation made me skeptical. The thing is that my code is generating the file properly, and saving it in the MEDIA_ROOT directory. But when I go to admin view and click on TargetFiles object, the link to the file returns this error:
The current path, media/target/target1.csv, didn't match any of these.
Since I am not an Django expert, I think I am setting something wrong. Maybe in settings.py or in urls.py (in this file I didn't write any reference to media, maybe this is where the error lives).
I have already read these posts:
Django - how to create a file and save it to a model's FileField?
,
Django: generate a CSV file and store it into FileField and this assign resulting csv file to django model. But I was not able to make the admin link point to the MEDIA_ROOT file.
Does anyone have ideas?
Thanks in advance.
Django does not serve the files stored in the MEDIA_ROOT. You can enable this during development by adding the following to your root url config:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
https://docs.djangoproject.com/en/3.0/howto/static-files/#serving-files-uploaded-by-a-user-during-development
It's recommended to let file serving be handled by some other server (apache or nginx) whe deploying to a production server.

Edit list of pictures that has foreign key to model

I have the following two models:
class Profile(AbstractUser, CommonInfo):
...
pictures = models.ManyToManyField(Picture, blank=True)
and
class Picture(CommonInfo):
picture = models.ImageField(upload_to='gallery/', blank=True, null=True)
What is the best way to display those pictures in a custom template/form/view.
I want to display them all and to delete several of them and add new.
Set media url and root in settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Make changes in urls.py of the project
urlpatterns = [
url(...)
url(...)
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Now you will be able to access the media files in template and perform different operations.

Viewing images uploaded to Django Admin

I have a simple Django admin page that uploads images to a product description. Everything works until I try to view the image by clicking on its path in the products information. I get this error:
Page not found (404)
Request URL: http://0.0.0.0:6666/the_image.jpg
I'm guessing I need to declare something in urls.py, but I have no idea where to start. I also tried changing my media paths in settings.py but I always get errors if I change to anything other than '/'
model.py
class Image(models.Model):
product_image = models.ForeignKey(Product)
image = models.ImageField(upload_to='/')
settings.py
MEDIA_ROOT = '/'
MEDIA_URL = '/'
admin.py
class InlineImage(admin.TabularInline):
model = Image
class ProductAdmin(admin.ModelAdmin):
inlines = [InlineImage]
Docs are here https://docs.djangoproject.com/en/dev/ref/settings/#media-root
You need to set MEDIA_ROOT and MEDIA_URL in your settings file like this
MEDIA_ROOT = /var/www/example.com/media/
MEDIA_URL = /media
and your upload_to should probably be the model name or something to identify it.
image = models.ImageField(upload_to='image')
Then the link should point the /media/image/NAME_OF_IMAGE.png
You will also need to have urls.py setup to server media files. For production you would want to do this in nginx with an alias. See https://docs.djangoproject.com/en/dev/howto/static-files/#serving-files-uploaded-by-a-user-during-development
Which says:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Categories

Resources