Re: Django Exception "Detected path traversal attempt in" for save a model with filefield

2022-02-04 Thread Joalbert Palacios
ES
[{'APP_DIRS': True, 'BACKEND': 
'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'OPTIONS': 
{'context_processors': ['django.template.context_processors.debug', 
'django.template.context_processors.request', 
'django.contrib.auth.context_processors.auth', 
'django.contrib.messages.context_processors.messages']}}]
TEST_NON_SERIALIZED_APPS
[]
TEST_RUNNER
'django.test.runner.DiscoverRunner'
THOUSAND_SEPARATOR
','
TIME_FORMAT
'P'
TIME_INPUT_FORMATS
['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']
TIME_ZONE
'UTC'
USE_I18N
True
USE_L10N
True
USE_THOUSAND_SEPARATOR
False
USE_TZ
True
USE_X_FORWARDED_HOST
False
USE_X_FORWARDED_PORT
False
WSGI_APPLICATION
'dummy.wsgi.application'
X_FRAME_OPTIONS
'DENY'
YEAR_MONTH_FORMAT
'F Y'

Thanks a lot for your help!

Sincerely,
Joalbert

On Friday, February 4, 2022 at 1:54:44 PM UTC-5 jacobgr...@gmail.com wrote:

> Hmm that can't be right. 
>
> Can you set a breakpoint on the line where the exception is raised: 
> SuspiciousFileOperation("Detected. 
>
> When you set a breakpoint there, inspect the value of dir_name.
>
> The ".parts" method breaks the file path up into a tuple, there shouldn't 
> be a ".." in the tuple.
>
> On Fri, Feb 4, 2022, 10:49 AM Joalbert Palacios  wrote:
>
>> Hi, 
>>
>> dir_name in the exception is '/home/joalbert/Documents/Remesas 
>> App/RemesasServer/media/payments/images/filename.jpg'
>>
>> The setting for media is:
>> Settings.py:
>> MEDIA_ROOT = "./media/"#os.path.join(BASE_DIR, 'media')
>> MEDIA_URL = '/media/'
>>
>> I try also with 
>> MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
>> where BASE_DIR = Path(__file__).resolve().parent.parent
>>
>> If you could tell me how could fix it, it would be nice. Since I do not 
>> have idea how to remove this exception.
>>
>> Sincerely,
>> Joalbert
>> On Friday, February 4, 2022 at 12:33:51 AM UTC-5 jacobgr...@gmail.com 
>> wrote:
>>
>>> This is obviously some type of security feature to prevent someone from 
>>> climbing up a directory. You have ".." in your string for the file path 
>>> somewhere. 
>>>
>>> What is the value of "dir_name" when the exception is raised? It should 
>>> be in the traceback somewhere. Should help narrow down where it's coming 
>>> from. Most likely a mistake you made in your settings file concating 
>>> strings related to where Django should upload files. 
>>>
>>> On Thu, Feb 3, 2022, 2:12 PM Joalbert Palacios  
>>> wrote:
>>>
>>>> Hi group,
>>>>
>>>> I have been updating my django version so as to cover the last security 
>>>> patch with django version 3.2  (current version 3.2.12). 
>>>>
>>>> Unfortunately, after this update the following exception occurs during 
>>>> execution of testing:
>>>>
>>>> Detected path traversal attempt in '/home/joalbert/Documents/Remesas 
>>>> App/RemesasServer/media/payments/images/temp_qHaTViL.png'
>>>> Bad Request: /webapp/payment
>>>>
>>>> I have read 
>>>> https://stackoverflow.com/questions/69745412/django-and-suspiciousfileoperationdetected-path-traversal-attempt
>>>>  
>>>> and followed but not works in my case, maybe I misunderstood something, I 
>>>> would appreciate any help regarding how to fix those exception. 
>>>>
>>>> I read django code and find the errors is in the following section:
>>>>
>>>> def get_available_name(self, name, max_length=None):
>>>>
>>>> """
>>>>
>>>> Return a filename that's free on the target storage system and
>>>>
>>>> available for new content to be written to.
>>>>
>>>> """
>>>>
>>>> name = str(name).replace('\\', '/')
>>>>
>>>> dir_name, file_name = os.path.split(name)
>>>>
>>>> if '..' in pathlib.PurePath(dir_name).parts:
>>>>
>>>> raise SuspiciousFileOperation("Detected path traversal attempt in '%s'" 
>>>> % dir_name)
>>>>
>>>> Here it is my code in the sections that code goes by to send response 
>>>> to client.
>>>>
>>>> *Model.py:*
>>>> class Payment(models.Model):
>>>> STATUS = ((0, _("Draft")), (1, _("Aproved")), (2 , _("Rejected")), (3, 
>>>> _("Released")))
>>>> order_number_id = models.OneToOneField(Exchange_Order, 
>>&g

Re: Django Exception "Detected path traversal attempt in" for save a model with filefield

2022-02-04 Thread Joalbert Palacios
Hi, 

dir_name in the exception is '/home/joalbert/Documents/Remesas 
App/RemesasServer/media/payments/images/filename.jpg'

The setting for media is:
Settings.py:
MEDIA_ROOT = "./media/"#os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

I try also with 
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
where BASE_DIR = Path(__file__).resolve().parent.parent

If you could tell me how could fix it, it would be nice. Since I do not 
have idea how to remove this exception.

Sincerely,
Joalbert
On Friday, February 4, 2022 at 12:33:51 AM UTC-5 jacobgr...@gmail.com wrote:

> This is obviously some type of security feature to prevent someone from 
> climbing up a directory. You have ".." in your string for the file path 
> somewhere. 
>
> What is the value of "dir_name" when the exception is raised? It should be 
> in the traceback somewhere. Should help narrow down where it's coming from. 
> Most likely a mistake you made in your settings file concating strings 
> related to where Django should upload files. 
>
> On Thu, Feb 3, 2022, 2:12 PM Joalbert Palacios  wrote:
>
>> Hi group,
>>
>> I have been updating my django version so as to cover the last security 
>> patch with django version 3.2  (current version 3.2.12). 
>>
>> Unfortunately, after this update the following exception occurs during 
>> execution of testing:
>>
>> Detected path traversal attempt in '/home/joalbert/Documents/Remesas 
>> App/RemesasServer/media/payments/images/temp_qHaTViL.png'
>> Bad Request: /webapp/payment
>>
>> I have read 
>> https://stackoverflow.com/questions/69745412/django-and-suspiciousfileoperationdetected-path-traversal-attempt
>>  
>> and followed but not works in my case, maybe I misunderstood something, I 
>> would appreciate any help regarding how to fix those exception. 
>>
>> I read django code and find the errors is in the following section:
>>
>> def get_available_name(self, name, max_length=None):
>>
>> """
>>
>> Return a filename that's free on the target storage system and
>>
>> available for new content to be written to.
>>
>> """
>>
>> name = str(name).replace('\\', '/')
>>
>> dir_name, file_name = os.path.split(name)
>>
>> if '..' in pathlib.PurePath(dir_name).parts:
>>
>> raise SuspiciousFileOperation("Detected path traversal attempt in '%s'" % 
>> dir_name)
>>
>> Here it is my code in the sections that code goes by to send response to 
>> client.
>>
>> *Model.py:*
>> class Payment(models.Model):
>> STATUS = ((0, _("Draft")), (1, _("Aproved")), (2 , _("Rejected")), (3, 
>> _("Released")))
>> order_number_id = models.OneToOneField(Exchange_Order, 
>> on_delete=models.CASCADE, related_name="order_payment")
>> user_id =models.ForeignKey(User, verbose_name=_('user'), on_delete= 
>> models.CASCADE, related_name="payment_user_id")
>> capture = models.FileField(verbose_name=_('image'), 
>> upload_to="payments/images", max_length=1024)
>> payment_date = models.DateTimeField(verbose_name=_('date'), 
>> default=datetime.now().replace(tzinfo=timezone.utc))
>> status = models.PositiveSmallIntegerField(verbose_name=_('status'), 
>> default=0, choices=STATUS) 
>> reason = models.ForeignKey(Reasons,verbose_name=_('reason'), 
>> on_delete=models.CASCADE, related_name="payment_reason", 
>> null=True, blank=True)
>>
>> def __str__(self) -> str:
>> return f"{self.order_number_id} {self.user_id.username} 
>> {self.payment_date}"
>> class Meta: #new
>> verbose_name = _("Payment from Client to 'Activo Digital'")
>> verbose_name_plural = _("Payments from Client to 'Activo Digital'")
>>
>> *forms.py*
>> class Payment_All_Form(forms.ModelForm):
>> class Meta: 
>> model = Payment
>> fields = "__all__"
>> views.py (only post method is included for clarity)
>> class PaymentSessionView(LoginRequiredMixin, CreateView):
>> queryset = Payment.objects.all()
>> form_class = Payment_Form
>> http_method_names = ['get', 'post']
>> template_name="clienteServidor/webapp/payment.html" 
>>
>> @method_decorator(User_Detail_Permission_Web)
>> def post(self, request, *args, **kwargs):
>> models = Exchange_Order.objects.filter(status=0, user_id=request.user)
>> # En caso de que no haya ordenes abiertas
>> if not models.exists():
>> context =self._add_context_data()
>> context["existant"]

Django Exception "Detected path traversal attempt in" for save a model with filefield

2022-02-03 Thread Joalbert Palacios
Hi group,

I have been updating my django version so as to cover the last security 
patch with django version 3.2  (current version 3.2.12). 

Unfortunately, after this update the following exception occurs during 
execution of testing:

Detected path traversal attempt in '/home/joalbert/Documents/Remesas 
App/RemesasServer/media/payments/images/temp_qHaTViL.png'
Bad Request: /webapp/payment

I have 
read 
https://stackoverflow.com/questions/69745412/django-and-suspiciousfileoperationdetected-path-traversal-attempt
 
and followed but not works in my case, maybe I misunderstood something, I 
would appreciate any help regarding how to fix those exception. 

I read django code and find the errors is in the following section:

def get_available_name(self, name, max_length=None):

"""

Return a filename that's free on the target storage system and

available for new content to be written to.

"""

name = str(name).replace('\\', '/')

dir_name, file_name = os.path.split(name)

if '..' in pathlib.PurePath(dir_name).parts:

raise SuspiciousFileOperation("Detected path traversal attempt in '%s'" % 
dir_name)

Here it is my code in the sections that code goes by to send response to 
client.

*Model.py:*
class Payment(models.Model):
STATUS = ((0, _("Draft")), (1, _("Aproved")), (2 , _("Rejected")), (3, 
_("Released")))
order_number_id = models.OneToOneField(Exchange_Order, 
on_delete=models.CASCADE, related_name="order_payment")
user_id =models.ForeignKey(User, verbose_name=_('user'), on_delete= 
models.CASCADE, related_name="payment_user_id")
capture = models.FileField(verbose_name=_('image'), 
upload_to="payments/images", max_length=1024)
payment_date = models.DateTimeField(verbose_name=_('date'), 
default=datetime.now().replace(tzinfo=timezone.utc))
status = models.PositiveSmallIntegerField(verbose_name=_('status'), 
default=0, choices=STATUS) 
reason = models.ForeignKey(Reasons,verbose_name=_('reason'), 
on_delete=models.CASCADE, related_name="payment_reason", 
null=True, blank=True)

def __str__(self) -> str:
return f"{self.order_number_id} {self.user_id.username} {self.payment_date}"
class Meta: #new
verbose_name = _("Payment from Client to 'Activo Digital'")
verbose_name_plural = _("Payments from Client to 'Activo Digital'")

*forms.py*
class Payment_All_Form(forms.ModelForm):
class Meta: 
model = Payment
fields = "__all__"
views.py (only post method is included for clarity)
class PaymentSessionView(LoginRequiredMixin, CreateView):
queryset = Payment.objects.all()
form_class = Payment_Form
http_method_names = ['get', 'post']
template_name="clienteServidor/webapp/payment.html" 

@method_decorator(User_Detail_Permission_Web)
def post(self, request, *args, **kwargs):
models = Exchange_Order.objects.filter(status=0, user_id=request.user)
# En caso de que no haya ordenes abiertas
if not models.exists():
context =self._add_context_data()
context["existant"] ="No hay orden abierta"
context["form"] = Payment_Form()
return render(request,self.template_name, context)
# Procesar pago para ordenes abiertas
forms = []
data_list = []
order_ids = []
for model in models:
my_data = self._complete_data(request, model.id)
data_list.append(my_data)
order_ids.append(f"Orden: {model.id}")
forms.append(Payment_All_Form(my_data,request.FILES))
# Chequear que todas las formas sean validas
are_valids = []
for form in forms: 
are_valids.append(form.is_valid())
# If any invalid
if False in are_valids:
for index, items in enumerate(are_valids):
if not items:
form = forms[index] 
context = self._add_context_data() 
context["form"] = form 
return render(request,self.template_name, context)
for index, model in enumerate(models):
if index == 0:
forms[index].save()
else:
data_list[index]["order_number_id"]=model
data_list[index]["user_id"]=request.user
datum = {k:v for k,v in data_list[index].items() if 
k!="csrfmiddlewaretoken"}
payment = Payment(**datum)
payment.save() 
model.status=1
model.grouped_orders = order_ids
model.save()
my_message ="Orden Nro "+ str(model.id) + (" fue procesada exitosamente, 
les estaremos notificando"
" por correo cuando el pago sea validado y procesado en el destino.")
messages.add_message(request, messages.INFO, my_message)
return HttpResponseRedirect(reverse_lazy("transaction_web"))

Settings.py:
MEDIA_ROOT = "./media/"#os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

I hope sincerely that you could have any answer how to fix it. I really 
appreciate your help regarding this issue.

Sincerely,
Joalbert 

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/35a15616-92fc-41d4-97b3-8fb3061ec881n%40googlegroups.com.


Re: Ayuda como pasar un sql al ORM Django

2019-12-07 Thread Joalbert Palacios
Hola, por fa revisa lo referente a queryset.

Cuando creas un modelo puedes hacer los queries sin necesidad de usar SQL.

Si necesitas más detalles por fa envíame la estructura de las tablas y te
ayudo con un ejemplo ilustrativo, pero te comento que la documentación de
Django está bastante buena en lo referente a modelos.

Espero sea de ayuda.

Un saludo,
Joalbert

On Sat, Dec 7, 2019, 6:58 PM DEYMER DE JESUS HOYOS PEREZ <
ddhoy...@misena.edu.co> wrote:

> Me gustaría saber como puedo pasar esta consulta de postgresql usando el
> orm de django
>
> SELECT  peluqueria_persona."Nombre", "GananciaEmpleado" From venta_venta
> INNER JOIN cita_cita ON  cita_cita.id = "Cita_id"
> INNER JOIN peluqueria_empleado  ON cita_cita.id = "Empleado_id"
> INNER JOIN peluqueria_persona  ON "Contacto_id" = peluqueria_persona.id ;
>
> gracias..
>
>
>
> *Declinación de Responsabilidades:* Los servicios de MISENA son
> soportados tecnológicamente por © Google y ofrecidos por el Servicio
> Nacional de Aprendizaje – SENA de manera gratuita a los aprendices e
> instructores de programas de formación titulada, las opiniones que contenga
> este mensaje son exclusivas de su autor y no representan la opinión del
> Servicio Nacional de Aprendizaje o de sus autoridades. El receptor deberá
> verificar posibles virus informáticos que tenga el correo o cualquier
> anexo, razón por la cual el SENA no es responsable de los daños causados
> por cualquier virus transmitido en este correo electrónico.
>
> Los contenidos, textos, imágenes, archivos enviados en este mensaje son
> responsabilidad exclusiva del remitente y no reflejan ni comprometen de
> ninguna manera a la institución. No se autoriza el uso de esta herramienta
> para el intercambio de correos masivos, cadenas o spam, ni de mensajes
> ofensivos, de carácter político, sexual o religioso, con fines de lucro,
> con propósitos delictivos o cualquier otro mensaje que se considere
> indebido o que vaya en contra de la Ley.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/2d6faf86-b14b-44fd-8cdd-b7191d1e0b5a%40googlegroups.com
> 
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAEtK16FuL0LZ40hv40KYpJgTscL2xPWZxDMBtHV_af3hT3fGqw%40mail.gmail.com.


Re: a variable is not defined

2019-10-18 Thread Joalbert Palacios
Not sure, but I believe that is because scope, given that result variable
is defined in the inner method and not defined in search function.

On Fri, Oct 18, 2019, 3:49 PM sotiris moustogiannis 
wrote:

> thanks for your help!!
>
> On Friday, October 18, 2019 at 6:59:05 AM UTC+3, jlgimeno71 wrote:
>>
>> I saw this that may be relevant:
>>
>>
>> https://stackoverflow.com/questions/7576202/how-can-i-pass-two-models-to-a-class-based-generic-view
>>
>> -Jorge
>>
>> On Thu, Oct 17, 2019 at 8:14 PM sotiris moustogiannis <
>> soto...@outlook.com> wrote:
>>
>>> I want to make custom function because i want to take one result from 2
>>> different models (inner join), and i dont find a way to use 2 models in my
>>> listview class (generic)
>>>
>>> On Friday, October 18, 2019 at 6:03:18 AM UTC+3, sotiris moustogiannis
>>> wrote:

 I read that you can't use the def get_queryset into a function but only
 in a generic class view, so maybe the def get_queryset function does not
 run. I want to  make my own custom function and i want to find a way to get
 self parameter in my function. Thanks a lot.

 On Friday, October 18, 2019 at 5:49:48 AM UTC+3, jlgimeno71 wrote:
>
> wd,
>
> The problem here is that when you're creating the context, the name
> 'result' is not defined. When the get_queryset() method returns, the 
> result
> name goes out of scope.  My guess that's why you're getting a NameError.
>
> If that's not it, I would suggest cutting and pasting the traceback
> and showing us the actual code (with line numbers if you have them). It
> will help us diagnose the problem.
>
> -Jorge
>
> On Thu, Oct 17, 2019 at 7:25 PM wd  wrote:
>
>> oh ,sorry my mistake. But I think the error is pretty clear ...
>>
>> On Fri, Oct 18, 2019 at 10:23 AM wd  wrote:
>>
>>> Dude, you need to indent at the line include 'context' ... it's a
>>> beginners  problem...
>>>
>>> On Fri, Oct 18, 2019 at 10:14 AM sotiris moustogiannis <
>>> soto...@outlook.com> wrote:
>>>
 I have an error: name 'result' is not defined



 def search(request):

 def get_queryset(self):
 query = self.request.GET.get('q')
 result = Shops.objects.filter(Q(city=query))

 return result

 context={
 'shops' : result,
 }

 return render(request, 'booking/search.html',context)





 --
 You received this message because you are subscribed to the Google
 Groups "Django users" group.
 To unsubscribe from this group and stop receiving emails from it,
 send an email to django...@googlegroups.com.
 To view this discussion on the web visit
 https://groups.google.com/d/msgid/django-users/543debc7-d517-4a7a-a9b8-f3fc7c7cc60d%40googlegroups.com
 
 .

>>> --
>> You received this message because you are subscribed to the Google
>> Groups "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it,
>> send an email to django...@googlegroups.com.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/django-users/CABexzmhZtCXQRWB7S%3DL8S3B2rzmnbi3Raan1MFKW1asbSoShqg%40mail.gmail.com
>> 
>> .
>>
> --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django users" group.
>>> To unsubscribe from this group and stop receiving emails from it, send
>>> an email to django...@googlegroups.com.
>>> To view this discussion on the web visit
>>> https://groups.google.com/d/msgid/django-users/dcd65a19-628b-4ac9-9f60-d8d4b726d945%40googlegroups.com
>>> 
>>> .
>>>
>> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/c602853d-b5c7-4105-b77c-95ed37ac67ea%40googlegroups.com
> 
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop 

Re: Should there be separate django app for every user type in a django project?

2019-10-13 Thread Joalbert Palacios
I think you don't need several apps for each user type. You have different
ways to approach it, one could be used with permisology policy for each
model and each user type in the Django app, other one could be managing the
policies by yourself.

I suggest to search in Google a entry in the blog
simpleisbetterthancomplex.com ir read documentation in django for further
details.

I hope this helps.



On Sun, Oct 13, 2019, 8:33 PM test user  wrote:

> Hi,
>
> I have got multiple user types(around 4 to 5) in my Django project. Should
> i make separate Django app for each user type? Each user type will have
> different interface after they log into the website.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/f7dc3b18-ab79-42ea-9ba2-7d3b2b8187fb%40googlegroups.com
> 
> .
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAEtK16GgLSyTkrzW9CKDirgVz5L4tUr1tPne%3DTJAKowrVAZw0g%40mail.gmail.com.