Upload files from django to a specific directory in a server? - python

I have a django-admin panel and a Windows Virtual Private Server.
What i want to do is upload files from django admin panel to a directory like this :
C:\site\media
and i dont want to upload files to django app folder .
This is my settings.py file :
STATIC_ROOT = os.path.join(BASE_DIR,'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
if not os.path.exists(MEDIA_ROOT):
os.makedirs(MEDIA_ROOT)
and This is my model :
class Pictures(models.Model):
product = models.ForeignKey('Products', models.DO_NOTHING)
picurl = models.ImageField()
def __unicode__(self):
return self.title
class Meta:
managed = False
db_table = 'pictures'
verbose_name_plural = "ProductPicturess"
def __str__(self):
return '%s------- (%s)' % (self.product.title,self.picurl)
How should i change it's values ?
Thank you .

After Searching alot and triying different values finally i found the solutin .
Simply I changed MEDIA_ROOT to this :
MEDIA_ROOT = os.path.join(BASE_DIR, '../../../realwamp/wamp64/www/myproject/pictures/')
And volla , My Problem is solved .
With three pairs of dots like ../../../ I back to the C:\ directory and then go to my www folder .

Related

Selenium screenshots are not saved on docker (Python)

Code sequence
self.driver.save_screenshot('./logs/{}.png'.format(step.id))
log = Logs(step=step, attachment='./logs/{}.png'.format(step.id), aditional_data={},
flow_instance=self.flowinstance)
log.save()
The picture is not saved at all in the Docker web container and cannot be accessed through the log.
error given
Logs model
class Logs(models.Model):
step = models.ForeignKey(Step, on_delete=models.CASCADE)
attachment = models.ImageField(upload_to='logs/', blank=True)
aditional_data = models.JSONField()
flow_instance = models.ForeignKey(FlowInstance, on_delete=models.CASCADE)
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')
MEDIA_URL = '/media/'
urls.py i added
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In docker-compose I have selenium-hub, browser instance, worker / beat. All this works correctly, the only problem is when the picture should be taken and saved, which does not happen.

DJANGO - [Errno 30] Read-only file system: '/media'

I get an error regarding Media directory on Django.
forms.py
from django.forms import ModelForm
from .models import Mots
from django import forms
class CreeMot(ModelForm):
mot = forms.CharField(max_length=50)
level = forms.IntegerField(max_value=10)
image = forms.FileField()
class Meta:
model = Mots
fields = ["mot", "level", "image"]
views.py
def cree_mot(request):
if request.method == "POST":
form = CreeMot(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/success/url/')
else:
form = CreeMot()
return render(request, "cp/cree_mot.html", {'form': form})
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
# Add these new lines
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_ROOT = os.path.join(BASE_DIR, 'staticfiles', 'media_root')
When the form is submitted I get this error:
[Errno 30] Read-only file system: '/media'
Actually my /media/ directory is at the same level of /static/:
cp
/views.py
/forms.py
main_app
/settings.py
/...
media
static
manage.py
I put my /media/ in 777 chmod.
You should erase and leave just basics staff to understand what is going on in your app. In your case firstly, remove
MEDIA_ROOT = os.path.join(BASE_DIR, 'staticfiles', 'media_root')
and leave just path to your path to media like :
MEDIA_ROOT = 'path/to/media'
Hope it will help for you

Django upload FileField and ImageField in differnt servers

I want to make a system where user can upload document files and also images (both for different tasks)
and i want to store the files in my own ftp server and images in s3 bucket.
i am using django-storages package
never saw a django approach like this, where FileField and ImageFields can be uploaded to different servers
for example, let's say when user uploads a file the file gets uploaded to my ftp server
FTP_USER = 'testuser'#os.environ['FTP_USER']
FTP_PASS = 'testpassword'#os.environ['FTP_PASS']
FTP_PORT = '21'#os.environ['FTP_PORT']
DEFAULT_FILE_STORAGE = 'storages.backends.ftp.FTPStorage'
FTP_STORAGE_LOCATION = 'ftp://' + FTP_USER + ':' + FTP_PASS + '#192.168.0.200:' + FTP_PORT
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static_my_proj"),
]
STATIC_ROOT = os.path.join(BASE_DIR, "static_cdn", "static_root")
MEDIA_URL = 'ftp://192.168.0.200/'
MEDIA_ROOT = 'ftp://192.168.0.200/'#os.path.join(BASE_DIR, "static_cdn", "media_root")
but problem is images now goto ftp server also
because of this
DEFAULT_FILE_STORAGE = 'storages.backends.ftp.FTPStorage'
yeah i know i can make different directories inside uploaded server root directory like this
def get_filename_ext(filepath):
base_name = os.path.basename(filepath)
name, ext = os.path.splitext(base_name)
return name, ext
def upload_image_path(instance, filename):
# print(instance)
#print(filename)
new_filename = random.randint(1,3910209312)
name, ext = get_filename_ext(filename)
final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext=ext)
return "myapp/{new_filename}/{final_filename}".format(
new_filename=new_filename,
final_filename=final_filename
)
class Product(models.Model):
title = models.CharField(max_length=120)
slug = models.SlugField(blank=True, unique=True)
document = models.FileField(upload_to=upload_image_path, null=True, blank=True)
def get_absolute_url(self):
#return "/products/{slug}/".format(slug=self.slug)
return reverse("detail", kwargs={"slug": self.slug})
def __str__(self):
return self.title
but that's not what i want, i want different servers for file and image uploads
is that even possible ? i mean there can be only one MEDIA_ROOT so how can i write two server addresses, am i making sense ?
EDIT 1:
iain shelvington mentioned a great point, that to add storage option for each field for customized storage backend
like this
from storages.backends.ftp import FTPStorage
fs = FTPStorage()
class FTPTest(models.Model):
file = models.FileField(upload_to='srv/ftp/', storage=fs)
class Document(models.Model):
docfile = models.FileField(upload_to='documents')
and in settings this
DEFAULT_FILE_STORAGE = 'storages.backends.ftp.FTPStorage'
FTP_STORAGE_LOCATION = 'ftp://user:password#localhost:21
but user uploaded photos also gets uploaded to that ftp server
due tp
DEFAULT_FILE_STORAGE = 'storages.backends.ftp.FTPStorage'
and about the MEDIA_URL and MEDIA_ROOT they can be only one right ?
so how can i put two different server address there ?
Thanks for reading this, i really appreciate it.
You can set a base_url in the FTPStorage class as
from storages.backends.ftp import FTPStorage
from django.conf import settings
fs = FTPStorage(base_url=settings.FTP_STORAGE_LOCATION)
class FTPTest(models.Model):
file = models.FileField(upload_to='srv/ftp/', storage=fs)
class Document(models.Model):
docfile = models.FileField(upload_to='documents')
This base_url is useful in building the "absolute URL" of the file and hence you don't need MEDIA_URL and MEDIA_ROOT "in this case"
I want different servers for file and image uploads.
You can achieve it by specifying the storage parameter the FileField (or ImageField)
but user uploaded photos also gets uploaded to that ftp server due to, DEFAULT_FILE_STORAGE settings.
It is your choice. What should be the default storage class in your case? Do you need to upload the media files to S3? or local storage, where the project runs? set the value accordingly.

