Tuesday, November 30, 2021

return or not from super().method(*args, **kwargs)

Hi django-users,

I have a a question that I don't know where to send. Since it happened
programming in Django and I usually read this list I thought of sending
it here. I would like to ask if someone has strong feelings or if I
have missed some styling documentation.

This could be a generic Python styling question when re-implementing a
method of a base class. The example below is for models.Model.

Let's say that you had a model such as:

class Person(models.Model):
name = models.CharField(max_length=100)

def save(self, *args, **kwargs):
# some things...

# Question: do you do:
super().save(*args, **kwargs)

# or do you:
return super().save(*args, **kwargs)

Currently Model.save() returns None.

My thoughts:
-"return super().save(*args, **kwargs)":
-Good: if some day the base class changes and starts returning
something: the sub-class is forward-compatible :-)
-Good: less thinking when implementing the derived method: just do the
return always instead of having to check the base class method
-Bad: a reader might assume that Person.save() returns a value (instead of None)
-?: I haven't looked yet if I could add type hints for the return value of the the sub-class method saying "same as the base class".

-"super().save(*args, **kwargs)":
-Good: it's clear for the reader that nothing is returned
-Easy to do the type hints "-> None" if used in the project

Any thoughts? What would you prefer to see?

Currently I tend to go for the "super().save(*args, **kwargs)" (no
unnecessary return) as done in the Django documentation and to be
explicit in the present (it doesn't return anything)... but I have my
own doubts :-)

Part of this happened when I was reading some code and I thought that I
was in a "save()" for a form but I was in the model. For the form I need
to not forget the "return".

Thanks for any thoughts / comments :-)

Cheers,

--
Carles Pina i Estany
https://carles.pina.cat

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20211130221344.GA15295%40pina.cat.

Re: Django help needed URGENTLY!!!!

-----BEGIN PGP PUBLIC KEY BLOCK-----

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
BHO6KilQ+QLzSektD8IpHM7tR6P+5PP6AQ==
=NePe
-----END PGP PUBLIC KEY BLOCK-----On 30/11/2021 02.25, Kay TV wrote:
> Hi everyone.

First of all, instead of a generic subject and screaming things like
urgent. Try to write a more descriptive subject. It will increase the
chances of someone being willing to help you.

> Can anyone please help. I have a Django project which i want to
> distribute as a Windows executable file. What do I do please?
>

You need to be more specific. It should be simple enough to create a
self-extracting archive, but I doubt that's what you mean or is it?

Kind regards,

Kasper Laudrup

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/7948b0f3-18a0-2cfe-b16c-a29ae091238e%40stacktrace.dk.

Monday, November 29, 2021

Issue in rendering of Inline forms on Django Admin site

Good evening,
I am encountering a weird bug when rendering Inline forms on the "Add" view of a ModelAdmin.

Here is a minimum example with Django version 2.2.4

- - - - - - -

in models.py:

class MyModel(models.Model):
text = models.CharField(max_length=100)

class RelatedModel(models.Model):
parent = models.ForeignKey(MyModel, null=False, on_delete=models.CASCADE)
number = models.DecimalField(decimal_places=2, max_digits=10, null=False, blank=False)

in admin.py:
class RelatedModelInlineTabular(admin.TabularInline):
model = RelatedModel
show_change_link = False
fields = ("number", )

class TestMyModelCreate(admin.ModelAdmin):
fields = ['text', ]
inlines = [RelatedModelInlineTabular]

admin.site.register(MyModel, TestMyModelCreate)

