def render_pdf(self):
if self.sponsoring.billingReferenceOptOut:
billRef = str(self.sponsoring.id)
else:
billRef = self.sponsoring.billingReference
context = {
"POSTAL_ADDRESS" : self.sponsoring.getBillingAddress(),
"INVOICE_NUMBER" : self.invoiceNumber,
"INVOICE_REF" : billRef,
"DUE_DATE" : self.dueDate.strftime("%d.%m.%Y"),
"PACKAGE_NAME" : self.sponsoring.package.name,
"PACKAGE_DESCRIPTION" : "\n".join(self.sponsoring.getPacketDescription()),
"VAT" : str(settings.INVOICE_VAT),
"PRICE_NET" : str(self.sponsoring.package.price.quantize(Decimal("0.01"))),
"PRICE_GROSS" : str(self.sponsoring.package.getPriceGross()),
"VAT_TOTAL" : str(self.sponsoring.package.getVATAmount()),
}
temp = odtemplate.ODTTemplate(self.template.template.path)
temp.render(context)
if not os.path.exists(settings.MEDIA_ROOT + "invoice_pdfs"):
os.mkdir(settings.MEDIA_ROOT + "invoice_pdfs")
pdfpath = settings.MEDIA_ROOT + "invoice_pdfs/" + self.getInvoiceFilename()
temp.savePDF(pdfpath)
self.pdf.name = "invoice_pdfs/" + self.getInvoiceFilename()
self.save()
python类MEDIA_ROOT的实例源码
def get_cloud_rate(scene_name):
"""Read the MTL file and return the cloud_rate of the scene."""
sat = 'L%s' % scene_name[2]
mtl_path = join(settings.MEDIA_ROOT, sat, scene_name, scene_name + '_MTL.txt')
if isfile(mtl_path):
with open(mtl_path, 'r') as f:
lines = f.readlines()
cloud_rate = [float(line.split(' = ')[-1]) for line in lines if 'CLOUD_COVER' in line][0]
return cloud_rate
else:
url_code = get_metadata_code(scene_name)
metadata = PyQuery(
'http://earthexplorer.usgs.gov/metadata/%s/%s/' % (url_code, scene_name)
)
metadata = metadata.text()[metadata.text().find('Cloud Cover '):]
return float(metadata.split(' ')[2])
def test_creation(self):
self.assertEqual(self.scene.__str__(), 'L8 001-001 01/01/15')
self.assertEqual(self.scene.day(), '001')
self.assertEqual(self.scene.dir(),
join(settings.MEDIA_ROOT, 'L8/LC80010012015001LGN00'))
self.scene.status = 'downloaded'
self.scene.save()
self.assertEqual(self.scene.status, 'downloaded')
Scene.objects.create(
path='001',
row='001',
sat='L8',
date=date(2015, 1, 17),
name='LC80010012015017LGN00',
status='downloading'
)
self.assertEqual(Scene.objects.count(), 4)
def setUp(self):
self.today_number = three_digit(date.today().timetuple().tm_yday)
self.sd = ScheduledDownload.objects.create(path='220', row='066')
self.sd2 = ScheduledDownload.objects.create(path='999', row='002')
self.scene = Scene.objects.create(
path='220',
row='066',
sat='L8',
date=date(2015, 1, 1),
name='LC82200662015001LGN00',
cloud_rate=20.3,
status='downloading'
)
if not exists(settings.MEDIA_ROOT):
makedirs(settings.MEDIA_ROOT)
def __init__(self, location=None, base_url=None, file_permissions_mode=None,
directory_permissions_mode=None):
if location is None:
location = settings.MEDIA_ROOT
self.base_location = location
self.location = abspathu(self.base_location)
if base_url is None:
base_url = settings.MEDIA_URL
elif not base_url.endswith('/'):
base_url += '/'
self.base_url = base_url
self.file_permissions_mode = (
file_permissions_mode if file_permissions_mode is not None
else settings.FILE_UPLOAD_PERMISSIONS
)
self.directory_permissions_mode = (
directory_permissions_mode if directory_permissions_mode is not None
else settings.FILE_UPLOAD_DIRECTORY_PERMISSIONS
)
def check_settings(base_url=None):
"""
Checks if the staticfiles settings have sane values.
"""
if base_url is None:
base_url = settings.STATIC_URL
if not base_url:
raise ImproperlyConfigured(
"You're using the staticfiles app "
"without having set the required STATIC_URL setting.")
if settings.MEDIA_URL == base_url:
raise ImproperlyConfigured("The MEDIA_URL and STATIC_URL "
"settings must have different values")
if ((settings.MEDIA_ROOT and settings.STATIC_ROOT) and
(settings.MEDIA_ROOT == settings.STATIC_ROOT)):
raise ImproperlyConfigured("The MEDIA_ROOT and STATIC_ROOT "
"settings must have different values")
def __init__(self, location=None, base_url=None, file_permissions_mode=None,
directory_permissions_mode=None):
if location is None:
location = settings.MEDIA_ROOT
self.base_location = location
self.location = abspathu(self.base_location)
if base_url is None:
base_url = settings.MEDIA_URL
elif not base_url.endswith('/'):
base_url += '/'
self.base_url = base_url
self.file_permissions_mode = (
file_permissions_mode if file_permissions_mode is not None
else settings.FILE_UPLOAD_PERMISSIONS
)
self.directory_permissions_mode = (
directory_permissions_mode if directory_permissions_mode is not None
else settings.FILE_UPLOAD_DIRECTORY_PERMISSIONS
)
def check_settings(base_url=None):
"""
Checks if the staticfiles settings have sane values.
"""
if base_url is None:
base_url = settings.STATIC_URL
if not base_url:
raise ImproperlyConfigured(
"You're using the staticfiles app "
"without having set the required STATIC_URL setting.")
if settings.MEDIA_URL == base_url:
raise ImproperlyConfigured("The MEDIA_URL and STATIC_URL "
"settings must have different values")
if ((settings.MEDIA_ROOT and settings.STATIC_ROOT) and
(settings.MEDIA_ROOT == settings.STATIC_ROOT)):
raise ImproperlyConfigured("The MEDIA_ROOT and STATIC_ROOT "
"settings must have different values")
def __init__(self, location=None, base_url=None, file_permissions_mode=None,
directory_permissions_mode=None):
if location is None:
location = settings.MEDIA_ROOT
self.base_location = location
self.location = abspathu(self.base_location)
if base_url is None:
base_url = settings.MEDIA_URL
elif not base_url.endswith('/'):
base_url += '/'
self.base_url = base_url
self.file_permissions_mode = (
file_permissions_mode if file_permissions_mode is not None
else settings.FILE_UPLOAD_PERMISSIONS
)
self.directory_permissions_mode = (
directory_permissions_mode if directory_permissions_mode is not None
else settings.FILE_UPLOAD_DIRECTORY_PERMISSIONS
)
def check_settings(base_url=None):
"""
Checks if the staticfiles settings have sane values.
"""
if base_url is None:
base_url = settings.STATIC_URL
if not base_url:
raise ImproperlyConfigured(
"You're using the staticfiles app "
"without having set the required STATIC_URL setting.")
if settings.MEDIA_URL == base_url:
raise ImproperlyConfigured("The MEDIA_URL and STATIC_URL "
"settings must have different values")
if ((settings.MEDIA_ROOT and settings.STATIC_ROOT) and
(settings.MEDIA_ROOT == settings.STATIC_ROOT)):
raise ImproperlyConfigured("The MEDIA_ROOT and STATIC_ROOT "
"settings must have different values")
def __init__(self, location=None, base_url=None, file_permissions_mode=None,
directory_permissions_mode=None):
if location is None:
location = settings.MEDIA_ROOT
self.base_location = location
self.location = abspathu(self.base_location)
if base_url is None:
base_url = settings.MEDIA_URL
elif not base_url.endswith('/'):
base_url += '/'
self.base_url = base_url
self.file_permissions_mode = (
file_permissions_mode if file_permissions_mode is not None
else settings.FILE_UPLOAD_PERMISSIONS
)
self.directory_permissions_mode = (
directory_permissions_mode if directory_permissions_mode is not None
else settings.FILE_UPLOAD_DIRECTORY_PERMISSIONS
)
def check_settings(base_url=None):
"""
Checks if the staticfiles settings have sane values.
"""
if base_url is None:
base_url = settings.STATIC_URL
if not base_url:
raise ImproperlyConfigured(
"You're using the staticfiles app "
"without having set the required STATIC_URL setting.")
if settings.MEDIA_URL == base_url:
raise ImproperlyConfigured("The MEDIA_URL and STATIC_URL "
"settings must have different values")
if ((settings.MEDIA_ROOT and settings.STATIC_ROOT) and
(settings.MEDIA_ROOT == settings.STATIC_ROOT)):
raise ImproperlyConfigured("The MEDIA_ROOT and STATIC_ROOT "
"settings must have different values")
def form_valid(self, form):
data = form.cleaned_data
docfile = data['archivo']
form.save()
csv_filepathname = os.path.join(settings.MEDIA_ROOT, 'archivos', str(docfile))
dataReader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='"')
for fila in dataReader:
dni = fila[0]
if dni != "":
appaterno = fila[1].upper()
apmaterno = fila[2].upper()
nombres = fila[3].upper()
try:
productor, creado = Productor.objects.get_or_create(dni=dni,
defaults={'apellido_paterno': appaterno,
'apellido_materno': apmaterno,
'nombres': nombres})
except:
pass
return HttpResponseRedirect(reverse('administracion:maestro_productores'))
def tabla_encabezado(self, styles):
sp = ParagraphStyle('parrafos',
alignment=TA_CENTER,
fontSize=14,
fontName="Times-Roman")
requerimiento = self.requerimiento
try:
archivo_imagen = os.path.join(settings.MEDIA_ROOT, str(EMPRESA.logo))
imagen = Image(archivo_imagen, width=90, height=50, hAlign='LEFT')
except:
print u"Ingresa acá "
imagen = Paragraph(u"LOGO", sp)
nro = Paragraph(u"REQUERIMIENTO DE BIENES Y SERVICIOS<br/>N°" + requerimiento.codigo, sp)
encabezado = [[imagen, nro, '']]
tabla_encabezado = Table(encabezado, colWidths=[4 * cm, 11 * cm, 4 * cm])
tabla_encabezado.setStyle(TableStyle(
[
('ALIGN', (0, 0), (1, 0), 'CENTER'),
('VALIGN', (0, 0), (1, 0), 'CENTER'),
]
))
return tabla_encabezado
def tabla_encabezado_consolidado(self, grupos):
sp = ParagraphStyle('parrafos',
alignment=TA_CENTER,
fontSize=14,
fontName="Times-Roman")
try:
archivo_imagen = os.path.join(settings.MEDIA_ROOT, str(EMPRESA.logo))
imagen = Image(archivo_imagen, width=90, height=50, hAlign='LEFT')
except:
imagen = Paragraph(u"LOGO", sp)
if grupos:
titulo = Paragraph(u"RESUMEN MENSUAL DE ALMACÉN POR GRUPOS Y CUENTAS", sp)
else:
titulo = Paragraph(u"RESUMEN MENSUAL DE ALMACÉN POR PRODUCTOS", sp)
encabezado = [[imagen,titulo]]
tabla_encabezado = Table(encabezado, colWidths=[2 * cm, 23 * cm])
style = TableStyle(
[
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
]
)
tabla_encabezado.setStyle(style)
return tabla_encabezado
def form_valid(self, form):
data = form.cleaned_data
docfile = data['archivo']
form.save()
csv_filepathname = os.path.join(settings.MEDIA_ROOT,'archivos',str(docfile))
dataReader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='"')
for fila in dataReader:
try:
cuenta = CuentaContable.objects.get(cuenta=fila[0])
descripcion = fila[1]
grupo_productos, creado = GrupoProductos.objects.get_or_create(descripcion=unicode(descripcion, errors='ignore'),
defaults={'ctacontable' : cuenta
})
except CuentaContable.DoesNotExist:
pass
return HttpResponseRedirect(reverse('productos:grupos_productos'))
def check_settings(base_url=None):
"""
Checks if the staticfiles settings have sane values.
"""
if base_url is None:
base_url = settings.STATIC_URL
if not base_url:
raise ImproperlyConfigured(
"You're using the staticfiles app "
"without having set the required STATIC_URL setting.")
if settings.MEDIA_URL == base_url:
raise ImproperlyConfigured("The MEDIA_URL and STATIC_URL "
"settings must have different values")
if ((settings.MEDIA_ROOT and settings.STATIC_ROOT) and
(settings.MEDIA_ROOT == settings.STATIC_ROOT)):
raise ImproperlyConfigured("The MEDIA_ROOT and STATIC_ROOT "
"settings must have different values")
def check_settings(base_url=None):
"""
Checks if the staticfiles settings have sane values.
"""
if base_url is None:
base_url = settings.STATIC_URL
if not base_url:
raise ImproperlyConfigured(
"You're using the staticfiles app "
"without having set the required STATIC_URL setting.")
if settings.MEDIA_URL == base_url:
raise ImproperlyConfigured("The MEDIA_URL and STATIC_URL "
"settings must have different values")
if ((settings.MEDIA_ROOT and settings.STATIC_ROOT) and
(settings.MEDIA_ROOT == settings.STATIC_ROOT)):
raise ImproperlyConfigured("The MEDIA_ROOT and STATIC_ROOT "
"settings must have different values")
def static(prefix, view=serve, **kwargs):
"""
Helper function to return a URL pattern for serving files in debug mode.
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)
"""
# No-op if not in debug mode or an non-local prefix
if not settings.DEBUG or (prefix and '://' in prefix):
return []
elif not prefix:
raise ImproperlyConfigured("Empty static prefix not permitted")
return [
url(r'^%s(?P<path>.*)$' % re.escape(prefix.lstrip('/')), view, kwargs=kwargs),
]
def delete_test_image(image_field):
"""
Deletes test image generated as well as thumbnails if created.
The recommended way of using this helper function is as follows:
delete_test_image(object_1.image_property)
:param image_field: The image field on an object.
:return: None.
"""
warnings.warn(DeprecationWarning(
"delete_test_image() is deprecated in favour of the "
"get_sample_image() context manager."), stacklevel=2)
# ensure all thumbs are deleted
for filename in glob.glob(
os.path.join(
settings.MEDIA_ROOT, 'thumbs', image_field.name.split('/')[-1]
) + '*'
):
os.unlink(filename)
# delete the saved file
image_field.delete()