So I have the following problem:
On an ivent a javascript sends some text to the django server and there are two functions that should work:
views.py:
def log(request):
f = open('media/log.txt', 'r')
return HttpResponse(f, mimetype='text/plain')
def modelers(request):
mod_stat = request.POST['id']
time = datetime.datetime.now().strftime("%b %d %Y %H:%M:%S")
file=open('media/log.txt', 'a')
file.write(time)
file.write(' ')
file.write(mod_stat)
file.write('\n')
file.close()
return ErrorResponse()
so the user clicks on a button and the "modelers" function is getting the info and is trying to add a line to the log file. But it doesn't work!
The apache error.log says that
IOError: [Errno 13] Permission denied: 'media/log.txt', referer: ...
chmod 777 media doesn't help.. I know that I must config the apache somehow to let the django write files, but didn't find how :(
If not under apache it works great(so the url.py is OK), but I need to make it work with apache. The other part of the application also works fine but there are no operations with files.. until now..
Have you tried chmod 777 media/log.txt? Does ls -l media/ say rwxrwxrwx log.txt? If yes then try to specify absolute path to log.txt in f = open('...log.txt')
Related
i'm try upload file with django(xlsx) this is my code:
myfile = request.FILES['document']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
on the model i have setup the folder "media" to uploads, get this error:
Permission denied: '/var/www/html/inventariosRG/media/my_file.xlsx'
this error i'm try fixed with this:
PATH = 'media/'
myfile = request.FILES['document']
try:
import subprocess
RUTA_ABSOLUTA = os.path.join(os.path.dirname(os.path.dirname(__file__)),PATH)
subprocess.Popen('sudo chmod -R 777 '+RUTA_ABSOLUTA, shell=True)
except Exception as e:
raise Exception ("Error ",e)
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
this code only show the same error "permission denied..." please i'm try set the permission by command on django, any suggest thanks..!!
These answers probably relate and are better than 777-ing:
Django - Media upload [Errno 13] Permission denied
A file from the internet is owned by user 'www-data:www-data' and that user has tightly restricted permissions (because files from the internet might be bad.) Your Django media/ folder needs to be accessible and writeable to the www-data user, so making that owner the user is appropriate.
Also, I'm not a sysadmin by any means and I may be speaking from unrecognized ignorance, but building the use of sudo into your Django application seems like a big security risk to me.
I can see a use for a 'config' script, that ensures a new deployment rolls out correctly, but keep that script and your Django code well separated from files from the internet. You could add your script to /etc/sudoers to give it the authority it needs (but remember to edit sudoers with visudo) if there was some reason to automate it.
Context : Implement prod Django web project in Centos env.
I am trying to solve a function on file storage action that didn't work but i cant see why?... maybe a permission problem...
I have a pretty same function that work...
The function
import os
def manager_file_tasks(file, archive_path):
print(file, archive_path)
# i got this : file.csv /MYHOME/Site_Django/media/archive_file/uploadedFiles
tmp_archive_path = os.path.join(BASE_DIR, 'visualisation', 'UploadFiles', 'file')
# Test if the folder archive exist
if not os.path.exists(tmp_archive_path):
os.makedirs(tmp_archive_path)
print(tmp_archive_path)
# i got this : /MYHOME/Site_Django/visualisation/UploadFiles/file
fs = FileSystemStorage(location=tmp_archive_path)
print(fs)
# i got this : <django.core.files.storage.FileSystemStorage object at 0x7f57f622bda0>
print(armdb_file.name, armdb_file)
# i got this : file.csv file.csv
print(fs.save(armdb_file.name, armdb_file))
# NO RESULT .... :(
filename = fs.save(armdb_file.name, armdb_file)
print(filename)
armdb_file = fs.path(filename)
print(armdb_file)
# some other stuffs are made after....
Here the rights of the folder:
[me#web01]$ ll /MYHOME/Site_Django/visualisation/UploadFiles/
total 0
drw-r--r--. 2 apache apache 6 10 oct. 11:22 file
EDIT 1
I think that i resolve a part of the problem (that encounter with SELinux)
with this command line :
sudo chcon -t httpd_sys_content_t /MYHOME/Site_Django -R
EDIT 2
The file dont exist in my tmp folder :/
Even the python code :
print(file.file.name)
return
/tmp/tmp1t_ahpg4.upload.csv
I cant read this file with that :
with open(file,"r") as f:
print(f.read())
Thanks in advance for the help.
I have a process that scans a tape library and looks for media that has expired, so they can be removed and reused before sending the tapes to an offsite vault. (We have some 7 day policies that never make it offsite.) This process takes around 20 minutes to run, so I didn't want it to run on-demand when loading/refreshing the page. Rather, I set up a django-cron job (I know I could have done this in Linux cron, but wanted the project to be as self-contained as possible) to run the scan, and creates a file in /tmp. I've verified that this works -- the file exists in /tmp from this morning's execution. The problem I'm having is that now I want to display a list of those expired (scratch) media on my web page, but the script is saying that it can't find the file. When the file was created, I use the absolute filename "/tmp/scratch.2015-11-13.out" (for example), but here's the error I get in the browser:
IOError at /
[Errno 2] No such file or directory: '/tmp/corpscratch.2015-11-13.out'
My assumption is that this is a "web root" issue, but I just can't figure it out. I tried copying the file to the /static/ and /media/ directories configured in django, and even in the django root directory, and the project root directory, but nothing seems to work. When it says it cant' find /tmp/file, where is it really looking?
def sample():
""" Just testing """
today = datetime.date.today() #format 2015-11-31
inputfile = "/tmp/corpscratch.%s.out" % str(today)
with open(inputfile) as fh: # This is the line reporting the error
lines = [line.strip('\n') for line in fh]
print(lines)
The print statement was used for testing in the shell (which works, I might add), but the browser gives an error.
And the file does exist:
$ ls /tmp/corpscratch.2015-11-13.out
/tmp/corpscratch.2015-11-13.out
Thanks.
Edit: was mistaken, doesn't work in python shell either. Was thinking of a previous issue.
Use this instead:
today = datetime.datetime.today().date()
inputfile = "/tmp/corpscratch.%s.out" % str(today)
Or:
today = datetime.datetime.today().strftime('%Y-%m-%d')
inputfile = "/tmp/corpscratch.%s.out" % today # No need to use str()
See the difference:
>>> str(datetime.datetime.today().date())
'2015-11-13'
>>> str(datetime.datetime.today())
'2015-11-13 15:56:19.578569'
I ended up finding this elsewhere:
today = datetime.date.today() #format 2015-11-31
inputfilename = "tmp/corpscratch.%s.out" % str(today)
inputfile = os.path.join(settings.PROJECT_ROOT, inputfilename)
With settings.py containing the following:
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
Completely resolved my issues.
In my Django app I have this kind of error: "IOError: [Errno 13] Permission denied: 'file_name'"
This is my code:
def record_export():
for file_name, tab_name in tab:
if len(globals()[tab_name].objects.all()) <> 0:
f = open(file_name, 'wb')
writer = csv.writer(f, delimiter='|')
for record in globals()[tab_name].objects.values_list():
writer.writerow([unicode(s).encode("utf-8") for s in record])
f.close()
In development enviroment all it's ok. I think that I have the permission.
In production I have: "IOError: [Errno 13] Permission denied: 'file_name'"
Do you know why?
Thanks for your help
Djangos's runserver usually runs as root, this is probably your problem.
Your webserver needs rights to read/write the file. You can use ls -l /your/path/to/file to check permissions for a given directory. To change rights and owner, use chmod and chown.
If you are running a apache2 webserver your user and group is in most cases www-data.
Hi am absolutely new to django,Now I am tring for builtin reset password view..
I follow the link link
But I got the error when I click on reset password button at /password_reset/ :
error at /accounts/password_reset/
[Errno 10061] No connection could be made because the target machine actively refused it.
Exception Location: C:\Python27\lib\socket.py in create_connection, line 571
'urls.py'
(r'^accounts/password_reset$','django.contrib.auth.views.password_reset','template_name':'user/password_reset_form.html','email_template_name':'user/password_reset_email.html'}),
(r'^accounts/password/reset/confirm/(?P[0-9A-Za-z]{1,13})-(?P[0-9Aa-z]{1,13}-[0-9A-Za-z]{1,20})/$', 'django.contrib.auth.views.password_reset_confirm', {'template_name' : 'user/password_reset.html', 'post_reset_redirect': '/logout/' }),
(r'^accounts/password_reset/done/$',<b>'django.contrib.auth.views.password_reset_done'</b>,{'template_name':'user/password_reset_done.html'}),
(r'^accounts/change_password/$',<b> 'password_change'</b>, {'post_change_redirect' : '/accounts/change_password/done/'}),
(r'^accounts/change_password/done/$',<b> 'password_change_done'</b>,{'template_name':'user/password_change_done.html'}),
<b>password_reset_email.html</b>
{% extends 'base.html'%}
{% block content%}
{% url django.contrib.auth.views.password_reset_confirm uidb36=uid, token=token %}
{% endblock %}
I add necessary templates in the folder 'user'.Please help me,Thanks in advance.
As rdegges said, it's a connection error. Check which port the request is trying to access, and make sure windows firewall is set up to receive on that port. You can check the port by looking through django's traceback page, and looking at the "local vars".
From the looks of it, it's an email port. Take another look at the traceback and look out for django trying to send a request to port 25. If it does, make sure your port 25 is configured to receive.
Also, you'll need a makeshift SMTP server for testing purposes because you probably wouldn't want to be using a real one. Just have this running in a separate command prompt window while you're running django, and any emails that django tries to send through your port 25 will be saved in an "emails" folder in the working directory.
#/usr/bin/env python
from datetime import datetime
import asyncore
from smtpd import SMTPServer
class EmlServer(SMTPServer):
no = 0
def process_message(self, peer, mailfrom, rcpttos, data):
filename = '%s-%d.eml' % (datetime.now().strftime('%Y%m%d%H%M%S'), self.no)
f = open(filename, 'w')
f.write(data)
f.close()
print '%s saved.' % filename
self.no += 1
def run():
foo = EmlServer(('localhost', 25), None)
try:
asyncore.loop()
except KeyboardInterrupt:
pass
if __name__ == '__main__':
from os.path import exists, join
from os import mkdir, chdir, getcwd
target_directory = join( getcwd(), "emails" )
if exists(target_directory):
chdir(target_directory)
else:
try:
mkdir(target_directory)
except OSError:
from sys import exit
exit("The containing folder couldn't be created, check your permissions.")
chdir(target_directory)
print "Using directory %s" % target_directory
run()
The error you're getting is a connection error--that means that the server you're using to run your Django site is likely not working correctly. Here are some things you can try on your Django server:
If you're running your Django site via python manage.py runserver, you can try to simply re-run that command.
If you're running your site via a webserver like apache, try restarting apache.
If neither of those work, post a comment and let me know what operating system you're running your site on, and how you're running it, and we can do further debugging.