Steps to replicate:
  • Login to django admin website
  • open the "add" view for MyModel (i.e. navigate to the list of Models and click on the "Add new" button

Expected result:
The form displays an empty text field. Below that, an Inline form is displayed with 3 empty rows for potential related instances of RelatedModel

Actual result:
The Inline form is displayed twice, each instance with its own 3 empty rows, as if I had specified it twice.

- - - - - -
I attach screenshots of the actual page ( Discount is the related Model). Please note that I get the same result with both StackedInline and TabularInline.



Am I making some trivial error here that could explain what's happening? Or is this is a known bug? Thank you in advance to anyone that will help.

Best regards
*  *  *  *  *
Andrea Arighi ~ Software Developer
Please consider the environment before printing this email

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAJzUX%3D68ejwz2Q0Lwvarw-hA%3DV5xsKfL%3D%2BHrsLzuHDkF2_ApmA%40mail.gmail.com.

Re: django@googlegroups.com

Why would you need to use blockchain technology, other than to simply check a checkbox and use a buzz word?

- Benjamin



On Nov 29, 2021, at 1:37 AM, Bernard Mallala <bernard@autofyle.com> wrote:

This is a very open ended comment but I will take a stab at it.
To build a blood bank management solution, you will need to dabble in supply chain and leverage blockchain to uniquely track each transfusion through the supply chain, to the bank and delivery to the recipient vein.
This is a big and expensive endeavor and I would recommend building such as solution only if you have a paying customer or strategic partner.
For reference, IBM has such a solution for their clients, Canada's blood system is another good example, and various ministries of health also leverage similar systems. Not all countries have such and there is opportunity and need. Research "vein to vein" to learn more.

On Sunday, November 28, 2021 at 9:20:49 AM UTC-7 asghedom...@gmail.com wrote:
i want to develop blood bank management system in django what can you help me

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5632ef97-8761-49c3-bc01-61981a6cccacn%40googlegroups.com.

Re: Developing django apps in jupyter

Hi, I am using the free version of Paycharm.
VS code is also good and is smaller than Paycharm.

On Mon, Nov 29, 2021 at 4:53 PM 'MH' via Django users <django-users@googlegroups.com> wrote:
Hi everyone

I have built a few django apps, but on a very basic level and only for my own usage. Little helpers for self management. So far I just used vi(m).

Now I tried out jupyter for the first time. Looks great and thanks to a few links from Google I could also load the django kernel in jupyter. Still I am not sure how to use juypter in order to develop django apps. Is this making sense to you? I either have one of those demonstration-/documentation-oriented notebooks or I have a plain py file as usual in django apps.

My two questions are:
1. Do you use juypter for django development?
2. If not, which editor or free IDE do you use?

Best regards
M

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/32085ce1-4bdc-4dfe-a031-9e4d6b15c9abn%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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAO-vjEQ1Z-NPsTT_nQkyrX272qOi81q%3Dkq3DmcO1GVTMhiUb4w%40mail.gmail.com.

Developing django apps in jupyter

Hi everyone

I have built a few django apps, but on a very basic level and only for my own usage. Little helpers for self management. So far I just used vi(m).

Now I tried out jupyter for the first time. Looks great and thanks to a few links from Google I could also load the django kernel in jupyter. Still I am not sure how to use juypter in order to develop django apps. Is this making sense to you? I either have one of those demonstration-/documentation-oriented notebooks or I have a plain py file as usual in django apps.

My two questions are:
1. Do you use juypter for django development?
2. If not, which editor or free IDE do you use?

Best regards
M

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/32085ce1-4bdc-4dfe-a031-9e4d6b15c9abn%40googlegroups.com.

Sunday, November 28, 2021

Re: django@googlegroups.com

This is a very open ended comment but I will take a stab at it.
To build a blood bank management solution, you will need to dabble in supply chain and leverage blockchain to uniquely track each transfusion through the supply chain, to the bank and delivery to the recipient vein.
This is a big and expensive endeavor and I would recommend building such as solution only if you have a paying customer or strategic partner.
For reference, IBM has such a solution for their clients, Canada's blood system is another good example, and various ministries of health also leverage similar systems. Not all countries have such and there is opportunity and need. Research "vein to vein" to learn more.

On Sunday, November 28, 2021 at 9:20:49 AM UTC-7 asghedom...@gmail.com wrote:
i want to develop blood bank management system in django what can you help me

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5632ef97-8761-49c3-bc01-61981a6cccacn%40googlegroups.com.

Saturday, November 27, 2021

Display api in particular format

Can anyone please help me with this? As I want to display the api data in this format.

------------------------
Thanks and Regards ,
Sapna Agrahari

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFx8_xf5d6r5cTv4i9OZyoZ2Y9_aJU9UgSNXs_ahKdhUVNQ1FQ%40mail.gmail.com.

Wednesday, November 24, 2021

Learn more about our updated Terms of Service

amkailamartinez@gmail.com

On January 5, 2022, we're making some changes to our Terms of Service. These changes won't affect the way you use Google services, but they'll make it easier for you to understand what to expect from Google — and what we expect from you — as you use our services.

You can review the new terms here. We've also provided a summary of the key changes. At a glance, here's what this update means for you:

  • More clarity on what you can expect from Google and what we expect from you: We're providing more examples to describe the mutually respectful conduct that we expect from all our users. We're also providing more transparency about how we develop, improve, and update our digital content, services, and goods – including more detail about the reasons we make changes and legally-required updates, the advanced notice we provide to you, and your right to withdraw from your contract with us.
  • Legal guarantee: We're summarizing the legal guarantees that you receive under EEA consumer laws when you use our digital content, services, and goods.
  • Withdrawal right: We're providing information about your legal right to withdraw from the terms within 14 days of agreeing to them if you're a consumer based in the European Economic Area (EEA). We're also including a copy of the EU Model Instructions on Withdrawal in case you want to exercise that right.
  • Additional definitions: We're adding more explanatory text to help you understand certain legal concepts that we refer to in our terms, including "commercial guarantee", "legal guarantee", and "lack of conformity".
  • Improved readability: While our terms remain a legal document, we've done our best to make them easier to understand, including reorganizing some topics so that they're easier to find.

If you use Family Link to manage a Google Account for someone else, please take some time to talk to them about these changes.

Thank you for using Google!

Google Ireland Limited, Gordon House, Barrow Street, Dublin 4, Ireland

You have received this email to update you about important changes to Google's Terms of Service.

RE: Permissions Model Inefficiency Killing DB

Do you think this is a consequence of permission complexity?

I have instinctively avoided individual permissions for purely management reasons and stuck to user membership of auth groups (roles) and given permissions exclusively to groups.

That postpones lookups to when they are needed.

I can't imagine how difficult it would be to unravel your scenario and impose group permissions.

Sorry I can't help with your actual question.

Cheers

Mike



--
(Unsigned mail from my phone)



-------- Original message --------
From: Ryan Skadberg <skadz@skadz.com>
Date: 25/11/21 07:35 (GMT+10:00)
To: Django users <django-users@googlegroups.com>
Subject: Permissions Model Inefficiency Killing DB

Hi All -

  Running Django 2.2.24 (Yes, I know, we are working on moving to 3.2)

  I've noticed some stalls in startup and finally have tracked it down.  It appears when permissions are imported, it checks EVERY user for permissions, NOT just the ones in the user_user_permissions table.  When you have 30k users in your DB this causes at least 60k SQL calls on startup.

They all look something like this:

2021-11-24 19:04:46.725 UTC [39] LOG:  duration: 0.344 ms  statement: SELECT "auth_group"."id", "auth_group"."name" FROM "auth_group" INNER JOIN "user_groups" ON ("auth_group"."id" = "user_groups"."group_id") WHERE "user_groups"."customuser_id" = 27345
2021-11-24 19:04:46.728 UTC [39] LOG:  duration: 0.379 ms  statement: SELECT "auth_permission"."id", "auth_permission"."name", "auth_permission"."content_type_id", "auth_permission"."codename" FROM "auth_permission" INNER JOIN "user_user_permissions" ON ("auth_permission"."id" = "user_user_permissions"."permission_id") INNER JOIN "django_content_type" ON ("auth_permission"."content_type_id" = "django_content_type"."id") WHERE "user_user_permissions"."customuser_id" = 27345 ORDER BY "django_content_type"."app_label" ASC, "django_content_type"."model" ASC, "auth_permission"."codename" ASC

 I have 677 rows in user_user_permissions with a minimum customuser_id of 0 and a max of 27346.  When I start up my tests, instead of looking at the 677 users that have permissions in the user_user_permissions table, it checks all 27346.  As there is nothing in the table for them, this is super super inefficient.

It appears that the SQL is doing something like:

select id from public.user

And really should be doing something like this to minimize SQL calls:

select id from public.user where id in (select customuser_id from user_user_permissions);


which in my case would be 1/30th of the calls, which would be HUGE for startup (60k to 2k or so).

Can anyone either explain why this is happening or a way to work around it or if I should file a bug?

Thanks!
Ryan

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/0d5aa4db-ccd7-482a-8530-1cc8d76bbcc0n%40googlegroups.com.

Permissions Model Inefficiency Killing DB

Hi All -

  Running Django 2.2.24 (Yes, I know, we are working on moving to 3.2)

  I've noticed some stalls in startup and finally have tracked it down.  It appears when permissions are imported, it checks EVERY user for permissions, NOT just the ones in the user_user_permissions table.  When you have 30k users in your DB this causes at least 60k SQL calls on startup.

They all look something like this:

2021-11-24 19:04:46.725 UTC [39] LOG:  duration: 0.344 ms  statement: SELECT "auth_group"."id", "auth_group"."name" FROM "auth_group" INNER JOIN "user_groups" ON ("auth_group"."id" = "user_groups"."group_id") WHERE "user_groups"."customuser_id" = 27345
2021-11-24 19:04:46.728 UTC [39] LOG:  duration: 0.379 ms  statement: SELECT "auth_permission"."id", "auth_permission"."name", "auth_permission"."content_type_id", "auth_permission"."codename" FROM "auth_permission" INNER JOIN "user_user_permissions" ON ("auth_permission"."id" = "user_user_permissions"."permission_id") INNER JOIN "django_content_type" ON ("auth_permission"."content_type_id" = "django_content_type"."id") WHERE "user_user_permissions"."customuser_id" = 27345 ORDER BY "django_content_type"."app_label" ASC, "django_content_type"."model" ASC, "auth_permission"."codename" ASC

 I have 677 rows in user_user_permissions with a minimum customuser_id of 0 and a max of 27346.  When I start up my tests, instead of looking at the 677 users that have permissions in the user_user_permissions table, it checks all 27346.  As there is nothing in the table for them, this is super super inefficient.

It appears that the SQL is doing something like:

select id from public.user

And really should be doing something like this to minimize SQL calls:

select id from public.user where id in (select customuser_id from user_user_permissions);


which in my case would be 1/30th of the calls, which would be HUGE for startup (60k to 2k or so).

Can anyone either explain why this is happening or a way to work around it or if I should file a bug?

Thanks!
Ryan

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/0d5aa4db-ccd7-482a-8530-1cc8d76bbcc0n%40googlegroups.com.

def post in ListView

Hi everyone,

Is there anything dangerous about this?
class ItemList(ListView):
    model = Item
    def post(self, request, *args, **kwargs):
        self.request.GET = self.request.POST
        return super().get(request, *args, **kwargs)

I want to use this to accept filtering parameters from a form in a list view template. This ListView also has a get_queryset which returns a filtered query based on the parameters

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/aa7a1392-e388-4727-b412-bd1329daa6c4n%40googlegroups.com.

Tuesday, November 23, 2021

Question for Upload images issue

Hi,
By using Vuejs, Axios and Django, we're uploading "multiple images" using Vuejs form in one upload/browse attempt. After uploading, the images are getting in a list and then the list of images names are stored into backend in ImageField.  The image names are saving into database but not saving into Media Folder. Here is snippet of the code.

Vuejs
```
  <label>
    <span>Files</span>
    <input type="file" multiple @change="handleFileUploads($event)" />
    <ul v-if="files.length">
      <li v-for="(name, i) in filesNames" :key="i">{{ name }}</li>
    </ul>
  </label>
  <div>
    <img v-for="image in images" :src="image" />
  </div>
  <br />
  <button v-on:click.prevent="submitForm">Submit</button>
```
Axiox
```
<script>
new Vue({
  el: '#app',
  data() {
    return {
      files: [],
      images: [],
    }
  },
  computed: {
    filesNames() {
      const fn = []
      for (let i = 0; i < this.files.length; ++i) {
        fn.push(this.files.item(i).name)

      }
      return fn
    }
  },
  methods: {
    handleFileUploads(event) {
      this.files = event.target.files;
      this.images = [...this.files].map(URL.createObjectURL);
    },
    submitFile() {
      let formData = new FormData();
      for (var i = 0; i < this.files.length; i++) {
        let file = this.files[i];
        formData.append('files[' + i + ']', file);
      }
     submitForm: function(){
                  let formData = new FormData();
                  const fna = []
                  for (let i = 0; i < this.files.length; ++i) {
                    fna.push(this.files.item(i).name)
                  }
                  console.log('fna');
                  console.log(fna);
            axios({
                method : "POST",
                url: "{% url 'service-ad' %}",
                headers: {'X-CSRFTOKEN': '{{ csrf_token }}',
                'Content-Type': 'multipart/form-data'},
                data : {
                "images": fna,
                },
              }).then(response => {
                    console.log('SUCCESS!!');
              }).catch(err => {
                    console.log('FAILURE!!');
              }); 
    }
  }
})
</script>
```
Where as in other case we have similar functionality of uploading  'multiple images' in one upload/browse attempt, but here, we are using HTML form and the images names are saved in database as well as in Media Folder.

Django
```
def servicevue(request):
    if request.method == "POST":
        data = json.loads(request.body)
        images = data['images']
        img_length = len(images)
        if img_length == 1:
            image_name = images[0]
            image_name2 = ''
        elif img_length == 2:
            image_name = images[0]
            image_name2 = images[1]
        else:
            image_name = ''
            image_name2 = ''

        savehotel = Hotel(
                          image=image_name,
                          image2=image_name2,
                          )
        savehotel.save()
        messages.success(request, """Your Ad is successfully posted.""")
        return JsonResponse(safe=False)
    return render(request, 'servicead.html')
```
So we are wondering what could be the issue. We hope our code is correctly implemented. Please help me out whether this is any way to unblock this issue?

Best regards,
Salima

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CABscGkRXhvC6zALxCXvQN6-DmB%2BxedTSWO8KrPS2Nih0imZtXA%40mail.gmail.com.

Monday, November 22, 2021

Re: Multiple Templates in single list view

Screenshot 2021-11-22 at 9.21.06 PM.png

On Monday, 22 November 2021 at 21:20:16 UTC+5:30 Trippy Samurai wrote:
Its done bro model is configured already i didn't just posted the models.py file

On Monday, 22 November 2021 at 21:18:12 UTC+5:30 ram.asf...@gmail.com wrote:
will update asap

On Mon, Nov 22, 2021 at 1:22 PM David Nugent <dav...@uniquode.io> wrote:
Well, there are several ways you can deal with that.

Probably easiest is to override get_template() and switch the template based on whatever type of ticket you're managing or you can change the value of self.template_name based on the request.

Or maybe you prefer a single template to deal with all cases with conditional blocks where appropriate.


Regards,
David

--
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.

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/211116cb-6012-4eb3-83f0-a11b79b7fecfn%40googlegroups.com.

Sunday, November 21, 2021

Re: Multiple Templates in single list view

What about the templates i have three different templates for as u can see in template_name in the above views ,how do i deal with it if i actualyl had one template the above could have worked.
On Monday, 22 November 2021 at 12:42:59 UTC+5:30 sutharl...@gmail.com wrote:
we can go like 

```

class Manager(...):
def get_context_data(self, **kwargs):
context = super() ....
context["open_tickets"] = Ticket.objects.filter(status="OPEN")
context["accepted_tickets"] = Ticket.objects.filter(status="ACCEPTED")
context["completed_tickets"] = Ticket.objects.filter(status="COMPLETED")
return context
```

On Mon, 22 Nov 2021 at 12:19, Trippy Samurai <someshkan...@gmail.com> wrote:
Hi Elena Thanks for the reply i have three different html pages to display open tickets closed tickets accepted tickets etc each of them have different ticket statuses i have them written in different views as above to display each type of ticket at different pages how can i combine all three in  a single view so that i dont repeat my logic in views.Is there a way to acheive all the three views writing in a single view?

On Monday, 22 November 2021 at 10:04:14 UTC+5:30 elena wrote:
Hi,

The problem is it's unclear what your question is. Can you be clearer about what outcome you're trying to achieve? 


---
Elena Williams
Github: elena


On Mon, 22 Nov 2021 at 15:20, Trippy Samurai <someshkan...@gmail.com> wrote:
Any one plz


On Sunday, 21 November 2021 at 15:09:39 UTC+5:30 Trippy Samurai wrote:
Hello,
I have different views for displaying different templates how do i write them into one single Listview so that i can take care of DRY


Screenshot 2021-11-21 at 3.08.58 PM.png

--
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/d86e1449-a17e-4e93-9dd2-1fae9a7e91d7n%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.

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a000369b-b20f-4737-9bdc-f913f5af0a08n%40googlegroups.com.

Saturday, November 20, 2021

Re: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

You can simply use (form.Modelform) if you are using django model form,
Or (forms.Form) if you are using html forms

On Sun, Nov 21, 2021, 07:48 Peter of the Norse <rahmcoff@gmail.com> wrote:
CommentForm inherits from both ModelForm and "forms".  I don't know what "forms" is, but PEP-8 says all classes should be capitalized.  If forms is a base class that has already defined Meta, then you need to have CommentForm's extend it.  So change the line to class Meta(forms.Meta):

On Oct 28, 2021, at 8:18 PM, Sabbir Hasan Munna <sabbirhasan2999@gmail.com> wrote:


<Annotation 2021-10-29 081743.png>

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f7d8a010-0f68-437c-b3df-ec99a4460aafn%40googlegroups.com.
<Annotation 2021-10-29 081743.png>

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/E4AE72BA-48B0-4AD8-9D63-4AE9663F7C10%40gmail.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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAO2Ykc4qRxn8%3DNaSCtdKE1GykCJLS0J%3DiNsGc33GC%2BQehM2-jQ%40mail.gmail.com.

choices = django background color

Mudar condicionalmente a cor de fundo da célula no django admin

Olá Preciso retornar uma lista de opcões do mysql, cada uma com uma cor. 


models.py

STATUS_CHOICES = (
        ('Pendente', format_html('<span><style="background-color:#ffcccc">Pendente</span>')),
        ('AGuardando', format_html('<span><style="background-color:#aaffcc">Aguardando</span>')),
        ('Resolvido', format_html('<span><style="background-color:#dddddd">Resolvido</span>')),
    )
status = models.CharField(max_length=10, choices=STATUS_CHOICES, blank=False, null=False)


Alguém pode me ajudar?

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/ec931086-d720-49db-89ea-7de06f3622e0n%40googlegroups.com.

Thursday, November 18, 2021

Asynchronous test always failing

Hello, 

I hope I am on the right place.
I want to write some test from my async view and I follow the documentation but it keeps failing.


this is my view:

```class Session(View):
""" Asynchronously get a session for a system."""

@classonlymethod
def as_view(cls, **initkwargs):
view = super().as_view(**initkwargs)
view._is_coroutine = asyncio.coroutines._is_coroutine # pylint: disable=protected-access
return view

async def get(self, request, **kwargs):
""" Async get list of session between two dates """

end_period: str = request.GET['end']
start_period: str = request.GET['start']
gcloud_id: str = request.GET['gcloud']
offset: int = int(request.GET.get('offset', 10))
page: int = int(request.GET.get('page', 1))
system_uuid: str = kwargs['uuid']

cache_id: str = f"session_{system_uuid}_{start_period}_{end_period}"
if cache.get(cache_id):
log_data = cache.get(cache_id)
else:
session_service: SessionService = SessionService(system_uuid, gcloud_id, start_period, end_period)
log_data: List[Dict[str, Union[str, pd.Timestamp]]] = await session_service.get_session()
cache.set(cache_id, log_data, timeout=60 * 60)

nb_page: int = math.ceil((len(log_data) / offset))
pagination: Pagination = Pagination(offset, nb_page)
pagination.page = page
return JsonResponse({'logs': log_data[pagination.start_limit:pagination.end_limit], 'nb_page': nb_page,
'page': pagination.page},
safe=False)```

the service called in here is actually getting some data from my postgres database.

here is my test, basically just following the doc:


```class SystemViewsTest(SystemSetUpTest):
async def test_get_session_detail(self):
uuid: str = '2265d534-5a62-426a-bc44-e17ebddabfb3'

console_gcloud_id = 'console-7ccbe2e157d6'
start_period = '2021-05-06'
end_period = '2021-05-07'
response = await self.async_client.get(
f'/v1/sessions/{uuid}?end={end_period}&start={start_period}&gcloud={console_gcloud_id}',
)
print(response)
self.assertEqual(response.status_code, 200)```

SystemSetUpTest is just a class I use to create System data (using the setUp method) for my test as it is related to many other models, it inherits from django.test import TestCase

but when I want to run my test I have this infinite stack trace saying that my db connection already closed, that another session is alredy using my db and something about the generator not stopping after throw()..

======================================================================
ERROR: test_get_session_detail (systems.tests.test_views.SystemViewsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/django/db/backends/base/base.py", line 237, in _cursor
    return self._prepare_cursor(self.create_cursor(name))
  File "/usr/local/lib/python3.8/dist-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/django/db/backends/postgresql/base.py", line 236, in create_cursor
    cursor = self.connection.cursor()
psycopg2.InterfaceError: connection already closed

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/asgiref/sync.py", line 223, in __call__
    return call_result.result()
  File "/usr/lib/python3.8/concurrent/futures/_base.py", line 437, in result
    return self.__get_result()
  File "/usr/lib/python3.8/concurrent/futures/_base.py", line 389, in __get_result
    raise self._exception
  File "/usr/local/lib/python3.8/dist-packages/asgiref/sync.py", line 292, in main_wrap
    result = await self.awaitable(*args, **kwargs)
  File "/app/systems/tests/test_views.py", line 15, in test_get_session_detail
    response = await self.async_client.get(
  File "/usr/local/lib/python3.8/dist-packages/django/test/client.py", line 908, in request
    self.check_exception(response)
  File "/usr/local/lib/python3.8/dist-packages/django/test/client.py", line 580, in check_exception
    raise exc_value
  File "/usr/local/lib/python3.8/dist-packages/asgiref/sync.py", line 482, in thread_handler
    raise exc_info[1]
  File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/exception.py", line 38, in inner
    response = await get_response(request)
  File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/base.py", line 233, in _get_response_async
    response = await wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python3.8/dist-packages/sentry_sdk/integrations/django/asgi.py", line 94, in sentry_wrapped_callback
    return await callback(request, *args, **kwargs)
  File "/app/systems/views/shift.py", line 114, in get
    log_data: List[Dict[str, Union[str, pd.Timestamp]]] = await session_service.get_session()
  File "/app/systems/services/session.py", line 73, in get_session
    await self.__vision_system_gcloud_id)
  File "/usr/local/lib/python3.8/dist-packages/async_property/base.py", line 37, in get_value
    return await self._fget(instance)
  File "/app/systems/services/session.py", line 57, in __vision_system_gcloud_id
    data = await self.__vision_data()
  File "/usr/local/lib/python3.8/dist-packages/asgiref/sync.py", line 444, in __call__
    ret = await asyncio.wait_for(future, timeout=None)
  File "/usr/lib/python3.8/asyncio/tasks.py", line 455, in wait_for
    return await fut
  File "/usr/local/lib/python3.8/dist-packages/asgiref/current_thread_executor.py", line 22, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/local/lib/python3.8/dist-packages/channels/db.py", line 13, in thread_handler
    return super().thread_handler(loop, *args, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/asgiref/sync.py", line 486, in thread_handler
    return func(*args, **kwargs)
  File "/app/systems/services/session.py", line 38, in __vision_data
    return System.objects.get_vision_conf_data(self.system_uuid)
  File "/app/systems/models/manager/manager.py", line 130, in get_vision_conf_data
    gcloud: List[str] = [data[0] for data in visions]
  File "/usr/local/lib/python3.8/dist-packages/django/db/models/query.py", line 280, in __iter__
    self._fetch_all()
  File "/usr/local/lib/python3.8/dist-packages/django/db/models/query.py", line 1324, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/usr/local/lib/python3.8/dist-packages/django/db/models/query.py", line 140, in __iter__
    return compiler.results_iter(tuple_expected=True, chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "/usr/local/lib/python3.8/dist-packages/django/db/models/sql/compiler.py", line 1124, in results_iter
    results = self.execute_sql(MULTI, chunked_fetch=chunked_fetch, chunk_size=chunk_size)
  File "/usr/local/lib/python3.8/dist-packages/django/db/models/sql/compiler.py", line 1167, in execute_sql
    cursor = self.connection.cursor()
  File "/usr/local/lib/python3.8/dist-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/django/db/backends/base/base.py", line 259, in cursor
    return self._cursor()
  File "/usr/local/lib/python3.8/dist-packages/django/db/backends/base/base.py", line 237, in _cursor
    return self._prepare_cursor(self.create_cursor(name))
  File "/usr/local/lib/python3.8/dist-packages/django/db/utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/usr/local/lib/python3.8/dist-packages/django/db/backends/base/base.py", line 237, in _cursor
    return self._prepare_cursor(self.create_cursor(name))
  File "/usr/local/lib/python3.8/dist-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/django/db/backends/postgresql/base.py", line 236, in create_cursor
    cursor = self.connection.cursor()
django.db.utils.InterfaceError: connection already closed

----------------------------------------------------------------------
Ran 1 test in 0.043s

FAILED (errors=1)
Destroying test database for alias 'default'...
/usr/local/lib/python3.8/dist-packages/django/db/backends/postgresql/base.py:304: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead.
  warnings.warn(
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/django/db/backends/utils.py", line 82, in _execute
    return self.cursor.execute(sql)
psycopg2.errors.ObjectInUse: database "test_django" is being accessed by other users
DETAIL:  There is 1 other session using the database.


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/django/db/backends/postgresql/base.py", line 302, in _nodb_cursor
    yield cursor
  File "/usr/local/lib/python3.8/dist-packages/django/db/backends/base/creation.py", line 298, in _destroy_test_db
    cursor.execute("DROP DATABASE %s"
  File "/usr/local/lib/python3.8/dist-packages/sentry_sdk/integrations/django/__init__.py", line 500, in execute
    return real_execute(self, sql, params)
  File "/usr/local/lib/python3.8/dist-packages/django/db/backends/utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/usr/local/lib/python3.8/dist-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/usr/local/lib/python3.8/dist-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python3.8/dist-packages/django/db/utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/usr/local/lib/python3.8/dist-packages/django/db/backends/utils.py", line 82, in _execute
    return self.cursor.execute(sql)
django.db.utils.OperationalError: database "test_django" is being accessed by other users
DETAIL:  There is 1 other session using the database.


During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 17, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python3.8/dist-packages/django/core/management/__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python3.8/dist-packages/django/core/management/__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python3.8/dist-packages/django/core/management/commands/test.py", line 23, in run_from_argv
    super().run_from_argv(argv)
  File "/usr/local/lib/python3.8/dist-packages/django/core/management/base.py", line 354, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/usr/local/lib/python3.8/dist-packages/django/core/management/base.py", line 398, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python3.8/dist-packages/django/core/management/commands/test.py", line 55, in handle
    failures = test_runner.run_tests(test_labels)
  File "/usr/local/lib/python3.8/dist-packages/django/test/runner.py", line 736, in run_tests
    self.teardown_databases(old_config)
  File "/usr/local/lib/python3.8/dist-packages/django/test/runner.py", line 674, in teardown_databases
    _teardown_databases(
  File "/usr/local/lib/python3.8/dist-packages/django/test/utils.py", line 313, in teardown_databases
    connection.creation.destroy_test_db(old_name, verbosity, keepdb)
  File "/usr/local/lib/python3.8/dist-packages/django/db/backends/base/creation.py", line 282, in destroy_test_db
    self._destroy_test_db(test_database_name, verbosity)
  File "/usr/local/lib/python3.8/dist-packages/django/db/backends/base/creation.py", line 298, in _destroy_test_db
    cursor.execute("DROP DATABASE %s"
  File "/usr/lib/python3.8/contextlib.py", line 162, in __exit__
    raise RuntimeError("generator didn't stop after throw()")
RuntimeError: generator didn't stop after throw()


I am very blocked by this, if you could give me some help I would be so grateful.

Thanks.
Julie 


--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/9a0754ee-e281-4363-a516-021983332acfn%40googlegroups.com.

Monday, November 15, 2021

Join Two fields during Import

Hello Team, 

I am importing a CSV file from the admin panel, during import I Want to Create a Unique ID by combing other three to four fields and storing it into the id column  how to combine columns during import of CSV or excel 


Thanks and Regards 

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/25165bc9-3143-4d83-83d4-16002943caefn%40googlegroups.com.

Sunday, November 14, 2021

Re: Question regarding organizing models

You can put a string with the name of a class that is yet to be defined in the ForeignKey.  https://docs.djangoproject.com/en/3.2/ref/models/fields/#foreignkey

In this case you would do

    created_by_id = models.ForeignKey("User", on_delete=models.DO_NOTHING)

On Sep 23, 2021, at 1:50 AM, Bhavin Shah <bhavinks.charlotte@gmail.com> wrote:

Hello,

Somewhat new to Django. I am trying to figure out the best way to define/organize models in Django app which have interdependent foreign keys. Simplified example below.


<Screenshot 2021-09-23 131449.png>

The issue I am struggling with is the following
  1. The above example produces an error as User class is defined after Company. Reversing the order would cause the same issue with reference to Company class in User class. What is the best way to handle this scenario ? I tried to set the created_by_id value post the User class declaration, but then the django migrations do not recognize/set the foreign key correctly.
  2. I also tried to split the models into multiple files as the app is expected to have several models with such interdependent foreign keys. However in that scenario, the import are causing an error due to circular references.
Any suggestions/guidance on best way to handle such models would be very much appreciated. Thank you.

Regards,

Bhavin Shah


Wednesday, November 10, 2021

Custom User App

Hi Django people. I request your thoughts on a custom user app. It's called 'TougshireAuth', but my intent is that it be renamed and hacked each time it is added to a new project. Otherwise it's not really a custom user

I would appreciate feedback. I'm an amateur who is ready to accept honest criticism. 

 Thank you

https://github.com/tougshire/tougshire

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/3ffb2e3f-c252-446c-a3ac-4377e7047190n%40googlegroups.com.

Tuesday, November 9, 2021

Django Admin Login

Hello,
We have a Django admin URL like https://abc.com/admin/, it's working fine however we want to proxy with a domain for admin url like https://abc.com/

We want to remove /admin from the URL.


Regards,
Abhishek

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/39bd9eb7-5002-4cc1-afd0-02eaa216da10n%40googlegroups.com.

Saturday, November 6, 2021

Re: Sanitize field from xss attacks in django models

My final solution :
bb.png

On Saturday, November 6, 2021 at 6:03:59 PM UTC+2 st...@jigsawtech.co.uk wrote:
Are you using the safe filter in your templates as otherwise that "attack" won't do anything but you are right that other XSS attack vectors can be used as per the example in the docs - https://docs.djangoproject.com/en/3.2/topics/security/#cross-site-scripting-xss-protection

If you are using safe then you could put a clean method on the form you are using to store the data in the first place to perform the validation/cleaning and if you wanted to go a step further and have places that update outside of forms then overload the save method of the class, put the custom validation in, then call super afterwards.

You could also look at django-bleach - https://pypi.org/project/django-bleach/

On Saturday, 6 November 2021 at 12:44:05 UTC omark...@gmail.com wrote:
hi all
i want to sanitize 'content' field from XSS attacks in django models
so i installed 'bleach' and used but script like "an <script>evil()</script> example" store as is (without sanitize script)
Note: i need bleach via function in models
Any idea ?
Thanks
bleach-Models.png

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/6da70f02-17ab-4e3f-8595-c6d492208abdn%40googlegroups.com.

Re: Sanitize field from xss attacks in django models

Are you using the safe filter in your templates as otherwise that "attack" won't do anything but you are right that other XSS attack vectors can be used as per the example in the docs - https://docs.djangoproject.com/en/3.2/topics/security/#cross-site-scripting-xss-protection

If you are using safe then you could put a clean method on the form you are using to store the data in the first place to perform the validation/cleaning and if you wanted to go a step further and have places that update outside of forms then overload the save method of the class, put the custom validation in, then call super afterwards.

You could also look at django-bleach - https://pypi.org/project/django-bleach/

On Saturday, 6 November 2021 at 12:44:05 UTC omark...@gmail.com wrote:
hi all
i want to sanitize 'content' field from XSS attacks in django models
so i installed 'bleach' and used but script like "an <script>evil()</script> example" store as is (without sanitize script)
Note: i need bleach via function in models
Any idea ?
Thanks
bleach-Models.png

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/ba551e69-e4be-4f96-9aee-01c58c54c09en%40googlegroups.com.

Sanitize field from xss attacks in django models

hi all
i want to sanitize 'content' field from XSS attacks in django models
so i installed 'bleach' and used but script like "an <script>evil()</script> example" store as is (without sanitize script)
Note: i need bleach via function in models
Any idea ?
Thanks
bleach-Models.png

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/65df3eee-f389-45cf-bb80-432fbcee40dbn%40googlegroups.com.

Wednesday, November 3, 2021

Re: Has anyone connected Django with AWS cognito in multi-tenant environment?


Heey Mike,

I was wondering if you found a solution to this?

Cheers,
Alex
Op vrijdag 1 februari 2019 om 04:21:43 UTC+1 schreef mike hennessy:
I'm new to Django, but not new to web development. I'm picking up Django/Python and I'm interested in setting up a SaaS multi-tenant application which leverages AWS's Cognito Identity/Infrastructure for scaling a SaaS Web application.

In googling this, I found very little. There was a thread about a wrapper for Cognito called warrant, but from what I read, it's no longer supported and it didn't seem stable.
Has anyone else gotten a multi-tenant Django app setup with AWS Cognito as your Identity/Authorization provider?

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/68579c8d-c796-40f1-b462-be7883b8d0d5n%40googlegroups.com.

Tuesday, November 2, 2021

Issue with django.forms.fields.FilePathField() and callable path

Hi,

First post here, so I don't know if it's the correct channel for this kind of issue.
Sorry if it's not.

Since v 3.0 we can set path attribute as a callable in a models.fields.FilePathField(),
as discussed here:
https://code.djangoproject.com/ticket/29529

and documented here:
https://docs.djangoproject.com/en/3.0/ref/models/fields/#django.db.models.FilePathField.path

The commit adding this feature can be found here:
https://github.com/django/django/commit/ef082ebb84f00e38af4e8880d04e8365c2766d34

I have an issue when I try to use django.forms.fields.FilePathField()
https://github.com/django/django/blob/stable/3.2.x/django/forms/fields.py#L1095
In the case where path is defined as a callable, and os.scandir(self.path) is called (as showed in  l.1126).
I 'm facing this explicit error:
"scandir: path should be string, bytes, os.PathLike, integer or None, not function"

If I override self.path with a pre-check similar to what it was done for the added feature
it seems to solve this issue.

```
...
path = self.path() if callable(self.path) else self.path
for f in os.scandir(path):
...
```

I don't know if it's a bug or if I miss something using models.fields.FilePathField() and django.forms.fields.FilePathField()

--
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+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b554a6eb-4978-428f-93b4-324a382557f0n%40googlegroups.com.