How to combine django-ckeditor upload path with ImageField upload path

Model:
content = RichTextUploadingField(blank=True, null=True)
image = models.ImageField(upload_to="news/%Y/%m")
I set this in settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
CKEDITOR_UPLOAD_PATH = 'news/%Y/%m'
But the images still go to different folders.Is there anyway to make two paths one?
Best regards!

Django uploading images

I want to upload images in the django admin interface. During development everything works fine but when I put the files on my server it doesn't work.
I have two different paths on my Server. One where I put all my source files and one where I put all the static files.
Path for source files: /htdocs/files/project/
Path for static files: /htdocs/html/project/
If I upload an image, then it is saved in /htdocs/files/project/media/. But I want to save it in /htdocs/html/project/. How can I change the path?
Here are my settings:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
'/var/www/ssd1257/htdocs/html/'
)
And here is my model:
class News(models.Model):
title = models.CharField(max_length=200, null=False)
date = models.DateField(null=False, default=datetime.now)
text = models.TextField(null=False, blank=True)
image = models.ImageField(upload_to="./news/")
The uploaded files are saved normally in the following path
MEDIA_URL + the path specified in “upload_to” attribute in the model class
So in your case,
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') = “/htdocs/files/project/media”
Django will create the path if it doesn’t exits
But I didn’t get the dot in-frontront of ‘upload_to’ to path(“./news/“)
So if you want to change the path where uploaded files are stored, simply change the MEDIA_ROOT
Note, please provide the absolute full path
I guess it will be
MEDIA_ROOT = '/var/www/ssd1257/htdocs/html/project'
Also, its better to rename the uploaded files before saving to avoid file_name conflicts
def get_news_image_path(instance, filename):
path_first_component = ‘news/‘
ext = filename.split('.')[-1]
timestamp = millis = int(round(time.time() * 1000))
file_name = ‘news_’ + str(instance.id) + str('_logo_image_') + timestamp + str('.') + ext
full_path = path_first_component + file_name
return full_path
class News(models.Model):
title = models.CharField(max_length=200, null=False)
date = models.DateField(null=False, default=datetime.now)
text = models.TextField(null=False, blank=True)
image = models.ImageField(upload_to=get_news_image_path)
Now the uploaded files will be saved in
'/var/www/ssd1257/htdocs/html/project/news’
You are Done
In addition, also set appropriate MEDIA_URL
Ex: MEDIA_URL = “media
So when generated URL for the upload images will be
MEDIA_URL + upload_to path
Also, configure the web server to serve these URLs from appropriate locations
from django.core.files.storage import FileSystemStorage
upload_storage = FileSystemStorage(location=UPLOAD_ROOT, base_url='/') #upload root set to your project directory
class News(models.Model):
title = models.CharField(max_length=200, null=False)
date = models.DateField(null=False, default=datetime.now)
text = models.TextField(null=False, blank=True)
image = models.ImageField(upload_to='/', storage=upload_storage)
Self-inflicted by this setting:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Change that to:
MEDIA_ROOT = '/htdocs/html/project/'

Categories