Re: web page blank

2022-02-04 Thread Alex Dénho
Thanks

Le mer. 2 févr. 2022 à 13:37, kka kar  a écrit :

> I recreated the project and changed the view function to the below, and it
> now works fine for me:
>
> def home(request):
> context = {
> 'posts': post
> }
> return render(request, 'home.html', context)
>
> On Wednesday, February 2, 2022 at 8:23:46 AM UTC devfem...@gmail.com
> wrote:
>
>> Is it working fine for you?
>>
>>
>> If not url blog/home.html?
>>
>> On Wed, Feb 2, 2022, 08:08 Sebastian Jung  wrote:
>>
>>> Hello,
>>>
>>> Please try:
>>>
>>> context = {
>>> 'posts': post
>>> }
>>>
>>> 'Delvin Alexander' via Django users 
>>> schrieb am Mi., 2. Feb. 2022, 06:59:
>>>
 Hello everyone,

 I am currently following a django tutorial regarding applications. I
 have followed through completely but for some reason, when I run server, i
 incur no errors but the web page is blank. Why would this be?

 Here is what is not displayed:

 from my Home.html file:
 
 
 
 
 
 
 {% for post in posts %}
 {{ post.title }}
 By {{ post.author }} on {{ post.date_posted}}
 {{ post.content }}
 {% endfor %}

 
 

 from my views.py file:
 from django.shortcuts import render

 post = [
 {
 'author': 'CoreyMS',
 'title': 'Blog Post',
 'content': 'First Post Content',
 'date_posted': 'August 27, 2018'
 },
 {
 'author': 'Jane Doe',
 'title': 'Blog Post 2',
 'content': 'Second Post Content',
 'date_posted': 'August 28, 2018'
 }
 ]

 def home(request):
 context = {
 'post': post
 }
 return render(request, 'blog/home.html', context)

 def about(request):
 return render(request, 'blog/about.html')

 My urls.py:
 from django.urls import path
 from . import views

 urlpatterns = [
 path('', views.home, name='blog-home'),
 path('about/', views.about, name='blog-about'),
 ]


 --
 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...@googlegroups.com.
 To view this discussion on the web visit
 https://groups.google.com/d/msgid/django-users/e9b557a6-403b-46ce-bc18-8d19b0091f2an%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...@googlegroups.com.
>>>
>> To view this discussion on the web visit
>>> https://groups.google.com/d/msgid/django-users/CAKGT9mzFaC4Eq9B_76nb0N2%2BRW-%2BNkbLMdfJT0Vph2qWuGefOw%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-users+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/c2f8ef77-d0ef-4868-8680-0314442952f9n%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/CAKvw4qy5WGaOaSPxZp27nZH-jFZps4nJreNE29w%3DgDaGNAJyPg%40mail.gmail.com.


ArrayAgg and Limits

2022-02-04 Thread Mohammed Ali Zubair
Is it possible to limit the results of array_agg of postgres to a certain 
number of results? If not how can I go about implementing my own aggregate 
function to achieve this?

-- 
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/f3516c10-7158-4c12-921b-3845e82a5f17n%40googlegroups.com.


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

2022-02-04 Thread Joalbert Palacios
In debug mode looks like, create a new app using your idea about a possible 
mistake in setting without django-storages works perfectly but with this 
one crash with the exception below. Trying to fix it but does not look 
clear which line in django-storages has the issue.

SuspiciousFileOperation at /admin/dummyapp/country/add/Detected path 
traversal attempt in 
'/home/joalbert/Documents/test/dummy/media/country/images/us_bP4iy1J.png'
Request Method:
POST
Request URL:
http://localhost:8000/admin/dummyapp/country/add/
Django Version:
3.2.12
Exception Type:
SuspiciousFileOperation
Exception Value:
Detected path traversal attempt in 
'/home/joalbert/Documents/test/dummy/media/country/images/us_bP4iy1J.png'
Exception Location:
/home/joalbert/.local/lib/python3.8/site-packages/django/core/files/utils.py, 
line 18, in validate_file_name
Python Executable:
/usr/bin/python3
Python Version:
3.8.10
Python Path:
['/home/joalbert/Documents/test/dummy', '/usr/lib/python38.zip', 
'/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', 
'/home/joalbert/.local/lib/python3.8/site-packages', 
'/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages']

Environment:


Request Method: POST
Request URL: http://localhost:8000/admin/dummyapp/country/add/

Django Version: 3.2.12
Python Version: 3.8.10
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
* 'storages',*
 'dummyapp']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File 
"/home/joalbert/.local/lib/python3.8/site-packages/django/core/handlers/exception.py",
 
line 47, in inner
response = get_response(request)
  File 
"/home/joalbert/.local/lib/python3.8/site-packages/django/core/handlers/base.py",
 
line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File 
"/home/joalbert/.local/lib/python3.8/site-packages/django/contrib/admin/options.py",
 
line 616, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
  File 
"/home/joalbert/.local/lib/python3.8/site-packages/django/utils/decorators.py", 
line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
  File 
"/home/joalbert/.local/lib/python3.8/site-packages/django/views/decorators/cache.py",
 
line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
  File 
"/home/joalbert/.local/lib/python3.8/site-packages/django/contrib/admin/sites.py",
 
line 232, in inner
return view(request, *args, **kwargs)
  File 
"/home/joalbert/.local/lib/python3.8/site-packages/django/contrib/admin/options.py",
 
line 1657, in add_view
return self.changeform_view(request, None, form_url, extra_context)
  File 
"/home/joalbert/.local/lib/python3.8/site-packages/django/utils/decorators.py", 
line 43, in _wrapper
return bound_method(*args, **kwargs)
  File 
"/home/joalbert/.local/lib/python3.8/site-packages/django/utils/decorators.py", 
line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
  File 
"/home/joalbert/.local/lib/python3.8/site-packages/django/contrib/admin/options.py",
 
line 1540, in changeform_view
return self._changeform_view(request, object_id, form_url, 
extra_context)
  File 
"/home/joalbert/.local/lib/python3.8/site-packages/django/contrib/admin/options.py",
 
line 1586, in _changeform_view
self.save_model(request, new_object, form, not add)
  File 
"/home/joalbert/.local/lib/python3.8/site-packages/django/contrib/admin/options.py",
 
line 1099, in save_model
obj.save()
  File 
"/home/joalbert/.local/lib/python3.8/site-packages/django/db/models/base.py", 
line 739, in save
self.save_base(using=using, force_insert=force_insert,
  File 
"/home/joalbert/.local/lib/python3.8/site-packages/django/db/models/base.py", 
line 776, in save_base
updated = self._save_table(
  File 
"/home/joalbert/.local/lib/python3.8/site-packages/django/db/models/base.py", 
line 881, in _save_table
results = self._do_insert(cls._base_manager, using, fields, 
returning_fields, raw)
  File 
"/home/joalbert/.local/lib/python3.8/site-packages/django/db/models/base.py", 
line 919, in _do_insert
return manager._insert(
  File 
"/home/joalbert/.local/lib/python3.8/site-packages/django/db/models/manager.py",
 
line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
  File 
"/home/joalbert/.local/lib/python3.8/site-packages/django/db/models/query.py", 
line 1270, in _insert
return query.get_compiler(using=usi

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

2022-02-04 Thread Jacob Greene
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,
>>> 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

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"] ="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