Weird issue with a form

2024-03-19 Thread 'Simon Connah' via Django users
I've been scratching my head over this one.

I have a user registration form but when I submit data on it and it always 
returns a 404 (it wants to go to the /users/accounts/ URL) but there are no 
URLs there. It initially went to /user/ but I created the view it was looking 
for but it just then moved to /user/accounts/.

I have added the get_success_url to point to the correct URL using reverse but 
even that doesn't work. Can someone help me out with this please?

Thank you.

Simon.

-- 
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/DuQl41jFoSkfZGUn35r4DdcARH3iV1InUZ5sozg4Jg4EfJ1tQPYGcC7WVs0Pr8UzyLtYWDXp5TiS0rBzC2QCRjXbSoR3bWwLRIbnK7f8bqA%3D%40protonmail.com.


signature.asc
Description: OpenPGP digital signature


Registration form in template

2024-03-17 Thread 'Simon Connah' via Django users
I have a register user template with a form which works well but I have a 
problem where there is lots of other text next to the form elements such as 
password length and what characters need to go in a password. Is their a 
reasonable way to hide that text or do I need to do it with JavaScript?

Thank you.

Simon.

-- 
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/xepYvHchH7kpHYeaYe7ByePm8VQYSjgIEzyGjSKDhOcAOhbh7j1vLmwSgLEgC5kkq-wYMOHjPM7--mLSu9w22I_BT9A-sQjZgTxVi9RR8IM%3D%40protonmail.com.


signature.asc
Description: OpenPGP digital signature


Strange bug with Firefox

2023-10-14 Thread 'Simon Connah' via Django users
Hi,

I have a strange issue that affects the latest stable version of Firefox and 
the latest Firefox Developer Edition as well. I'm making a custom user and am 
just setting all the forms up. I can login with the user and when I go to the 
password change form it is displayed correctly in Firefox but if I right click 
and click view source it shows a completely different form. On the other hand 
when I use Chrome and Chrome Developer Edition it shows the correct form and 
works exactly as intended. I've never seen anything like this before. I thought 
it was a problem with a browser extension so I removed them all (apart from 
Bitwarden) and completely cleared the history but none of that seems to have 
fixed the issue.

I'm at a loss. Can someone suggest what might be going on here? As I said it 
works fine in Chrome.

Simon.

-- 
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/zT7ozAu9QZo4FQ9XwBRiSTIc2ZwYA3eknb3Z-NJpibp6KIw3I9HmI0vOjhwtoyUux2qIu_Zqa3dI3ecbdkQKWdHmT86PsXQ378hsYbrp3gw%3D%40protonmail.com.


signature.asc
Description: OpenPGP digital signature


Re: Unit test to make sure correct template is returned from a specific URL?

2023-09-25 Thread 'Simon Connah' via Django users
Thank you very much!


--- Original Message ---
On Monday, September 25th, 2023 at 14:07, Muhammad Juwaini Abdul Rahman 
 wrote:


> Use assertTemplateUsed.
> https://docs.djangoproject.com/en/dev/topics/testing/tools/#django.test.SimpleTestCase.assertTemplateUsed
> 

> On Sun, 24 Sept 2023 at 22:37, 'Simon Connah' via Django users 
>  wrote:
> 

> > I can write a unit test which checks say the title on a page and compares 
> > it to a string but that is really prone to breakage. What I want to do 
> > instead is to check that the template that is returned by the URL is the 
> > same one that is expected in the unit test. Is there an easy way to do 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/MnCVU2YvJzLiFdMPPAVBwMY7SMosqS5wvqopbySnD05i7BTc375v_Bo5GB4VlUQSd5K2OwsiblAbxsfsz7in96L4_Ou4RTRm0jwVN3aMp54%3D%40protonmail.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/CAFKhtoRiz4mr69ZLu7_wCxVFXgjnvmAW3JCoYdcDrx%2Bwu94vrw%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/O_3E4w3kT2FE_XgQrWGfQFM_DcKq_syuWJ0eEuZ0zJfIPnZ6rzbF80z28SORLG9r7rik-evYNQhGnchpIcEDOP9zqIX9n_xOntOTHDAbv4M%3D%40protonmail.com.


signature.asc
Description: OpenPGP digital signature


Unit test to make sure correct template is returned from a specific URL?

2023-09-24 Thread 'Simon Connah' via Django users
I can write a unit test which checks say the title on a page and compares it to 
a string but that is really prone to breakage. What I want to do instead is to 
check that the template that is returned by the URL is the same one that is 
expected in the unit test. Is there an easy way to do 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/MnCVU2YvJzLiFdMPPAVBwMY7SMosqS5wvqopbySnD05i7BTc375v_Bo5GB4VlUQSd5K2OwsiblAbxsfsz7in96L4_Ou4RTRm0jwVN3aMp54%3D%40protonmail.com.


signature.asc
Description: OpenPGP digital signature


Re: Splitting views.py and urls.py into a directory rather than single files

2023-09-18 Thread 'Simon Connah' via Django users
Thank you! That got it working!


--- Original Message ---
On Monday, September 18th, 2023 at 13:34, Asim Sulehria 
 wrote:


> You can just directly declare an array of URL Patterns in a separate file and 
> then import that file in the url files you want to make the main urls file
> 

> On Mon, Sep 18, 2023 at 5:28 PM 'Simon Connah' via Django users 
>  wrote:
> 

> > Hi,
> > 

> > I have an app which has a lot of views and URLs and keeping them in just 
> > one file makes it really hard to manage because it is so long. I'd like to 
> > make a views and URLs folder which will allow me to break up views and URLs 
> > into different categories but I'm not sure what the best way to go about 
> > doing that is.
> > 

> > Can someone point me in the right direction please?
> > 

> > Thank you!
> > 

> > Simon.
> > 

> > --
> > 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/4svI0xN0uu53BvHzhG9Aa1qvI61v1qPlQOhkOLpaJPRXX1Jysfu-BOmrFlBsDOfHfKRHwTaXJNmKFApZ1W13jQLdpVvXQDEPdWq87T-ILR8%3D%40protonmail.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/CAPz57eGK6EXPGObGH5-ej3OPGvEmox%2BkR34xW3Eg1weWQug%3Dcw%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/d3_jwrhlaNWhn-_QfIOhopznbSi5o3e5tF5p-pF34iqaGFRRBVFScOg6PL95XWeJIBV6JpmQpXg0L0FcGNH9fjM5CItLGCZ8mIoJqNxEohU%3D%40protonmail.com.


signature.asc
Description: OpenPGP digital signature


Splitting views.py and urls.py into a directory rather than single files

2023-09-18 Thread 'Simon Connah' via Django users
Hi,

I have an app which has a lot of views and URLs and keeping them in just one 
file makes it really hard to manage because it is so long. I'd like to make a 
views and URLs folder which will allow me to break up views and URLs into 
different categories but I'm not sure what the best way to go about doing that 
is.

Can someone point me in the right direction please?

Thank you!

Simon.

-- 
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/4svI0xN0uu53BvHzhG9Aa1qvI61v1qPlQOhkOLpaJPRXX1Jysfu-BOmrFlBsDOfHfKRHwTaXJNmKFApZ1W13jQLdpVvXQDEPdWq87T-ILR8%3D%40protonmail.com.


signature.asc
Description: OpenPGP digital signature


Re: UpdateView and DeleteView

2023-08-27 Thread 'Simon Connah' via Django users
Will do! Thank you for your help.


--- Original Message ---
On Saturday, August 26th, 2023 at 19:30, Ruby  wrote:


> I'm glad it worked out,Consider using LoginRequiredMixin to ensure that 
> current user is authenticated before accessing the view.
> 

> 

> On Sat, Aug 26, 2023, 16:23 'Simon Connah' via Django users 
>  wrote:
> 

> > Thank you! That is very helpful.
> > 

> > 

> > --- Original Message ---
> > On Saturday, August 26th, 2023 at 14:07, Ruby  
> > wrote:
> > 

> > 

> > > You can simply set a test case using the built-in user passes test 
> > > (https://docs.djangoproject.com/en/4.2/topics/auth/default/#django.contrib.auth.decorators.user_passes_test)
> > > 

> > > On Sat, Aug 26, 2023, 11:20 'Simon Connah' via Django users 
> > >  wrote:
> > > 

> > > > I want to make sure that the only people who can update and delete an 
> > > > object are either superusers or the person that originally created them 
> > > > but I'm not sure how to go about doing it. Can someone point me in the 
> > > > right direction?
> > > > 

> > > > I'm not sure which method(s) to override.
> > > > 

> > > > Thank you.
> > > > 

> > > > 

> > 

> > --
> > 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/iT1fh6Btk96LInLjgvQNNIOeqZTL6TMcV5IbsAmfVdnR1ujaNPCbV_zhJeXr5o7emCHzK_BHnYDtyxQ1ZJVu7oDGqyDRkJirWsaGto-5bbA%3D%40protonmail.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/CAPUD46vM6PEJK4btLa-DCF8-VvExdnJ2OpzB0-Z6h03CVWvzOg%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/nMbslf1DnsTi42UmcaQZjvuHxoVVxPQapPAABp-aN5zswI1iBp61YS-J9IwUsRPyTb_87IJsY5rMktNRS9h6rY57zUjT_4fJzdSU8Dxuiec%3D%40protonmail.com.


signature.asc
Description: OpenPGP digital signature


Re: UpdateView and DeleteView

2023-08-26 Thread 'Simon Connah' via Django users
Thank you! That is very helpful.


--- Original Message ---
On Saturday, August 26th, 2023 at 14:07, Ruby  wrote:


> You can simply set a test case using the built-in user passes test 
> (https://docs.djangoproject.com/en/4.2/topics/auth/default/#django.contrib.auth.decorators.user_passes_test)
> 

> On Sat, Aug 26, 2023, 11:20 'Simon Connah' via Django users 
>  wrote:
> 

> > I want to make sure that the only people who can update and delete an 
> > object are either superusers or the person that originally created them but 
> > I'm not sure how to go about doing it. Can someone point me in the right 
> > direction?
> > 

> > I'm not sure which method(s) to override.
> > 

> > Thank you.
> > 

> > 

-- 
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/iT1fh6Btk96LInLjgvQNNIOeqZTL6TMcV5IbsAmfVdnR1ujaNPCbV_zhJeXr5o7emCHzK_BHnYDtyxQ1ZJVu7oDGqyDRkJirWsaGto-5bbA%3D%40protonmail.com.


signature.asc
Description: OpenPGP digital signature


UpdateView and DeleteView

2023-08-26 Thread 'Simon Connah' via Django users
I want to make sure that the only people who can update and delete an object 
are either superusers or the person that originally created them but I'm not 
sure how to go about doing it. Can someone point me in the right direction?

I'm not sure which method(s) to override.

Thank you.

-- 
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/RC50Lr8yv1j7M_cjvPHLpvLJ1RzHJP3QQaF5oQu4vAmfeijfMbprfVyyHGTIvg9udwKhe_-XcM9tYH9tRyaX-MDQauXKf3PiJbMOq2hEfj4%3D%40protonmail.com.


signature.asc
Description: OpenPGP digital signature


Building a modular app?

2023-04-02 Thread 'Simon Connah' via Django users
Hi,

I want to make a blogging platform and have a question about organising the 
project.

With my blog, I'll have the blog in one Django app and then have something like 
a forum in another app, along with additional functions in other apps. Also, 
I'd like to have a single-user system that uses AbstractUser (or 
AbstractBaseUser).

So how do all apps require my AbstractUser class for authentication, and then 
the other apps be added or removed based on what is needed for each site? I 
want to split auth from the rest project.

Thanks!

-- 
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/Y-FsxPZKXSIkwB9-Hj599nnwPVu5XWMbDlfv0HEnIu9cLNeRU5b-1egUTZv8vUpHVLc4uq6oP8pVEXlxW9PqVDQQMud9BJBdBn6V6EI0hEM%3D%40protonmail.com.


signature.asc
Description: OpenPGP digital signature


Possible bug with Q objects

2022-05-19 Thread Simon Van De Keer
ch individual item as 
well, hence *keeping individual items* that do have "123", but don't have 
"456" in their some_field value.

The expectation that both of the above queries would yield 1 result stems 
from the fact that if you would have a query with *Q(items__some_field="123") 
& Q(items__some_field="456") *or *Q(children__items__some_field="123") & 
Q(children__items__some_field="456") *(so no negation of the second Q 
object)*, *both Q objects' filter will be validating against each (and the 
same) item row. 
You could also argue that both queries should yield an empty result 
depending on how you interpret the filter statement.

I was wondering if this is intended and expected behaviour, or if this 
might be a bug with how the filter with Q objects is translated into an SQL 
query. 

Thanks,
Simon

-- 
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/0d1995ca-eb53-46ec-ab63-709565f86c9bn%40googlegroups.com.


Re: counting the same words within a song added by a user using Django

2021-07-05 Thread Simon Charette
If you're using a PostgreSQL you might want to look at using a tsvector 
column instead which will ignore stop words (the, or, of, ...) and map 
lexemes to their number of occurrence and position in the lyrics[0]. 
Assuming you were to index this column you'd be able to efficiently query 
it for existence of a particular lexeme or multiple of them.

You could then a union of all a user's song lyrics tsvector and even apply 
weights based on their listening frequency or their favorite songs.

Cheers,
Simon

[0] 
https://stackoverflow.com/questions/25445670/retrieving-position-and-number-of-lexem-occurrences-from-tsvector
Le lundi 5 juillet 2021 à 13:51:48 UTC-4, abubak...@gmail.com a écrit :

> Thank you Lalit bhai.
> it seems to be a solution.
> but what if I want to get the result for each single word rather than 
> single letter?
>
>
> On Mon, Jul 5, 2021 at 5:43 PM Lalit Suthar  wrote:
>
>> https://www.guru99.com/python-counter-collections-example.html
>> Counter can be helpful for this situation
>>
>> On Mon, 5 Jul 2021 at 17:07, DJANGO DEVELOPER  
>> wrote:
>>
>>> Hi there.
>>> I am developing a project based on adding songs to the user's library 
>>> and to the home page.
>>> other users can also purchase the songs like wise people do shopping on 
>>> eCommerce stores.
>>> *Problem:(Question)*
>>> The problem that I want to discuss here is that when a user adds a sing 
>>> through django forms, and now that song is added to the user's personal 
>>> library.
>>> now what I want to do is :
>>>
>>>
>>> *When the lyrics of a song are added as a record to the "Song" table, 
>>> the individual words in that song should be added to a 2nd table with their 
>>> frequency of usage within that song (so the words need to be counted and a 
>>> signal needs to be created).Also, when a user adds the song to his/her 
>>> personal library, all of the words from the song and their frequencies 
>>> within that song should be added to another table and associated with that 
>>> user.*
>>>
>>> how to count same word within a song? 
>>>
>>> can anyone help me here?
>>> your help would be appreciated.
>>>
>>> -- 
>>> 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/bc7bc37b-6f26-465c-b330-d275ab86b76an%40googlegroups.com
>>>  
>>> <https://groups.google.com/d/msgid/django-users/bc7bc37b-6f26-465c-b330-d275ab86b76an%40googlegroups.com?utm_medium=email_source=footer>
>>> .
>>>
>> -- 
>> 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/CAGp2JVHuos6d4%3D-_S%3DR-q8hq48Yzf%3D-xgmPziKEA2a3DYXAzbg%40mail.gmail.com
>>  
>> <https://groups.google.com/d/msgid/django-users/CAGp2JVHuos6d4%3D-_S%3DR-q8hq48Yzf%3D-xgmPziKEA2a3DYXAzbg%40mail.gmail.com?utm_medium=email_source=footer>
>> .
>>
>

-- 
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/c77799f3-1492-459a-8187-8d62985407b6n%40googlegroups.com.


Re: MODEL CONSTRAINT (based on two dates)

2021-06-30 Thread Simon Charette
Short answer is that you can't; constraints cannot spans across JOINs.

You might be able to use database triggers to emulate though.

Le lundi 28 juin 2021 à 08:08:27 UTC-4, ngal...@gmail.com a écrit :

> I have two models like this
>
> How can I make models constraint based on the dates as shows on image??
>

-- 
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/87cda97d-9fd8-4264-bb37-8d466eec0cb4n%40googlegroups.com.


Re: Filtering OR-combined queries

2021-05-03 Thread Simon Charette
Hello Shaheed,

I didn't look at your issue into details but since it involves exclude, 
subqueries, an queryset combination and only manifests itself on Django 3.2 
I wouldn't be surprised if it was related to some regressions in this area 
that are fixed in Django 3.2.1 which is meant to be released tomorrow

https://docs.djangoproject.com/en/3.2/releases/3.2.1/

Cheers,
Simon
Le vendredi 30 avril 2021 à 09:58:53 UTC-4, shahee...@gmail.com a écrit :

> Hi,
>
> On Fri, 30 Apr 2021 at 11:52, Sebastian Jung  wrote:
>
>> Take q for or Filterung:
>>
>>
>> https://stackoverflow.com/questions/6567831/how-to-perform-or-condition-in-django-queryset
>>
>
> Thanks for the response, but the OR is not the problem: it works just 
> fine. (FWIW, I used the "|" form rather than the Q() form because it is not 
> clear to me how one can express a .exclude() when using Q()). The problem 
> here is that the result of the OR cannot be reliably .filter()d. 
>
> As I tried to explain, I can see that in some cases, a .filter() of the 
> OR'd result does indeed add extra SQL to the query, whereas in others it 
> does not:
>
> qs_or_result.filter(a='b')
>
> This works for some values of "a" but not others, I can use this to 
> achieve the same effect:
>
> Buss.objects.filter(a='b').intersection(qs_or_result)
>
> though it is rather clumsy!!! FWIW, this is with Django 3.2. I'm inclined 
> to think this is a bug in the ORM, though I have not dived into the code to 
> track it down.
>
> Thanks, Shaheed
>  
>
>>
>>
>> Shaheed Haque  schrieb am Fr., 30. Apr. 2021, 02:43:
>>
>>> Hi,
>>>
>>> I have a query which ORs some selects on a single table together like 
>>> this:
>>>
>>> jurisdiction = 'aaa'
>>> qs = Buss.objects.filter(jurisdiction=jurisdiction)
>>> qs = qs | Buss.objects.filter(jurisdiction='xxx').exclude(name__in
>>> =qs.values_list('name', flat=True))
>>> qs = qs | Buss.objects.filter(jurisdiction='yyy').exclude(name__in
>>> =qs.values_list('name', flat=True))
>>>
>>> This seems to work just fine (and the raw SQL looks suitably 
>>> complicated):
>>>
>>> SELECT "paiyroll_buss"."id", "paiyroll_buss"."jurisdiction", 
>>> "paiyroll_buss"."name", "paiyroll_buss"."description" FROM "paiyroll_buss" 
>>> WHERE ("paiyroll_buss"."jurisdiction" = aaa OR 
>>> ("paiyroll_buss"."jurisdiction" = xxx AND NOT ("paiyroll_buss"."name" IN 
>>> (SELECT U0."name" FROM "paiyroll_buss" U0 WHERE U0."jurisdiction" = aaa))) 
>>> OR ("paiyroll_buss"."jurisdiction" = yyy AND NOT ("paiyroll_buss"."name" IN 
>>> (SELECT U0."name" FROM "paiyroll_buss" U0 WHERE (U0."jurisdiction" = aaa OR 
>>> (U0."jurisdiction" = xxx AND NOT (U0."name" IN (SELECT U0."name" FROM 
>>> "paiyroll_buss" U0 WHERE U0."jurisdiction" = aaa
>>>
>>> Now, if I post-filter qs using something other than "aaa" (the first 
>>> term above) like this:
>>>
>>>qs.filter('xxx)
>>>
>>> then the resulting SQL has an 'AND "paiyroll_buss"."jurisdiction" = xxx' 
>>> as one might expect. However, if I try to post-filter qs like this:
>>>
>>> qs.filter('aaa') # 'aaa' was the first term in the original trio of 
>>> clauses
>>>
>>> Then the formed SQL looks like this:
>>>
>>> SELECT "paiyroll_buss"."id", "paiyroll_buss"."jurisdiction", 
>>> "paiyroll_buss"."name", "paiyroll_buss"."description" FROM "paiyroll_buss" 
>>> WHERE ("paiyroll_buss"."jurisdiction" = aaa OR 
>>> ("paiyroll_buss"."jurisdiction" = xxx AND NOT ("paiyroll_buss"."name" IN 
>>> (SELECT U0."name" FROM "paiyroll_buss" U0 WHERE U0."jurisdiction" = aaa))) 
>>> OR ("paiyroll_buss"."jurisdiction" = yyy AND NOT ("paiyroll_buss"."name" IN 
>>> (SELECT U0."name" FROM "paiyroll_buss" U0 WHERE (U0."jurisdiction" = aaa OR 
>>> (U0."jurisdiction" = xxx AND NOT (U0."name" IN (SELECT U0."name" FROM 
>>> "paiyroll_buss" U0 WHERE U0.&qu

Re: Please help, I can't install django after a fresh installation of python 3.9 on windows 10

2021-03-19 Thread Simon Lankwagh

thank you all, i created a virtual environment and installed it.

On Thursday, March 18, 2021 at 9:20:56 PM UTC+1 ule...@gmail.com wrote:

> After installing python, you have to install PIP.
> To install PIP type in the following:
> python get-pip.py
>
> To install django tye in the following :
> pip install django
>
>
> Op donderdag 18 maart 2021 om 19:10:45 UTC+1 schreef 
> simmonshas...@gmail.com:
>
>> I have installed python 3.9 and selected 'add to path' during 
>> installation, i am now trying to install django 3.1.7 but it generates a 
>> lot of errors i can not understand, please what is the right way to setup 
>> django development on windows 10?
>
>

-- 
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/989c744a-4525-4fdf-93c9-935c004f2bd3n%40googlegroups.com.


Please help, I can't install django after a fresh installation of python 3.9 on windows 10

2021-03-18 Thread Simon Lankwagh
I have installed python 3.9 and selected 'add to path' during installation, 
i am now trying to install django 3.1.7 but it generates a lot of errors i 
can not understand, please what is the right way to setup django 
development on windows 10?

-- 
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/2b2ce7b0-3158-4ad8-8464-6b6b8e91e0ebn%40googlegroups.com.


Re: Questions about code coverage.

2020-11-09 Thread Simon Charette
Hello Chris,

> It looks like the gis files aren't covered. Is there any way to run tests 
and coverage on this code?

The tests for these files won't be run unless you run the suite with a GIS 
enabled database backend.

We do it on CI (https://djangoci.com/view/%C2%ADCoverage/) but you can do 
the same locally using django-docker-box 
(https://github.com/django/django-docker-box)

Best,
Simon

Le lundi 9 novembre 2020 à 10:38:13 UTC-5, chris...@gmail.com a écrit :

> Folks-
> I ran coverage and massaged the data a bit to get a better idea what areas 
> weren’t covered. Here is a Google Sheet 
> <https://docs.google.com/spreadsheets/d/19AnrBsmei5p-MYFiAhB4naTXdPYSZsAq_p1vgeLFNkE/edit?usp=sharing>
>  
> with the results, sorted by coverage% low-to-high.
>
> It looks like the gis files aren't covered. Is there any way to run tests 
> and coverage on this code?
> The other uncovered areas look to be primarily database specific 
> (Postgres, Oracle, etc.). Are these covered in an automated build somewhere 
> (e.g., in the CI system)?
>
> Thanks,
>
> Chris
>

-- 
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/5021544b-a66b-4858-8bc3-4d60622422f5n%40googlegroups.com.


Re: Replicating complex query with two dense_rank() functions using ORM

2020-11-04 Thread Simon Charette
This is unfortunately not possible to do through the ORM right now due to 
lack of support for filtering against window expressions[0]

Until this ticket is solved you'll have to rely on raw SQL.

Cheers,
Simon

[0] ticket https://code.djangoproject.com/ticket/28333

Le mercredi 4 novembre 2020 à 12:25:30 UTC-5, nhb.ra...@gmail.com a écrit :

> Hi,
>
> In Django queryset you can query PuzzleAnswer, filter by author (assuming 
> that is the user), order_by('created)' and return the created dates only: 
> values_list('created', flat=True). Then take the len() of that list and 
> check the [0] and [-1] entries for first and last date. The rest is date 
> math.
>
> In general I try to keep the number of database accesses as low as 
> possible. A pre-calculated answer takes less resources to present than 
> calculating this over and over again, especially if you have many users. So 
> you could do the above and store the result in a new table every time a new 
> PuzzleAnswer has been added for a user.
>
> Ramon
>
> Op woensdag 4 november 2020 om 05:34:22 UTC+1 schreef Brad Buran:
>
>> I have a "puzzle of the day" that users can answer. I track the puzzle of 
>> the day using the Puzzle model. I track the answers using the PuzzleAnswer 
>> model. I would like to calculate the number of consecutive puzzles a 
>> particular user (i.e., the author) gets right in a row. The current SQL I 
>> use that can calculate the start date of the streak, end date of the streak 
>> and the number of days in the streak. As you can see, it does a dens_rank 
>> over the puzzles (to count them in order), then does a join with the 
>> PuzzleAnswer, then does a second dense rank over the merged tables. I 
>> figured out how to use the DenseRank function in the Django ORM on the 
>> Puzzle manager, but I cannot figure out how to do the left join next. Any 
>> advice?
>>
>> SELECT min(s.id) AS id, 
>>count(s.date) AS streak, 
>>min(s.date) AS start_streak, 
>>max(s.date) AS end_streak, 
>>s.author_id 
>>   FROM ( SELECT dense_rank() OVER (ORDER BY ROW(pa.author_id, pr.rank)) 
>> AS id, 
>>pa.created AS date, 
>>(pr.rank - dense_rank() OVER (ORDER BY ROW(pa.author_id, 
>> pr.rank))) AS g, 
>>pa.author_id 
>>   FROM (( SELECT "POTD_puzzle".id, 
>>dense_rank() OVER (ORDER BY "POTD_puzzle".published) 
>> AS rank 
>>   FROM public."POTD_puzzle") pr 
>> JOIN public."POTD_puzzleanswer" pa ON ((pr.id = 
>> pa.puzzle_id))) 
>>  WHERE pa.correct) s 
>>  GROUP BY s.author_id, s.g 
>>  ORDER BY count(s.date) DESC;
>>
>> The models are:
>>
>> class PuzzleAnswer(models.Model): 
>>puzzle = models.ForeignKey(Puzzle, editable=True, 
>> on_delete=models.CASCADE) 
>>
>>answer = models.CharField(max_length=64)   
>>correct = models.BooleanField(editable=False)
>>created = models.DateTimeField(auto_now_add=True) 
>>author = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, 
>> null=True, 
>>
>>   on_delete=models.SET_NULL) 
>>  
>>  
>>
>> class Puzzle(models.Model):
>>category = models.ForeignKey(PuzzleCategory, on_delete=models.CASCADE, 
>> help_text=category_help)
>>notation = models.CharField(max_length=64) 
>>correct_answer = models.CharField(max_length=64) 
>>published = models.DateField(blank=True, null=True, db_index=True, 
>> unique=True)
>> 
>>  
>>
>

-- 
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/7282e7dc-e098-462e-b9aa-050dfcbde60dn%40googlegroups.com.


Re: Django Mysql Bulk_Create Ids

2020-09-28 Thread Simon Charette
Unfortunately MySQL doesn't support an equivalent of the RETURNING clause 
on PostgreSQL/Oracle.

In other words MySQL only allows to retrieve an inserted row auto id one at 
a time through its non-standard LAST_INSERT_ID function.

That prevents any attempts at inserting multiple rows and retrieving their 
corresponding primary key.

Cheers,
Simon

Le dimanche 27 septembre 2020 à 19:15:11 UTC-4, rohan...@gmail.com a écrit :

> How can we make this happen? 
> What steps would be needed so that bulk_create ends up returning the ids 
> of the items that just got created? I don't want to be machine gunning my 
> db with save statements to retrieve ids. 
>

-- 
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/f9cddbc9-85f7-487e-8d12-7a6445e4e870n%40googlegroups.com.


Re: select_for_update + select_related issue

2020-09-26 Thread Simon Charette
I don't think your issue has anything to do with proxy models.

You'll get the exact same error if your use Parent.objects instead of 
Child.objects as both will generate the same SQL:

SELECT *
FROM parent
LEFT JOIN foreign ON parent.foreign_id = foreign.id
FOR UPDATE OF parent

In this case "parent" cannot be selected for update since it's "foreign_id" 
column, which is "nullable", is implied in an outer join.

PostgreSQL simply doesn't support that and you'll have to rethink your data 
model if this is something you need to achieve[0]

Cheers,
Simon

[0] https://www.postgresql.org/message-id/21634.1160151...@sss.pgh.pa.us

Le mercredi 23 septembre 2020 à 12:15:35 UTC-4, d.ivan...@distillery.com a 
écrit :

> Hello.
> I just wanted to know, whether I run into a bug, and whether I should 
> report it.
>
> Normally select_for_update and select_related try to lock all affected 
> rows in all tables. One can specify "of" for select_for_update to limit 
> tables to lock (to prevent locking nullable relations).
>
> Recently a bug was fixed, which allowed to lock parent nodes with 
> multitable inheritance. But what about proxies? For me the following does 
> not work. Should it?
>
> class Parent(Model):
>   foreign = ForeignKey(Foreign, null=True, blank=True)
>
> class Child(Parent):
>   class Meta:
> proxy = True
>
> class Foreign(Model):
>   pass
>
> with transaction.atomic():
>   
> Child.objects.select_for_update(of=('self',)).select_related('foreign').get(pk=1)
>
> So the (pseudo) code above fails with a message "FOR UPDATE cannot be 
> applied to the nullable side of an outer join"
>
> So is this expected behaviour or a bug? What are possible workarounds for 
> that?
>

-- 
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/b9e15c75-8ec7-4ca2-a9a9-21f0d58f64a3n%40googlegroups.com.


Re: Bootstrap drop down menu not clickable.

2020-05-16 Thread Simon A
Not quite sure on that. Usually what I do is the process that you just
mentioned and what we did earlier for all the packages that I use.

On Sat, May 16, 2020, 23:10 sunday honesty  wrote:

> I saw "pip install django-bootstrap4"
>
> After installing, I should load bootstrap
> Then I could add bootstrap form.
>
> Other tutorials I have seen don't require downloading bootstrap since I
> have doneloaded the compiled bootstrap and added it to the static folder of
> my Django project.
> If really I must download bootstrap using pip before it works, why did
> other bootstrap features worked well except for the dropdown?
>
> On Sat, May 16, 2020, 3:51 PM sunday honesty 
> wrote:
>
>> All right
>>
>> On Sat, May 16, 2020, 3:49 PM Simon A  wrote:
>>
>>> Try to run the pip install command if you havent already. Check the
>>> correct command to install bootstrap3 or 4 if forgot the complete package
>>> name.
>>>
>>> On Sat, May 16, 2020, 22:45 sunday honesty 
>>> wrote:
>>>
>>>> I included it to installed app and got an error message on the console.
>>>> "Module not found, no module named bootstrap 4"
>>>>
>>>> On Sat, May 16, 2020, 3:31 PM Clive Bruton  wrote:
>>>>
>>>>>
>>>>> On 16 May 2020, at 15:03, sunday honesty wrote:
>>>>>
>>>>> > I did that and got a TemplateSyntaxError stating that bootstrap4 is
>>>>> > not a registered tag library
>>>>>
>>>>> Did you put it in your installed_apps?
>>>>>
>>>>>
>>>>> -- Clive
>>>>>
>>>>> --
>>>>> 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/AF951EBC-2228-4CB5-92CA-F7207A31DE0B%40indx.co.uk
>>>>> .
>>>>>
>>>> --
>>>> You received this message because you are subscribed to a topic in the
>>>> Google Groups "Django users" group.
>>>> To unsubscribe from this topic, visit
>>>> https://groups.google.com/d/topic/django-users/4gDB5RmIxfA/unsubscribe.
>>>> To unsubscribe from this group and all its topics, 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/CALcuGNsKtsCKW8FiTSSnrD1B7ajLYGU-rUGs23SFPSfsva%2BwMw%40mail.gmail.com
>>>> <https://groups.google.com/d/msgid/django-users/CALcuGNsKtsCKW8FiTSSnrD1B7ajLYGU-rUGs23SFPSfsva%2BwMw%40mail.gmail.com?utm_medium=email_source=footer>
>>>> .
>>>>
>>> --
>>> 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/CABXH83rS%2BdyLMhOdcdcXtvERh5a2PpmG_NubQjjspEz1YacWSw%40mail.gmail.com
>>> <https://groups.google.com/d/msgid/django-users/CABXH83rS%2BdyLMhOdcdcXtvERh5a2PpmG_NubQjjspEz1YacWSw%40mail.gmail.com?utm_medium=email_source=footer>
>>> .
>>>
>> --
> You received this message because you are subscribed to a topic in the
> Google Groups "Django users" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/django-users/4gDB5RmIxfA/unsubscribe.
> To unsubscribe from this group and all its topics, 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/CALcuGNsRdWqucetgtU3qS_78mCxu%3DBvV%3DDO4DXGdH7fpSknk-w%40mail.gmail.com
> <https://groups.google.com/d/msgid/django-users/CALcuGNsRdWqucetgtU3qS_78mCxu%3DBvV%3DDO4DXGdH7fpSknk-w%40mail.gmail.com?utm_medium=email_source=footer>
> .
>

-- 
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/CABXH83o-FvkG4PV32-e6NeHmBPZqKq4K55VgFpLPBmmA%2BQDbww%40mail.gmail.com.


Re: Bootstrap drop down menu not clickable.

2020-05-16 Thread Simon A
Try to run the pip install command if you havent already. Check the correct
command to install bootstrap3 or 4 if forgot the complete package name.

On Sat, May 16, 2020, 22:45 sunday honesty  wrote:

> I included it to installed app and got an error message on the console.
> "Module not found, no module named bootstrap 4"
>
> On Sat, May 16, 2020, 3:31 PM Clive Bruton  wrote:
>
>>
>> On 16 May 2020, at 15:03, sunday honesty wrote:
>>
>> > I did that and got a TemplateSyntaxError stating that bootstrap4 is
>> > not a registered tag library
>>
>> Did you put it in your installed_apps?
>>
>>
>> -- Clive
>>
>> --
>> 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/AF951EBC-2228-4CB5-92CA-F7207A31DE0B%40indx.co.uk
>> .
>>
> --
> You received this message because you are subscribed to a topic in the
> Google Groups "Django users" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/django-users/4gDB5RmIxfA/unsubscribe.
> To unsubscribe from this group and all its topics, 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/CALcuGNsKtsCKW8FiTSSnrD1B7ajLYGU-rUGs23SFPSfsva%2BwMw%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/CABXH83rS%2BdyLMhOdcdcXtvERh5a2PpmG_NubQjjspEz1YacWSw%40mail.gmail.com.


Re: Bootstrap drop down menu not clickable.

2020-05-16 Thread Simon A
Is it in you installed apps?

On Sat, May 16, 2020, 22:04 sunday honesty  wrote:

> I did that and got a TemplateSyntaxError stating that bootstrap4 is not a
> registered tag library
>
> --
> You received this message because you are subscribed to a topic in the
> Google Groups "Django users" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/django-users/4gDB5RmIxfA/unsubscribe.
> To unsubscribe from this group and all its topics, 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/5756089d-a944-4b3c-8d35-74e328c47cc1%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/CABXH83ouWqdjQkVYJmhnkJir_Rt6EqydrHbwqJg4%3DawuYUv3-w%40mail.gmail.com.


Bootstrap drop down menu not clickable.

2020-05-16 Thread Simon A
Try to include the dependencies inside the block content. Here is what I did

{% block content %} 
 {% load bootstrap3 %}
 {% bootstrap_css %}
 {% bootstrap_javascript %}

-- 
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/a3761f2c-2ddf-4eb7-939a-70d7b6192a26%40googlegroups.com.


Re: ValueError: The database backend does not accept 0 as a value for AutoField.

2020-04-06 Thread Simon Charette
Something in your code is assigning a id=0 to Mail before calling .save() 
on it.

If you identify its origin then removing it should address your problem.

Simon

Le lundi 6 avril 2020 11:51:46 UTC-4, Hamza Mirchi a écrit :
>
> How Can I Fix That Via Django?
>
> On Mon, Apr 6, 2020 at 10:16 AM Simon Charette  > wrote:
>
>> Hello there,
>>
>> By default MySQL interprets providing 0 for an AUTO_INCREMENT PRIMARY KEY 
>> as NULL which defaults to increment the field.
>>
>> CREATE TABLE foo (id int auto_increment primary key);
>> INSERT INTO foo (id) VALUES(0);
>> INSERT INTO foo (id) VALUES(0);
>> SELECT * FROM foo;
>> ++
>> | id |
>> ++
>> | 1  |
>> | 2  |
>> ++
>>
>> This ORM level check is to prevent you from shooting yourself in the foot 
>> by expecting that providing a zero will assign this value.
>>
>> Cheers,
>> Simon
>>
>> Le lundi 6 avril 2020 09:35:22 UTC-4, Hamza Mirchi a écrit :
>>>
>>> Hi Everyone,
>>>
>>> I'm Saving My Mail Model but i can't but i get that error again and again
>>>
>>> This is my model:
>>>
>>> class Mail(models.Model):
>>>  choices = (('Valid','Valid'),('InValid','InValid'),('Unknown','Unknown'
>>> ),('Extracted','Extracted',))
>>>  providers = (('Gmail','Gmail'),('Yahoo','Yahoo'),('Hotmail','Hotmail'
>>> ),('Outlook','Outlook'),('Live','Live'),('Aol','Aol'),('Protonmail',
>>> 'Protonmail'),('Other','Other'),)
>>>  user = models.ForeignKey(User,on_delete=models.CASCADE,blank=True,null=
>>> True)
>>>  email = models.EmailField(blank=False,null=False)
>>>  status = models.CharField(max_length=100,choices=choices)
>>>  type = models.CharField(max_length=100,choices=providers)
>>>
>>>
>>>  def __str__(self):
>>>  return self.email
>>>
>>>
>>>
>>> This is my Code:
>>>
>>> mail = Mail.objects.create(user=request.user,email=str(g),status='Valid'
>>> ,type='Gmail')
>>> mail.save()
>>>
>>>
>>> Here is The Error:
>>>
>>>
>>> Traceback (most recent call last):
>>>   File "/usr/lib/python3.7/multiprocessing/process.py", line 297, in 
>>> _bootstrap
>>> self.run()
>>>   File "/usr/lib/python3.7/multiprocessing/process.py", line 99, in run
>>> self._target(*self._args, **self._kwargs)
>>>   File "/media/lenovo/Local 
>>> Disk/Learning/Scripts/Django/emailv3/src/validator/views.py", line 703, 
>>> in g6
>>> mail.save()
>>>   File 
>>> "/home/lenovo/.local/lib/python3.7/site-packages/django/db/models/base.py"
>>> , line 746, in save
>>> force_update=force_update, update_fields=update_fields)
>>>   File 
>>> "/home/lenovo/.local/lib/python3.7/site-packages/django/db/models/base.py"
>>> , line 784, in save_base
>>> force_update, using, update_fields,
>>>   File 
>>> "/home/lenovo/.local/lib/python3.7/site-packages/django/db/models/base.py"
>>> , line 887, in _save_table
>>> results = self._do_insert(cls._base_manager, using, fields, 
>>> returning_fields, raw)
>>>   File 
>>> "/home/lenovo/.local/lib/python3.7/site-packages/django/db/models/base.py"
>>> , line 926, in _do_insert
>>> using=using, raw=raw,
>>>   File 
>>> "/home/lenovo/.local/lib/python3.7/site-packages/django/db/models/manager.py"
>>> , line 82, in manager_method
>>> return getattr(self.get_queryset(), name)(*args, **kwargs)
>>>   File 
>>> "/home/lenovo/.local/lib/python3.7/site-packages/django/db/models/query.py"
>>> , line 1204, in _insert
>>> return query.get_compiler(using=using).execute_sql(returning_fields)
>>>   File 
>>> "/home/lenovo/.local/lib/python3.7/site-packages/django/db/models/sql/compiler.py"
>>> , line 1390, in execute_sql
>>> for sql, params in self.as_sql():
>>>   File 
>>> "/home/lenovo/.local/lib/python3.7/site-packages/django/db/models/sql/compiler.py"
>>> , line 1335, in as_sql
>>> for obj in self.query.objs
>>>   File 
>>> "/home/lenovo/.local/lib/python3.7/site-packages/django/db/models/sql/compiler.py"
>>> , line 1335, in 
>>> for obj in self.query.objs
>>>   File 
>>> "/home/lenovo/.local/lib/python3.7/site-packages/dja

Re: ValueError: The database backend does not accept 0 as a value for AutoField.

2020-04-06 Thread Simon Charette
Hello there,

By default MySQL interprets providing 0 for an AUTO_INCREMENT PRIMARY KEY 
as NULL which defaults to increment the field.

CREATE TABLE foo (id int auto_increment primary key);
INSERT INTO foo (id) VALUES(0);
INSERT INTO foo (id) VALUES(0);
SELECT * FROM foo;
++
| id |
++
| 1  |
| 2  |
++

This ORM level check is to prevent you from shooting yourself in the foot 
by expecting that providing a zero will assign this value.

Cheers,
Simon

Le lundi 6 avril 2020 09:35:22 UTC-4, Hamza Mirchi a écrit :
>
> Hi Everyone,
>
> I'm Saving My Mail Model but i can't but i get that error again and again
>
> This is my model:
>
> class Mail(models.Model):
>  choices = (('Valid','Valid'),('InValid','InValid'),('Unknown','Unknown'
> ),('Extracted','Extracted',))
>  providers = (('Gmail','Gmail'),('Yahoo','Yahoo'),('Hotmail','Hotmail'),(
> 'Outlook','Outlook'),('Live','Live'),('Aol','Aol'),('Protonmail',
> 'Protonmail'),('Other','Other'),)
>  user = models.ForeignKey(User,on_delete=models.CASCADE,blank=True,null=
> True)
>  email = models.EmailField(blank=False,null=False)
>  status = models.CharField(max_length=100,choices=choices)
>  type = models.CharField(max_length=100,choices=providers)
>
>
>  def __str__(self):
>  return self.email
>
>
>
> This is my Code:
>
> mail = Mail.objects.create(user=request.user,email=str(g),status='Valid',
> type='Gmail')
> mail.save()
>
>
> Here is The Error:
>
>
> Traceback (most recent call last):
>   File "/usr/lib/python3.7/multiprocessing/process.py", line 297, in 
> _bootstrap
> self.run()
>   File "/usr/lib/python3.7/multiprocessing/process.py", line 99, in run
> self._target(*self._args, **self._kwargs)
>   File "/media/lenovo/Local 
> Disk/Learning/Scripts/Django/emailv3/src/validator/views.py", line 703, in 
> g6
> mail.save()
>   File 
> "/home/lenovo/.local/lib/python3.7/site-packages/django/db/models/base.py"
> , line 746, in save
> force_update=force_update, update_fields=update_fields)
>   File 
> "/home/lenovo/.local/lib/python3.7/site-packages/django/db/models/base.py"
> , line 784, in save_base
> force_update, using, update_fields,
>   File 
> "/home/lenovo/.local/lib/python3.7/site-packages/django/db/models/base.py"
> , line 887, in _save_table
> results = self._do_insert(cls._base_manager, using, fields, 
> returning_fields, raw)
>   File 
> "/home/lenovo/.local/lib/python3.7/site-packages/django/db/models/base.py"
> , line 926, in _do_insert
> using=using, raw=raw,
>   File 
> "/home/lenovo/.local/lib/python3.7/site-packages/django/db/models/manager.py"
> , line 82, in manager_method
> return getattr(self.get_queryset(), name)(*args, **kwargs)
>   File 
> "/home/lenovo/.local/lib/python3.7/site-packages/django/db/models/query.py"
> , line 1204, in _insert
> return query.get_compiler(using=using).execute_sql(returning_fields)
>   File 
> "/home/lenovo/.local/lib/python3.7/site-packages/django/db/models/sql/compiler.py"
> , line 1390, in execute_sql
> for sql, params in self.as_sql():
>   File 
> "/home/lenovo/.local/lib/python3.7/site-packages/django/db/models/sql/compiler.py"
> , line 1335, in as_sql
> for obj in self.query.objs
>   File 
> "/home/lenovo/.local/lib/python3.7/site-packages/django/db/models/sql/compiler.py"
> , line 1335, in 
> for obj in self.query.objs
>   File 
> "/home/lenovo/.local/lib/python3.7/site-packages/django/db/models/sql/compiler.py"
> , line 1334, in 
> [self.prepare_value(field, self.pre_save_val(field, obj)) for field in 
> fields]
>   File 
> "/home/lenovo/.local/lib/python3.7/site-packages/django/db/models/sql/compiler.py"
> , line 1275, in prepare_value
> value = field.get_db_prep_save(value, connection=self.connection)
>   File 
> "/home/lenovo/.local/lib/python3.7/site-packages/django/db/models/fields/__init__.py"
> , line 821, in get_db_prep_save
> return self.get_db_prep_value(value, connection=connection, prepared=
> False)
>   File 
> "/home/lenovo/.local/lib/python3.7/site-packages/django/db/models/fields/__init__.py"
> , line 2366, in get_db_prep_value
> value = connection.ops.validate_autopk_value(value)
>   File 
> "/home/lenovo/.local/lib/python3.7/site-packages/django/db/backends/mysql/operations.py"
> , line 192, in validate_autopk_value
> raise ValueError('The database backend does not accept 0 as a '
> ValueError: The database backend does not accept 0 as a value for 
> AutoField
>
>
>
>
>

-- 
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/86f4aedc-2241-4ca9-b088-afb511d1733a%40googlegroups.com.


Re: Impossible d'utiliser language_code 'fr-fr' avec django 3.0.4

2020-03-26 Thread Simon Charette
La documentation de Django est disponible en Français.

Ce message d'erreur est traduit dans cette section: 
https://docs.djangoproject.com/fr/3.0/ref/checks/#translation

Tu as deux choix:
1. Ajoute 'fr-fr' à ton setting LANGUAGES tel qu'indiqué
2. Définit ton setting LANGUAGE_CODE = 'fr' plutôt que 'fr-fr'

Simon

Le jeudi 26 mars 2020 21:47:11 UTC-4, Anselme SERI a écrit :
>
> Je suis un nouveau dans le développement python et je teste actuellement 
> Django.
> Il m'est impossible d'utiliser le language_code 'fr-fr' dans django 3.0.4.
> Le message d'erreur qui s'affiche dans le terminal est le suivant :
>
> "ERRORS:
> ?: (translation.E004) You have provided a value for the LANGUAGE_CODE 
> setting that is not in the LANGUAGES setting."
>
> J'ai fouiner sur internet à la recherche de solution sans succès.
>
> Comment puis-je travailler avec une interface en français. Quelqu'un 
> pourrait m'aider?
>

-- 
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/37a930ed-f975-41c4-b567-ab710bc0a266%40googlegroups.com.


Re: is there any way to django3.0 & oracle 11g together?

2020-03-21 Thread Simon Charette
Django 3.0 only supports Oracle 12.2 and and 18c[0].

Django 2.2 only supports Oracle 12.1+[1]

Django 1.11 supports Oracle 11g but LTS support for it will end in April[2].

In short even if you downgrade to 1.11 LTS you won't get any support from 
Django after less than two weeks.

It looks like Oracle 11g has not been supported since August 2013 [3]

If you can't upgrade your Oracle setup I suggest you consider moving to a 
different database such as PostgreSQL.

Simon

[0] 
https://docs.djangoproject.com/en/3.0/releases/3.0/#dropped-support-for-oracle-12-1
[1] https://docs.djangoproject.com/en/2.2/ref/databases/#oracle-notes
[2] https://www.djangoproject.com/download/#supported-versions
[3] https://en.wikipedia.org/wiki/Oracle_Database

Le samedi 21 mars 2020 12:55:56 UTC-4, Md. Rakibul Islam 131-35-385 a 
écrit :
>
> *My organization uses Oracle 11g there is no way to upgrade it.*
>
> I am facing some issues with oracle 11g & Django 3.0. when i try to 
> migrate a model in django 3.0 i face below mentioned problem:
>
> django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create 
> the django_migrations table (ORA-02000: missing ALWAYS keyword)
>
> To solve it i switched to django 1.11.17 but it is generating below 
> mentioned error.
>
> ImportError: cannot import name 'path' from 'django.urls' 
> (C:\Users\RAKIB\AppData\Local\Programs\Python\Python38\lib\site-packages\django\urls\__init__.py).
>
> *is there any solution??*
>
>

-- 
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/17391d85-8f9e-49dd-b950-27999a88f44d%40googlegroups.com.


Re: Get last instance object per each month and sum per month in Django

2020-02-25 Thread Simon Charette
If you don't want to operate on Activity instances annotations you can use 
the following queryset

Status.objects.annotate(
status_month=TruncMonth('status_date'),
).order_by(
'activity', 'status_month',
).values_list(
'activity', 'status_month',
).annotate(
progress_sum=Sum(actual_progress)
)

That will return an iterable of lists of the form [activity_id, 
status_month, progress_sum]

If you want to annotate your Activity instances you'll need to use window 
functions[0].

Simon

[0] 
https://docs.djangoproject.com/en/3.0/ref/models/expressions/#window-functions

Le mardi 25 février 2020 17:55:49 UTC-5, Agnese Camellini a écrit :
>
> You should search how to make a group by activity and a partition by month 
> then take each partition and sum the record up, i don't know how to do it 
> in Django orm but in sql is the most effective way to solve the issue and 
> it's a lot let expensive than taking all the activities and then search in 
> the status Table.
> my 2 cents
> Agnese
>
> On Tue, 25 Feb 2020 at 21:07, Mario Bisiani  > wrote:
>
>> I tryed to search for answer but nothing yet can help me.
>>
>> I have one class model Activity and a class model Status :
>>
>> class Status(models.Model):
>> activity = models.ForeignKey(Activity, on_delete=models.CASCADE, 
>> related_name="all_status")
>> status_date = models.DateField()
>> actual_progress = models.DecimalField(max_digits=3, decimal_places=2)
>>
>> I need to get last 'status_date' for each activity for each month and sum 
>> up its actual_progress.
>>
>> Can't find after many research a way out.
>>
>> *Update*
>>
>> I found a way to get latest status per activity helped here Django - get 
>> latest object in each relation 
>> <https://stackoverflow.com/questions/52586866/django-get-latest-object-in-each-relation>
>> :
>>
>> @classmethod
>> def get_latest_by_activity_ids(cls, activity_id):
>> found = []
>> for aid in Activity.objects.all():
>> 
>> found.append(cls.objects.filter(activity_id=aid).latest("status_date"))
>> return found 
>>
>> This gave me a list of dates. Now I'm blocked to sum them up per month.
>>
>>
>>
>> https://stackoverflow.com/questions/60366457/get-last-instance-object-per-each-month-and-sum-per-month-in-django
>>
>>
>> -- 
>> 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/91d43812-6c7a-431d-9117-7a79519564fd%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/django-users/91d43812-6c7a-431d-9117-7a79519564fd%40googlegroups.com?utm_medium=email_source=footer>
>> .
>>
>

-- 
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/c2cbe3ac-9acd-44cd-a48b-24d74f75cb09%40googlegroups.com.


Re: Django queryset result and mysql query are wrong after updating from 3.0.2 to 3.0.3

2020-02-19 Thread Simon Charette
Hello Ricardo,

I suggest you follow these docs to submit your bug report and link to this 
thread.

https://docs.djangoproject.com/en/3.0/internals/contributing/bugs-and-features/#reporting-bugs

I'd mention that the issue is also present if you use 
`output_field=DurationField` as BigIntegerField
was likely only working by change.

Cheers,
Simon


Le mercredi 19 février 2020 14:51:53 UTC-5, Ricardo H a écrit :
>
> Hi Simon, 
>
> It was ok on 2.2.6, only on 3.0.3 it fails.
>
> I use BigIntegerField because I use it for some calculations after that, 
> but even if I try with DurationField it doens't assert right.
>
> Definitely must be caused by this patch, if I can't find another solution, 
> where and how should I report this ?.
>
> Thanks.
>

-- 
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/0ce21876-4be1-4096-8537-c9d76894dd84%40googlegroups.com.


Re: How to store a boolean expression (parse tree) in a model?

2020-02-19 Thread Simon Charette
Could you simply make the connector field nullable to express that?

Simon

Le mercredi 19 février 2020 12:15:32 UTC-5, test a écrit :
>
> thanks, do you know how i can create custom leaf nodes when using MPTT or 
> treebeard?
>
> My parent nodes should have connector types such as AND/OR but the child 
> should not
>
>
> On Tuesday, February 18, 2020 at 11:30:40 PM UTC-5, Simon Charette wrote:
>>
>> I suggest you have a look at the "Trees and Graph" section of the
>> Django Packages website[0]. I've personally used MPTT and Treebeard
>> in the past without too much trouble.
>>
>> You could also a field able to store composite data structures
>> such as JSONField or even a dedicated PostgreSQL type[1] to efficiently 
>> store
>> such data.
>>
>> Cheers,
>> Simon
>>
>> [0] https://djangopackages.org/grids/g/trees-and-graphs/
>> [1] https://www.postgresql.org/docs/current/sql-createtype.html
>>
>> Le mardi 18 février 2020 18:13:39 UTC-5, test a écrit :
>>>
>>> Let's say I have:
>>>
>>> Calculator #1:
>>> Expression: (True AND False) AND (True OR False)
>>>
>>> This expression should be a child of some calculator. 
>>>
>>> class Calculator(models.Model):
>>> name = ...
>>>
>>> class Expression(models.Model):
>>> parent = models.ForeignKey(Calculator)
>>>
>>> boolean = AND or OR
>>>
>>> sub_exp1 = models.ForeignKey(Expression)
>>> sub_exp2 = models.ForeignKey(Expression)
>>>
>>>
>>> When I query all the expressions for the Calculator #1, I should get all 
>>> the subexpressions.
>>>
>>> 1 AND 2 5
>>> 2 AND 3 4
>>> 3 leaf node of True 
>>> 4 lead node of False
>>> 5 OR 6 7
>>> 6 leaf node of True
>>> 7 leaf node of False
>>>
>>> From this, I can quickly apply my parse tree.
>>>
>>> How would I display the base case/leaf nodes in my model? Also, is there 
>>> a better way?
>>>
>>> Thanks, I would really appreciate any help
>>>
>>

-- 
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/1b1c4b6e-71e7-4613-854c-b96d0028f28b%40googlegroups.com.


Re: Django queryset result and mysql query are wrong after updating from 3.0.2 to 3.0.3

2020-02-19 Thread Simon Charette
Hello Ricardo,

This could be a regression caused by a patch addressing a regression in 
3.0.3[0].

Did you also notice this behaviour on Django 2.2.x or was this project 
started from Django 3.0?

>From what I can see though I find it strange that the ExpressionWrapper of 
end_total_time
have an output_field of BigIntegerField instead of DurationField. That 
could be the origin
of your issue.

Cheers,
Simon

[0] 
https://github.com/django/django/commit/02cda09b13e677db01863fa0a7112dba631b9c5c

Le mercredi 19 février 2020 13:08:57 UTC-5, Ricardo H a écrit :
>
> Hello,  after I updated django from 3.0.2 to 3.0.3 the result of the 
> following code has changed when using a MySQL database. It produces a wrong 
> sql query and also the wrong result for "*end_total_time"* attribute.
> Is this a bug ? also is there any other way to get the wright result using 
> 3.0.3 ?
>
> Thank you.
>
> *models.py*
> from datetime import datetime
> import pytz
>
>
> from django.db import models
> from django.db.models.functions import Cast
>
>
> class PhaseQueryset(models.QuerySet):
>
>
> def with_duration(self,):
> base_date = datetime(2000, 1, 3, 0, tzinfo=pytz.utc)
>
>
> # When I use base_date to do the end_total_time math in 3.0.3 
> together
> # with ended_at annotated, it creates a wrong query
> qs = self.annotate(
> ended_at=models.Case(
> models.When(
> models.Q(type='TYPEONE'),
> then=models.functions.Now()
> ),
> default=models.F('started_at'),
> output_field=models.DateTimeField(),
> ),
> base_date=models.functions.Cast(
> models.Value(base_date),
> output_field=models.DateTimeField()
> ),
> end_total_time=models.ExpressionWrapper(
> models.F('ended_at') - models.F('base_date'),
> output_field=models.fields.BigIntegerField()
> )
> )
>
>
> return qs
>
>
> # Create your models here.
> class Phase(models.Model):
> objects = PhaseQueryset().as_manager()
> started_at = models.DateTimeField()
> type = models.CharField(max_length=40)
>
>
>
> *tests.py*
> from datetime import datetime, timedelta
> import pytz
>
>
> from django.test import TestCase
> from daterror.models import Phase
> # Create your tests here.
>
>
> class TestDateProblem(TestCase):
>
>
> def setUp(self,):
> past = datetime.now(tz=pytz.UTC) - timedelta(days=30)
> Phase.objects.create(started_at=past, type='TYPEONE')
> past = datetime.now(tz=pytz.UTC) - timedelta(days=33)
> Phase.objects.create(started_at=past, type='TYPETWO')
> past = datetime.now(tz=pytz.UTC) - timedelta(days=34)
> Phase.objects.create(started_at=past, type='TYPETHREE')
>
>
>
>
> def test_timedifference_not_none(self,):
> phases = Phase.objects.all().with_duration()
> print(phases[0].end_total_time)
> print(phases[1].end_total_time)
> print(phases[2].end_total_time)
> self.assertNotEqual(None, phases[0].end_total_time)
> self.assertNotEqual(None, phases[1].end_total_time)
> self.assertNotEqual(None, phases[2].end_total_time)
>
>

-- 
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/4542b03e-797a-4e06-99c2-5ca77ccd4aec%40googlegroups.com.


Re: How to store a boolean expression (parse tree) in a model?

2020-02-18 Thread Simon Charette
I suggest you have a look at the "Trees and Graph" section of the
Django Packages website[0]. I've personally used MPTT and Treebeard
in the past without too much trouble.

You could also a field able to store composite data structures
such as JSONField or even a dedicated PostgreSQL type[1] to efficiently 
store
such data.

Cheers,
Simon

[0] https://djangopackages.org/grids/g/trees-and-graphs/
[1] https://www.postgresql.org/docs/current/sql-createtype.html

Le mardi 18 février 2020 18:13:39 UTC-5, test a écrit :
>
> Let's say I have:
>
> Calculator #1:
> Expression: (True AND False) AND (True OR False)
>
> This expression should be a child of some calculator. 
>
> class Calculator(models.Model):
> name = ...
>
> class Expression(models.Model):
> parent = models.ForeignKey(Calculator)
>
> boolean = AND or OR
>
> sub_exp1 = models.ForeignKey(Expression)
> sub_exp2 = models.ForeignKey(Expression)
>
>
> When I query all the expressions for the Calculator #1, I should get all 
> the subexpressions.
>
> 1 AND 2 5
> 2 AND 3 4
> 3 leaf node of True 
> 4 lead node of False
> 5 OR 6 7
> 6 leaf node of True
> 7 leaf node of False
>
> From this, I can quickly apply my parse tree.
>
> How would I display the base case/leaf nodes in my model? Also, is there a 
> better way?
>
> Thanks, I would really appreciate any help
>

-- 
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/5ec92ddf-78b7-477a-aa0c-c7bc2a5ef005%40googlegroups.com.


Re: Model uniqueness constraint with date extraction

2020-02-18 Thread Simon Charette
Hello Thierry,

Django doesn't support support constraints on lookups/expressions but 
there's ungoing work to do so[0].

In the mean time you'll have to rely on a `RunSQL` operation  in your 
migrations to create the constraint.

Cheers,
Simon

[0] https://code.djangoproject.com/ticket/30916

Le mardi 18 février 2020 09:32:19 UTC-5, Thierry Backes a écrit :
>
> Hey,
>
>  
>
> I have a model which has a date and a foreign key field. I want a 
> uniqueness constraint that each fk can only be used once per month, so 
> Unique(date__year, date__month, fk). However, when I use this in my model’s 
> metadata:
>
>  
>
> models.UniqueConstraint(fields=['date__year', 'date__month', 'category'], 
> name='date_month_cat_unique')
>
>  
>
> I get an error that the date__year field doesn’t exist. This is a bit 
> strange because I use this syntax throughout my app and I also know that 
> such constraints are supported by Postgres:
>
>  
>
> create unique index year_month_uq 
>
>   on foo 
>
>   ( extract(year from mydate), 
>
> extract(month from mydate)
>
>   ) ;
>
>  
>
> As per 
> https://dba.stackexchange.com/questions/210736/postgresql-enforcing-unique-constraint-on-date-column-parts
>
>  
>
> What am I doing wrong here? I’m using Django 3 and Postgres.
>
>  
>
> Thanks
>

-- 
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/030dbd7e-b4bd-4905-9a59-cbb61d12132e%40googlegroups.com.


Re: How to express `foo = (bar < quox)` as a constraint

2020-01-27 Thread Simon Charette
I see, I think you'll need to wrap the inner Q in an ExpressionWrapper[0]

That would be

CheckConstraint(check=Q(is_on_sale=ExpressionWrapper(Q(price__lt=F('full_price')),
 
output_field=models.BooleanField(

That involves a lot of boilerplate though and it ought to work without all 
of it so I'd submit an optimization ticket
to allow direct usage of Q objects for boolean field lookup right hand sides

Cheers,
Simon

https://docs.djangoproject.com/en/3.0/ref/models/expressions/#django.db.models.ExpressionWrapper

Le lundi 27 janvier 2020 14:32:24 UTC-5, Peter Law a écrit :
>
> Hi Simon,
>
> Thanks for your response.
>
> I did try that, however unfortunately I get an error when running the 
> migration:
>
> django.core.exceptions.ValidationError: ["'(AND: 
> )' value must 
> be either True or False."]
>
> I'm using Django 2.2 LTS though testing this in 3.0 unfortunately errors 
> in the same way.
>
> I think the issue with this spelling is that a `models.Q` isn't expecting 
> to be passed another `models.Q` as a value. I think ideally it would want 
> an expression there, which a `models.F` is closest to, however using a 
> `models.F` relation there also doesn't work (see my response to Stephen's 
> suggestion).
>
> Thanks,
> Peter
>
> On Monday, 27 January 2020 18:23:28 UTC, Simon Charette wrote:
>>
>> Did you try
>>
>> class Item(Model):
>> price = DecimalField()
>> full_price = DecimalField()
>> is_on_sale = BooleanField()
>>
>> class Meta:
>> constraints = [
>> 
>> CheckConstraint(check=Q(is_on_sale=Q(price__lt=F('full_price'
>> ]
>>
>> I haven't tried it myself but I would expect it to work on Django 3.0.
>>
>> Cheers,
>> Simon
>>
>> Le lundi 27 janvier 2020 12:47:37 UTC-5, Peter Law a écrit :
>>>
>>> Hi, 
>>>
>>> Thanks for adding support for check constraints in Django 2.2, it's 
>>> great to be able to move constraints into the model definitions. 
>>>
>>> I've been trying to work out how to express a constraint which 
>>> validates that the value of one field expresses a relation between two 
>>> other fields, but can't find a nice way to do so. 
>>>
>>> I've read through the docs and also found 
>>> https://groups.google.com/d/topic/django-users/6Olh5V1b7Us/discussion, 
>>> but haven't found a concise spelling. 
>>>
>>> I've got a model like: 
>>>
>>> ``` 
>>> class Item(Model): 
>>> price = DecimalField() 
>>> full_price = DecimalField() 
>>> is_on_sale = BooleanField() 
>>> ``` 
>>>
>>> I'd like to be able to express neatly that the `is_on_sale` boolean be 
>>> true only when `price < full_price`. 
>>> In Postgres I can express this as: 
>>>
>>> ``` 
>>> ALTER TABLE item 
>>> ADD CONSTRAINT is_on_sale_check 
>>> CHECK (is_on_sale = (price < full_price)) 
>>> ``` 
>>>
>>> However in Django I can't find a way to express this directly. 
>>>
>>> I did find a long spelling which essentially checks the True case and 
>>> the False case explicitly and then ORs them together, however it's 
>>> several lines of `models.Q` combinations and not at all clear about 
>>> what the code is trying to achieve. 
>>>
>>> Is there a concise way to do this sort of constraint? If not, would it 
>>> be possible for Django to add support for it? 
>>>
>>> Thanks, 
>>> Peter 
>>>
>>

-- 
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/5d9488a8-7e6d-4a96-b009-fd94feb9df86%40googlegroups.com.


Re: How to express `foo = (bar < quox)` as a constraint

2020-01-27 Thread Simon Charette
Did you try

class Item(Model):
price = DecimalField()
full_price = DecimalField()
is_on_sale = BooleanField()

class Meta:
constraints = [

CheckConstraint(check=Q(is_on_sale=Q(price__lt=F('full_price'
]

I haven't tried it myself but I would expect it to work on Django 3.0.

Cheers,
Simon

Le lundi 27 janvier 2020 12:47:37 UTC-5, Peter Law a écrit :
>
> Hi, 
>
> Thanks for adding support for check constraints in Django 2.2, it's 
> great to be able to move constraints into the model definitions. 
>
> I've been trying to work out how to express a constraint which 
> validates that the value of one field expresses a relation between two 
> other fields, but can't find a nice way to do so. 
>
> I've read through the docs and also found 
> https://groups.google.com/d/topic/django-users/6Olh5V1b7Us/discussion, 
> but haven't found a concise spelling. 
>
> I've got a model like: 
>
> ``` 
> class Item(Model): 
> price = DecimalField() 
> full_price = DecimalField() 
> is_on_sale = BooleanField() 
> ``` 
>
> I'd like to be able to express neatly that the `is_on_sale` boolean be 
> true only when `price < full_price`. 
> In Postgres I can express this as: 
>
> ``` 
> ALTER TABLE item 
> ADD CONSTRAINT is_on_sale_check 
> CHECK (is_on_sale = (price < full_price)) 
> ``` 
>
> However in Django I can't find a way to express this directly. 
>
> I did find a long spelling which essentially checks the True case and 
> the False case explicitly and then ORs them together, however it's 
> several lines of `models.Q` combinations and not at all clear about 
> what the code is trying to achieve. 
>
> Is there a concise way to do this sort of constraint? If not, would it 
> be possible for Django to add support for it? 
>
> Thanks, 
> Peter 
>

-- 
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/93fe186a-4f25-4ec2-ac5c-f28fd882812f%40googlegroups.com.


Re: Case-insensitve unique = True

2020-01-23 Thread Simon Charette
If you are using PostgreSQL I'd suggest using a CIText field[0] with a 
unique
constraint[1].

If you are *not* using PostgreSQL your best choice is likely to emulate the
upcoming expression[3] support for UniqueConstraint(Lower('field')) by using
a RunSQL operation that performs the appropriate DDL assuming your backend
supports it.

Best,
Simon

[0] 
https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#citext-fields
[1] https://docs.djangoproject.com/en/3.0/ref/models/fields/#unique
[3] https://github.com/django/django/pull/11929

Le jeudi 23 janvier 2020 21:36:29 UTC-5, Mike Dewhirst a écrit :
>
> What is the best way to ensure a charfield is case-insensitively unique? 
>
> Currently I'm using a query with __iexact=True but I wonder whether 
> there is a better way. 
>
> Thanks 
>
> Mike 
>
>
>

-- 
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/967c8a27-a8ec-42fc-abf5-bda76fbb5ef9%40googlegroups.com.


Re: UniqueConstraint rises fields.E310 error because of issue with backward compatibility with unique_together

2020-01-20 Thread Simon Charette
Hello Pavel,

This is likely a bug because UniqueConstraint was only recently introduced.

Please file a bug report about it. In the mean time you can add this check 
to
your SILENCED_SYSTEM_CHECKS setting to silence it.

Best,
Simon

Le lundi 20 janvier 2020 07:21:26 UTC-5, Pavel Garkin a écrit :
>
> Hi all,
>
>
> I'm trying to create migration with uniqueness of 2 fields: uid, source. 
>
> *Django 2.2.9*
>
> class Users(models.Model):
> uid = models.CharField(...)
> source = models.ForeignKey(*...*)
>
> class Meta:
>
>constraints = [models.UniqueConstraint(fields=['uid', 'source'], 
> name='users_uniqueness')]
>indexes = [models.Index(fields=('uid', 'source'), 
> name='users_indexes')]
>
>
>
> When I start makemigrations command in manage.py it rises *fields.E310 
> <https://docs.djangoproject.com/en/2.2/ref/checks/#related-fields>* error
>
>
> app_name.Users.field: (fields.E310) No subset of the fields 'uid', 'source' 
> on model 'Users' is unique.
>   HINT: Add unique=True on any of those fields or add at least a subset 
> of them to a unique_together constraint.
>
>
>
> When I change Meta options to unique_together constraint it works ok. 
> Migrations passes with no errors
>
>
> ...
>class Meta:
>
> unique_together = [['uid', 'source']]
>
>
> As mentioned in docs 
> <https://docs.djangoproject.com/en/2.2/ref/models/options/#unique-together> 
> unique_together may be deprecated in the future so I wanted to avoid this 
> kind of issue.
>
>
>
> *Thanks,*
>
> *Pavel*
>
>
>

-- 
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/b49b70d2-9a1d-409f-ac43-3a643a7f27b1%40googlegroups.com.


Re: Prefetching returning empty values for some object

2019-12-30 Thread Simon Charette
I suspect your usage of `distinct('path')` is causing issues during 
prefetching here
as it will prevent different File with the same .path from being prefetched 
for two different
folder objects.

You likely want to use `distinct('path', 'folder')` here instead where 
'folder' might have a different
name based on whether or not you provided a related_name or 
related_query_name to Folder.files.

Cheers,
Simon

Le lundi 30 décembre 2019 02:20:07 UTC-5, Mohit Solanki a écrit :
>
> Assume these two models.
>
> class Folder(model):
> name = models.CharField(max_length=8)
> files = models.ManyToManyField('File')
> class File:
>path = models.CharField(max_length=255)
>
>
> First I was fetching the folders and while looping over them fetching the 
> files with a distinct path
>
> folders = Folder.objects.all()
> for folder in folders:
> files_with_distinct_path = folder.files.distinct('path').order_by('path')
>
>
> but this suffers from the N+1 problem, So I tried prefetching the files 
> while fetching all the folders.
>
> from django.db.models import Prefetch
>
> folders = Folder.objects.prefetch_related(
> Prefetch(
> 'files', queryset=File.objects.distinct('path').order_by('path'), 
> to_attr='distinct_files'
> ))
>
>
> but it turns out now there objects with empty `distinct_files` which is 
> not the correct result, these objects have files but after prefetching, the 
> result is empty only for few objects.
>

-- 
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/ac516a2f-a835-4371-b097-be5793b42c6a%40googlegroups.com.


Re: FieldError at / Django models how to reslove this issue....

2019-12-19 Thread Simon Charette
You are missing an underscore here.

It should be published_date__lte and not published_date_lte.

Cheers,
Simon

Le jeudi 19 décembre 2019 11:40:05 UTC-5, MEGA NATHAN a écrit :
>
> Hi all.
>
> Cannot resolve keyword 'published_date_lte' into field. Choices are: author, 
> author_id, comments, create_date, id, published_date, text, title
>
>   
>
> this are models:
> from django.db import models
> from django.utils import timezone
> from django.urls import reverse
>
> # Create your models here.
>
> class Post(models.Model):
> author = models.ForeignKey('auth.User', on_delete=models.CASCADE,)
> title = models.CharField(max_length=200)
> text = models.TextField()
> create_date = models.DateTimeField(default=timezone.now())
> published_date = models.DateTimeField(blank=True, null=True) 
>
> def publish(self):
> self.published_date = timezone.now()
> self.save()
>
> #def approve_comments(self):
> #return self.comments.filter(approved_comments=True)
> 
> def approved_comments(self):
> return self.comments.filter(approved_comment=True)
>
> #def get_absolute_url(self):
> #return reverse("post_detail", kwargs={"pk": self.pk})
>
> def __str__self():
> return self.title
>
> class Comment(models.Model):
> post = models.ForeignKey('blog.post',related_name='comments'
> , on_delete=models.CASCADE,)
> title = models.CharField(max_length=200)
> text = models.TextField()
> create_date = models.DateTimeField(default=timezone.now())
> published_date = models.DateTimeField(blank=True, null=True) 
> approved_comment = models.BooleanField(default=False)
>
> def approve(self):
> self.approved_comment = True
> self.save()
> 
> def get_absolute_url(self):
> return reverse('post_list')
>  
> def __str__(self):
> return self.text
>
> And views:
>
> from django.shortcuts import render, get_object_or_404, redirect
> from django.utils import timezone
> #from django.utils.timezone.now`
> from blog.models import Post, Comment
> from .forms import PostForm,CommentForm
> from django.urls import reverse_lazy
> from django.contrib.auth.decorators import login_required
> from django.contrib.auth.mixins import LoginRequiredMixin 
> from django.views.generic import
>  (TemplateView, ListView, DetailView, CreateView,
> UpdateView, DeleteView)
> 
> # Create your views here.
>
> class Aboutview(TemplateView):
> template_name = 'about.html'
>
> class PostListView(ListView):
> model = Post
>
> def get_queryset(self):
> return
>  Post.objects.filter(published_date_lte=timezone.now()).order_by(
> '-published_date')
>
> class PostDetailView(DetailView):
> model = Post
>
> class CreatePostView(LoginRequiredMixin,CreateView):
> Login_url = '/Login/'
> redirect_field_name = 'blog/post_detail.html'
> from_class = PostForm
> model = Post
>
> class PostUpdateView(LoginRequiredMixin, UpdateView):
> Login_url = '/Login/'
> redirect_field_name = 'blog/post_detail.html'
> from_class = PostForm
> model = Post
>
> #class PostDeleteView(loginrequiredMixin, DeleteView):
> class PostDeleteView(LoginRequiredMixin,DeleteView):
> model = Post
> success_url = reverse_lazy('post_list')
>
> class DraftListView(LoginRequiredMixin, ListView):
> login_url = '/Login/'
> redirect_field_name = 'blog/post_list.html'
> model = Post
>
> def get__queryset(self):
> return Post.objects.filter(published_date_isnull=True).order_by(
> 'created_date')
>
>
> #
> ##
> def add_comment_to_post(request, pk):
> post = get_object_or_404(Post, pk=pk)
> if request.method == "POST":
> form = CommentForm(request.POST)
> if form.is_valid():
> comment = form.save(commit=False)
> comment.post = post
> comment.save()
> return redirect('post_detail', pk=post.pk)
> else:
> form = CommentForm()
> return render(request, 'blog/comment_form.html', {'form': form})
>
> @login_required
> def post_publish(request, pk):
> post = get_object_or_404(Post, pk=pk)
> post.publish
> return redirect('blog/post_detail.html', pk=pk)
>
> #@login_required
> def comment_approve(request,pk):
> comment = get_object_or_404(comment,pk=pk)
> comment.approve()
> return redirect('post_detail',pk=comment.post.pk)
&g

Re: Influencing order of internal migration operations

2019-12-11 Thread Simon Charette
Hello Rich,

Unfortunately the migration framework is not smart enough to resolve this 
kind of dependency.

The order of operation/migrations of the makemigrations is generated by the 
autodetector which
hardcodes most of its logic.

I would have assumed that constraints were generated _after_ 
unique_togethers though[0].

I suspect the operations are ordered this way because the index and 
constraints operations don't
implement the references_field and references_model operations.

Could you give a try at implementing them for `AddConstraint` based on your 
CompositeForeignKey
values and see if it helps anyhow?

They should likely be implemented in core but I suspect it will be hard for 
functional and conditional
indices just like constraints are. I think the best way forward will be to 
add a `referenced_fields`
property on Index and BaseConstraint that returns a set of (model_label, 
field_name) tuples and
have index and constraint operations rely on them.

Cheers,
Simon

[0] 
https://github.com/django/django/blob/8ea3ff155eda8c9aa55e01e756c13faf2eb542d6/django/db/migrations/autodetector.py#L187-L190

Le mercredi 11 décembre 2019 12:27:43 UTC-5, Rich Rauenzahn a écrit :
>
> I've created a CompositeForeignKey constraint derived from Django's new 
> BaseConstraint.  It requires that I manually make a unique_together in any 
> of the referenced models views due to the DB internal requirements of 
> composite foreign keys.
>
> It mostly works -- except that when the operations are defined in the 
> migration, the order is critical -- the unique_together's need to be made 
> before the composite key SQL.
>
> For now, I just went in and manually changed the order of operations in 
> the migration to put the CompositeForeignKeys last.   Another way around 
> would be to comment out all the CompositeForeignKey declarations in my 
> models, migrate my unique_together's first, and then re-add the 
> CompositeForeignKeys.
>
> ...I'm wondering if there is a supported way to hook into the migration 
> creation process, give priorities to certain kinds of constraints, and then 
> sort the operations by this priority before they are emitted into a 
> migration.py.
>
> Or any other ideas to make this a bit more seamless?
>
> Rich
>

-- 
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/a41ba064-82b7-489d-9b57-7b48f57c4c94%40googlegroups.com.


Re: pip install Django==3.0

2019-12-02 Thread Simon Charette
Dear Uri,

> When I use pip to install a package, does it depend on the version of 
Python I'm using?

Yes, it does.

> I noticed that Django 3.0 doesn't support Python 3.5. But why does pip 
fail?

Pip will respect the supported version metadata of the package. There's no 
package available for the Django
and Python version constraints you provided.

Instead of getting a non-nonsensical SyntaxError crash when trying to run 
Django on Python 3.5 pip prevents
you from shooting yourself in the foot in the first place.

Simon

Le lundi 2 décembre 2019 11:06:18 UTC-5, Uri a écrit :
>
> Django users,
>
> When I use pip to install a package, does it depend on the version of 
> Python I'm using?
>
> pip install Django==3.0 fails with Python 3.5:
> https://travis-ci.org/speedy-net/speedy-net/builds/619671495 
>
> But it succeeds with Python 3.6 and 3.7. I noticed that Django 3.0 doesn't 
> support Python 3.5. But why does pip fail?
>  
> אורי
> u...@speedy.net 
>

-- 
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/f38c74ce-dd5b-428b-b785-003e19bf147b%40googlegroups.com.


Re: Django GIS query on annotated spatial field

2019-11-18 Thread Simon Charette
Hello Bill!

I'd try again with 3.0rc1 which was released today and file a bug report if 
it still crashes.

Cheers,
Simon

Le lundi 18 novembre 2019 06:08:29 UTC-5, Bill Bouzas a écrit :
>
> Good day Simon,
>
> I reproduced with Django 2.2.7, I receive the same error.
>
> Kind regards,
> Bill
>
> On Fri, 15 Nov 2019 at 17:19, Simon Charette  > wrote:
>
>> Can you reproduce with Django 2.2.7 (releases November 4th, 2019)
>>
>> Le vendredi 15 novembre 2019 06:04:32 UTC-5, Bill Bouzas a écrit :
>>>
>>> Good morning Simon,
>>>
>>> Sorry for the delayed response. I a using Django 2.2.6 (released October 
>>> 1st, 2019)
>>>
>>> Kind regards,
>>> Bill
>>>
>>> On Thu, 14 Nov 2019 at 16:41, Simon Charette  wrote:
>>>
>>>> Hello Bill,
>>>>
>>>> Could you give us more details about which version of Django you are 
>>>> using?
>>>>
>>>> There was a few Django bugs related to as_sql returning Union[list, 
>>>> tuple] as params that were
>>>> fixed in recent release but this one might not have been caught yet.
>>>>
>>>> Cheers,
>>>> Simon
>>>>
>>>> Le jeudi 14 novembre 2019 09:43:46 UTC-5, Bill Bouzas a écrit :
>>>>>
>>>>>
>>>>>
>>>>> I am currently building a web app based on GeoDjango and I want to 
>>>>> check if 
>>>>> a number of points lie within a multipolygon. To form the 
>>>>> multipolygon, I 
>>>>> check which areas are selected and then aggregate them into one 
>>>>> multipolygon with the following query: 
>>>>>
>>>>> area = Area.objects.filter(id__in = 
>>>>> area_ids).aggregate(area=Union('geom'))['area']print(area) 
>>>>>
>>>>> SRID=4326;MULTIPOLYGON (((5.014146 52.371687, 5.013973 52.371632, 
>>>>> 5.013238 52.37166, 5.012505 52.372437, 5.01294 52.372787, 5.012977 
>>>>> 52.373, 
>>>>> 5.013142 52.373072, 5.014488 52.373032, 5.014564 52.372957, 5.014701 
>>>>> 52.37272, 5.01461 52.372181, 5.014372 52.371786, 5.014146 52.371687)), 
>>>>> ((5.014054 52.367988, 5.014448 52.368027, 5.014532 52.367978, 5.014079 
>>>>> 52.367899, 5.014033 52.367822, 5.01398 52.367882, 5.012914 52.367781, 
>>>>> 5.013032 52.367372, 5.012751 52.367294, 5.00198 52.366278, 5.001809 
>>>>> 52.366739, 5.36 52.366614, 5.86 52.366682, 5.013941 52.367968, 
>>>>> 5.013987 52.36805, 5.014054 52.367988)), ((4.997837 52.350827, 4.997581 
>>>>> 52.350302, 4.996731 52.35072, 4.996493 52.350708, 4.991906 52.352949, 
>>>>> 4.989279 52.354708, 4.990234 52.354938, 4.993064 52.353655, 4.997837 
>>>>> 52.350827)), ((5.021518 52.384118, 5.018382 52.380388, 5.01628 52.377323, 
>>>>> 5.014382 52.37417, 5.014296 52.374171, 5.014094 52.37425, 5.014288 
>>>>> 52.374504, 5.014268 52.374785, 5.013763 52.374812, 5.013434 52.375018, 
>>>>> 5.013673 52.375082, 5.01377 52.375441, 5.014177 52.375737, 5.014467 
>>>>> 52.375531, 5.014801 52.375961, 5.014822 52.376498, 5.014295 52.376588, 
>>>>> 5.014194 52.376725, 5.014413 52.377446, 5.015047 52.378, 5.015372 
>>>>> 52.378016, 5.015413 52.377633, 5.01574 52.377412, 5.015965 52.377466, 
>>>>> 5.015873 52.378071, 5.016008 52.378355, 5.015993 52.378669, 5.016702 
>>>>> 52.380502, 5.016514 52.380922, 5.016989 52.381336, 5.017121 52.381644, 
>>>>> 5.017756 52.381984, 5.017666 52.382471, 5.018341 52.383453, 5.018662 
>>>>> 52.383813, 5.018769 52.383778, 5.019567 52.384011, 5.020317 52.383815, 
>>>>> 5.02067 52.38387, 5.022685 52.386085, 5.022946 52.386199, 5.023521 
>>>>> 52.386835, 5.023697 52.386851, 5.023905 52.386782, 5.021518 52.384118)), 
>>>>> ((4.980684 52.330761, 4.982519 52.330804, 4.983355 52.330747, 4.984946 
>>>>> 52.330428, 4.98604 52.329811, 4.987298 52.32893, 4.989045 52.327985, 
>>>>> 4.989604 52.327548, 4.990891 52.326142, 4.991615 52.324538, 4.992109 
>>>>> 52.323766, 4.995479 52.31931, 4.997103 52.317392, 4.997369 52.316672, 
>>>>> 4.997147 52.315905, 4.997091 52.314456, 4.997298 52.314196, 4.997456 
>>>>> 52.314246, 4.99786 52.313979, 5.001531 52.315911, 5.006523 52.319077, 
>>>>> 5.016134 52.324512, 5.016323 52.324237, 5.016653 52.322987, 5.017933 
>>>>> 52.323192, 5.018331 52.320249, 5.021543 52.302457, 5

Re: Conditional Order By

2019-11-15 Thread Simon Charette
Hello there,

You'll want to use Coalesce[0] for this purpose.

Model1.objects.order_by(Coalesce('effectual_rating', 'rating').desc())

Cheers,
Simon

[0] 
https://docs.djangoproject.com/en/2.2/ref/models/database-functions/#coalesce

Le vendredi 15 novembre 2019 13:32:46 UTC-5, Kev H a écrit :
>
> I have a model where a field can be null (and is most of the time).  
> However, I need to order_by this both this field and another field (the 2nd 
> field is never null) so that the results would be sorted by from high to 
> low (1st based on the possible null field if it is not null and then by the 
> 2nd field).
>
> Example:
>
> Model 1:
>   dollar_amount = Char()
>   rating = Int()
>   effectual_rating = Int(null=True, blank=True)
>
> Example Entries:
> $100, 5, Null
> $125, 4, 8
> $195, 3, 2
> $81, 7, Null
>
> So the end result of the query i would want it sorted like so from high to 
> low value:
> $125, 4, 8
> $81, 7, Null
> $100, 5, Null
> $195, 3, 2
>
>
> I have millions of rows so doing multiple queries and then looping through 
> those would be not feasible.  But I am not sure how to even start to setup 
> this query properly.
>
> Model1.objects.all().order_by(???)
>
> Any help would be appreciated.  Thanks!
>

-- 
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/96d77542-f58e-4059-9f7e-04128310de4a%40googlegroups.com.


Re: Django GIS query on annotated spatial field

2019-11-15 Thread Simon Charette
Can you reproduce with Django 2.2.7 (releases November 4th, 2019)

Le vendredi 15 novembre 2019 06:04:32 UTC-5, Bill Bouzas a écrit :
>
> Good morning Simon,
>
> Sorry for the delayed response. I a using Django 2.2.6 (released October 
> 1st, 2019)
>
> Kind regards,
> Bill
>
> On Thu, 14 Nov 2019 at 16:41, Simon Charette  > wrote:
>
>> Hello Bill,
>>
>> Could you give us more details about which version of Django you are 
>> using?
>>
>> There was a few Django bugs related to as_sql returning Union[list, 
>> tuple] as params that were
>> fixed in recent release but this one might not have been caught yet.
>>
>> Cheers,
>> Simon
>>
>> Le jeudi 14 novembre 2019 09:43:46 UTC-5, Bill Bouzas a écrit :
>>>
>>>
>>>
>>> I am currently building a web app based on GeoDjango and I want to check 
>>> if 
>>> a number of points lie within a multipolygon. To form the multipolygon, 
>>> I 
>>> check which areas are selected and then aggregate them into one 
>>> multipolygon with the following query: 
>>>
>>> area = Area.objects.filter(id__in = 
>>> area_ids).aggregate(area=Union('geom'))['area']print(area) 
>>>
>>> SRID=4326;MULTIPOLYGON (((5.014146 52.371687, 5.013973 52.371632, 
>>> 5.013238 52.37166, 5.012505 52.372437, 5.01294 52.372787, 5.012977 52.373, 
>>> 5.013142 52.373072, 5.014488 52.373032, 5.014564 52.372957, 5.014701 
>>> 52.37272, 5.01461 52.372181, 5.014372 52.371786, 5.014146 52.371687)), 
>>> ((5.014054 52.367988, 5.014448 52.368027, 5.014532 52.367978, 5.014079 
>>> 52.367899, 5.014033 52.367822, 5.01398 52.367882, 5.012914 52.367781, 
>>> 5.013032 52.367372, 5.012751 52.367294, 5.00198 52.366278, 5.001809 
>>> 52.366739, 5.36 52.366614, 5.86 52.366682, 5.013941 52.367968, 
>>> 5.013987 52.36805, 5.014054 52.367988)), ((4.997837 52.350827, 4.997581 
>>> 52.350302, 4.996731 52.35072, 4.996493 52.350708, 4.991906 52.352949, 
>>> 4.989279 52.354708, 4.990234 52.354938, 4.993064 52.353655, 4.997837 
>>> 52.350827)), ((5.021518 52.384118, 5.018382 52.380388, 5.01628 52.377323, 
>>> 5.014382 52.37417, 5.014296 52.374171, 5.014094 52.37425, 5.014288 
>>> 52.374504, 5.014268 52.374785, 5.013763 52.374812, 5.013434 52.375018, 
>>> 5.013673 52.375082, 5.01377 52.375441, 5.014177 52.375737, 5.014467 
>>> 52.375531, 5.014801 52.375961, 5.014822 52.376498, 5.014295 52.376588, 
>>> 5.014194 52.376725, 5.014413 52.377446, 5.015047 52.378, 5.015372 
>>> 52.378016, 5.015413 52.377633, 5.01574 52.377412, 5.015965 52.377466, 
>>> 5.015873 52.378071, 5.016008 52.378355, 5.015993 52.378669, 5.016702 
>>> 52.380502, 5.016514 52.380922, 5.016989 52.381336, 5.017121 52.381644, 
>>> 5.017756 52.381984, 5.017666 52.382471, 5.018341 52.383453, 5.018662 
>>> 52.383813, 5.018769 52.383778, 5.019567 52.384011, 5.020317 52.383815, 
>>> 5.02067 52.38387, 5.022685 52.386085, 5.022946 52.386199, 5.023521 
>>> 52.386835, 5.023697 52.386851, 5.023905 52.386782, 5.021518 52.384118)), 
>>> ((4.980684 52.330761, 4.982519 52.330804, 4.983355 52.330747, 4.984946 
>>> 52.330428, 4.98604 52.329811, 4.987298 52.32893, 4.989045 52.327985, 
>>> 4.989604 52.327548, 4.990891 52.326142, 4.991615 52.324538, 4.992109 
>>> 52.323766, 4.995479 52.31931, 4.997103 52.317392, 4.997369 52.316672, 
>>> 4.997147 52.315905, 4.997091 52.314456, 4.997298 52.314196, 4.997456 
>>> 52.314246, 4.99786 52.313979, 5.001531 52.315911, 5.006523 52.319077, 
>>> 5.016134 52.324512, 5.016323 52.324237, 5.016653 52.322987, 5.017933 
>>> 52.323192, 5.018331 52.320249, 5.021543 52.302457, 5.019476 52.302498, 
>>> 5.018104 52.302624, 5.016685 52.302881, 5.014265 52.303677, 5.014229 
>>> 52.30359, 5.012989 52.303605, 5.012279 52.303522, 5.011623 52.303337, 
>>> 5.011051 52.303029, 5.009933 52.302103, 5.008961 52.301726, 5.007892 
>>> 52.301522, 5.007544 52.300868, 5.005265 52.298393, 5.003835 52.298509, 
>>> 5.003233 52.297389, 5.003227 52.296065, 5.002484 52.296035, 5.001851 
>>> 52.295879, 5.001789 52.292793, 4.998814 52.290239, 4.998551 52.290234, 
>>> 4.998452 52.289839, 4.998298 52.289815, 4.997475 52.289118, 4.994117 
>>> 52.289288, 4.990459 52.289603, 4.983506 52.290368, 4.982889 52.289642, 
>>> 4.975148 52.286342, 4.973249 52.285236, 4.973072 52.285022, 4.972611 
>>> 52.284846, 4.969726 52.283121, 4.969378 52.281789, 4.968815 52.280973, 
>>> 4.968753 52.280726, 4.968328 52.280412, 4.967674 52.279582, 4.967576 
>>> 52.279561, 4.966842 52.27987

Re: Django 2.2: how to use to a field "from a foreign model", in a CheckConstraint: ?

2019-11-14 Thread Simon Charette
So this happened not to be supported in Django 3.0 either.

But https://github.com/django/django/pull/12067 should add support for it.

Le jeudi 14 novembre 2019 15:50:34 UTC-5, Simon Charette a écrit :
>
> For the record I haven' tested the above myself.
>
> It might only work on Django 3.0+ and require you to pass 
> `output_field=BooleanField()` to Func.
>
> Le jeudi 14 novembre 2019 09:46:48 UTC-5, Simon Charette a écrit :
>>
>> Hello there,
>>
>> I guess your example is not the best since this check could be defined on 
>> Author.Meta.constraints
>> directly but if you wanted to define such a check on Book anyway you'll 
>> have to define a function
>> and refer to it in the check constraint using Func.
>>
>> Using RunSQL in your migrations
>>
>> RunSQL("""
>> create or replace function author_age_gt(int, int) returns boolean as $$
>> select exists (
>> select 1
>> from "author"
>> where id = $1 and age > $2
>> );
>> $$ language sql;
>> """)
>>
>> And then you could define your CheckConstraint as
>>
>> CheckConstraint(Func(F('author'), 18, function='author_age_gt'), 
>> name='age_check')
>>
>> Cheers,
>> Simon
>>
>> Le jeudi 14 novembre 2019 02:45:32 UTC-5, Olivier a écrit :
>>>
>>> Hello,
>>>
>>> Let say I want to enforce a database constraint saying a "book's author 
>>> age is over 18".
>>> As you may guess, books and authors are each described with a Model 
>>> subclass with a foreign key (in this example each book is written by a 
>>> single author) linking both.
>>>
>>> class Author(models.Model):
>>> age = models.SmallIntegerField()
>>>
>>>
>>> class Book(models.Model):
>>> author = models.ForeignKey(Author, on_delete=models.PROTECT)
>>>
>>> class Meta:
>>> constraints = [
>>>models.CheckConstraint(check=models.Q(__gt=18), 
>>> name='age_check'),
>>> ]
>>>
>>>
>>> I've tried replacing  above with author_age or author__age.
>>> In both cases, makemigrations works but migrate fails with:
>>> django.core.exceptions.FieldError: Joined field references are not 
>>> permitted in this query
>>>
>>>
>>> Can I work around this ?
>>> Any working example ?
>>>
>>> Best 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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/d2b4f7cf-8334-40eb-ba8b-af0151424da9%40googlegroups.com.


Re: Django 2.2: how to use to a field "from a foreign model", in a CheckConstraint: ?

2019-11-14 Thread Simon Charette
For the record I haven' tested the above myself.

It might only work on Django 3.0+ and require you to pass 
`output_field=BooleanField()` to Func.

Le jeudi 14 novembre 2019 09:46:48 UTC-5, Simon Charette a écrit :
>
> Hello there,
>
> I guess your example is not the best since this check could be defined on 
> Author.Meta.constraints
> directly but if you wanted to define such a check on Book anyway you'll 
> have to define a function
> and refer to it in the check constraint using Func.
>
> Using RunSQL in your migrations
>
> RunSQL("""
> create or replace function author_age_gt(int, int) returns boolean as $$
> select exists (
> select 1
> from "author"
> where id = $1 and age > $2
> );
> $$ language sql;
> """)
>
> And then you could define your CheckConstraint as
>
> CheckConstraint(Func(F('author'), 18, function='author_age_gt'), 
> name='age_check')
>
> Cheers,
> Simon
>
> Le jeudi 14 novembre 2019 02:45:32 UTC-5, Olivier a écrit :
>>
>> Hello,
>>
>> Let say I want to enforce a database constraint saying a "book's author 
>> age is over 18".
>> As you may guess, books and authors are each described with a Model 
>> subclass with a foreign key (in this example each book is written by a 
>> single author) linking both.
>>
>> class Author(models.Model):
>> age = models.SmallIntegerField()
>>
>>
>> class Book(models.Model):
>> author = models.ForeignKey(Author, on_delete=models.PROTECT)
>>
>> class Meta:
>> constraints = [
>>models.CheckConstraint(check=models.Q(__gt=18), 
>> name='age_check'),
>> ]
>>
>>
>> I've tried replacing  above with author_age or author__age.
>> In both cases, makemigrations works but migrate fails with:
>> django.core.exceptions.FieldError: Joined field references are not 
>> permitted in this query
>>
>>
>> Can I work around this ?
>> Any working example ?
>>
>> Best 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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/17a81a8f-85c7-4df4-a2c2-a0b6096a8f00%40googlegroups.com.


Re: Django GIS query on annotated spatial field

2019-11-14 Thread Simon Charette
Hello Bill,

Could you give us more details about which version of Django you are using?

There was a few Django bugs related to as_sql returning Union[list, tuple] 
as params that were
fixed in recent release but this one might not have been caught yet.

Cheers,
Simon

Le jeudi 14 novembre 2019 09:43:46 UTC-5, Bill Bouzas a écrit :
>
>
>
> I am currently building a web app based on GeoDjango and I want to check 
> if 
> a number of points lie within a multipolygon. To form the multipolygon, I 
> check which areas are selected and then aggregate them into one 
> multipolygon with the following query: 
>
> area = Area.objects.filter(id__in = 
> area_ids).aggregate(area=Union('geom'))['area']print(area) 
>
> SRID=4326;MULTIPOLYGON (((5.014146 52.371687, 5.013973 52.371632, 5.013238 
> 52.37166, 5.012505 52.372437, 5.01294 52.372787, 5.012977 52.373, 5.013142 
> 52.373072, 5.014488 52.373032, 5.014564 52.372957, 5.014701 52.37272, 
> 5.01461 52.372181, 5.014372 52.371786, 5.014146 52.371687)), ((5.014054 
> 52.367988, 5.014448 52.368027, 5.014532 52.367978, 5.014079 52.367899, 
> 5.014033 52.367822, 5.01398 52.367882, 5.012914 52.367781, 5.013032 
> 52.367372, 5.012751 52.367294, 5.00198 52.366278, 5.001809 52.366739, 
> 5.36 52.366614, 5.86 52.366682, 5.013941 52.367968, 5.013987 
> 52.36805, 5.014054 52.367988)), ((4.997837 52.350827, 4.997581 52.350302, 
> 4.996731 52.35072, 4.996493 52.350708, 4.991906 52.352949, 4.989279 
> 52.354708, 4.990234 52.354938, 4.993064 52.353655, 4.997837 52.350827)), 
> ((5.021518 52.384118, 5.018382 52.380388, 5.01628 52.377323, 5.014382 
> 52.37417, 5.014296 52.374171, 5.014094 52.37425, 5.014288 52.374504, 
> 5.014268 52.374785, 5.013763 52.374812, 5.013434 52.375018, 5.013673 
> 52.375082, 5.01377 52.375441, 5.014177 52.375737, 5.014467 52.375531, 
> 5.014801 52.375961, 5.014822 52.376498, 5.014295 52.376588, 5.014194 
> 52.376725, 5.014413 52.377446, 5.015047 52.378, 5.015372 52.378016, 
> 5.015413 52.377633, 5.01574 52.377412, 5.015965 52.377466, 5.015873 
> 52.378071, 5.016008 52.378355, 5.015993 52.378669, 5.016702 52.380502, 
> 5.016514 52.380922, 5.016989 52.381336, 5.017121 52.381644, 5.017756 
> 52.381984, 5.017666 52.382471, 5.018341 52.383453, 5.018662 52.383813, 
> 5.018769 52.383778, 5.019567 52.384011, 5.020317 52.383815, 5.02067 
> 52.38387, 5.022685 52.386085, 5.022946 52.386199, 5.023521 52.386835, 
> 5.023697 52.386851, 5.023905 52.386782, 5.021518 52.384118)), ((4.980684 
> 52.330761, 4.982519 52.330804, 4.983355 52.330747, 4.984946 52.330428, 
> 4.98604 52.329811, 4.987298 52.32893, 4.989045 52.327985, 4.989604 
> 52.327548, 4.990891 52.326142, 4.991615 52.324538, 4.992109 52.323766, 
> 4.995479 52.31931, 4.997103 52.317392, 4.997369 52.316672, 4.997147 
> 52.315905, 4.997091 52.314456, 4.997298 52.314196, 4.997456 52.314246, 
> 4.99786 52.313979, 5.001531 52.315911, 5.006523 52.319077, 5.016134 
> 52.324512, 5.016323 52.324237, 5.016653 52.322987, 5.017933 52.323192, 
> 5.018331 52.320249, 5.021543 52.302457, 5.019476 52.302498, 5.018104 
> 52.302624, 5.016685 52.302881, 5.014265 52.303677, 5.014229 52.30359, 
> 5.012989 52.303605, 5.012279 52.303522, 5.011623 52.303337, 5.011051 
> 52.303029, 5.009933 52.302103, 5.008961 52.301726, 5.007892 52.301522, 
> 5.007544 52.300868, 5.005265 52.298393, 5.003835 52.298509, 5.003233 
> 52.297389, 5.003227 52.296065, 5.002484 52.296035, 5.001851 52.295879, 
> 5.001789 52.292793, 4.998814 52.290239, 4.998551 52.290234, 4.998452 
> 52.289839, 4.998298 52.289815, 4.997475 52.289118, 4.994117 52.289288, 
> 4.990459 52.289603, 4.983506 52.290368, 4.982889 52.289642, 4.975148 
> 52.286342, 4.973249 52.285236, 4.973072 52.285022, 4.972611 52.284846, 
> 4.969726 52.283121, 4.969378 52.281789, 4.968815 52.280973, 4.968753 
> 52.280726, 4.968328 52.280412, 4.967674 52.279582, 4.967576 52.279561, 
> 4.966842 52.279878, 4.966491 52.280096, 4.966166 52.28098, 4.965709 
> 52.280578, 4.965316 52.280448, 4.962548 52.280285, 4.962244 52.280207, 
> 4.961054 52.278174, 4.959968 52.278346, 4.958664 52.278343, 4.957809 
> 52.278612, 4.957144 52.278671, 4.956564 52.278641, 4.955241 52.278305, 
> 4.95184 52.282443, 4.952091 52.282534, 4.946407 52.288562, 4.937142 
> 52.29947, 4.934869 52.301943, 4.934936 52.301969, 4.933217 52.303553, 
> 4.932721 52.304263, 4.931682 52.305025, 4.930256 52.30643, 4.929473 
> 52.307414, 4.929825 52.307515, 4.929416 52.307829, 4.929909 52.308104, 
> 4.929328 52.308532, 4.929615 52.308813, 4.930303 52.309182, 4.930065 
> 52.30934, 4.931656 52.310267, 4.934138 52.311903, 4.936352 52.312663, 
> 4.935229 52.313889, 4.938724 52.315091, 4.938738 52.315636, 4.938042 
> 52.316505, 4.93983 52.31712, 4.940332 52.318302, 4.939585 52.31912, 
> 4.941043 52.31962, 4.940205 52.320815, 4.939927 52.321936, 4.9

Re: Django 2.2: how to use to a field "from a foreign model", in a CheckConstraint: ?

2019-11-14 Thread Simon Charette
Hello there,

I guess your example is not the best since this check could be defined on 
Author.Meta.constraints
directly but if you wanted to define such a check on Book anyway you'll 
have to define a function
and refer to it in the check constraint using Func.

Using RunSQL in your migrations

RunSQL("""
create or replace function author_age_gt(int, int) returns boolean as $$
select exists (
select 1
from "author"
where id = $1 and age > $2
);
$$ language sql;
""")

And then you could define your CheckConstraint as

CheckConstraint(Func(F('author'), 18, function='author_age_gt'), 
name='age_check')

Cheers,
Simon

Le jeudi 14 novembre 2019 02:45:32 UTC-5, Olivier a écrit :
>
> Hello,
>
> Let say I want to enforce a database constraint saying a "book's author 
> age is over 18".
> As you may guess, books and authors are each described with a Model 
> subclass with a foreign key (in this example each book is written by a 
> single author) linking both.
>
> class Author(models.Model):
> age = models.SmallIntegerField()
>
>
> class Book(models.Model):
> author = models.ForeignKey(Author, on_delete=models.PROTECT)
>
> class Meta:
> constraints = [
>models.CheckConstraint(check=models.Q(__gt=18), 
> name='age_check'),
> ]
>
>
> I've tried replacing  above with author_age or author__age.
> In both cases, makemigrations works but migrate fails with:
> django.core.exceptions.FieldError: Joined field references are not 
> permitted in this query
>
>
> Can I work around this ?
> Any working example ?
>
> Best 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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/2fa2ba09-2323-4b4a-8e7c-0f0712c561e0%40googlegroups.com.


Re: Performing a query returns an error

2019-11-13 Thread Simon Charette
Hello Patrick,

>From what I understand you are relying on unmanaged (Meta.managed=False) 
models
to use the ORM to query an externally managed database.

The part you missed here is that the ORM maps ForeignKey fields to database 
columns with
a "_id" suffix by default. In your case that means it expects a "pid_id" 
column to exist for the
Budgettable.pid field.

If you column is actually named "pid" you'll want to use the "db_column" 
option to let the ORM
know about it[0]. That is `db_column=pid` in your `pid = ForeignKey` 
definition.

Cheers,
Simon

[0] 
https://docs.djangoproject.com/en/2.2/ref/models/fields/#database-representation

Le mercredi 13 novembre 2019 10:28:30 UTC-5, Patrick Carra a écrit :
>
> Hello all I am new to django and I am trying to do a query to that will 
> provide me with information from multiple tables I have included my 
> models.py file below:
> Enter code hclass Circuitinfotable(models.Model):
> pid = models.CharField(max_length=255, blank=True, null=True)
> circuitid = models.CharField(primary_key=True, max_length=255, 
> blank=True, null=False)
> bandwidth = models.CharField(max_length=255, blank=True, null=True)
> region = models.CharField(max_length=255, blank=True, null=True)
> 
>
> class Meta:
> managed = False
> db_table = 'circuitinfotable'
>
>
> class Budgettable(models.Model):
> id = models.IntegerField(primary_key=True)
> circuitid = models.CharField(max_length=255, blank=True, null=True)
> pid = models.ForeignKey('Circuitinfotable', on_delete=models.CASCADE)
> monthnum = models.IntegerField(blank=True, null=True)
> yearnum = models.IntegerField(blank=True, null=True)
> budgetmrc = models.TextField(blank=True, null=True)  # This field type 
> is a guess.
> actualmrc = models.TextField(blank=True, null=True)  # This field type 
> is a guess.
> region = models.CharField(max_length=255, blank=True, null=True)
>
> class Meta:
> managed = False
> db_table = 'budgettable'
>
>
> the code I was using to query this is below:
> >>> from viewLit.models import Circuitinfotable, Budgettable
> >>> btc = Circuitinfotable.objects.get(circuitid='ETH100GB-23349286')
> >>> btc.budgettable_set.all()
> Traceback (most recent call last):
>   File 
> "/home/db_user/ciopsdb/venv/lib64/python3.6/site-packages/django/db/backends/utils.py",
>  
> line 84, in _execute
> return self.cursor.execute(sql, params)
> psycopg2.errors.UndefinedColumn: column budgettable.pid_id does not exist
> LINE 1: ...CT "budgettable"."id", "budgettable"."circuitid", "budgettab...
>  ^
> HINT:  Perhaps you meant to reference the column "budgettable.pid".
>
>
> The above exception was the direct cause of the following exception:
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File 
> "/home/db_user/ciopsdb/venv/lib64/python3.6/site-packages/django/db/models/query.py",
>  
> line 250, in __repr__
> data = list(self[:REPR_OUTPUT_SIZE + 1])
>   File 
> "/home/db_user/ciopsdb/venv/lib64/python3.6/site-packages/django/db/models/query.py",
>  
> line 274, in __iter__
> self._fetch_all()
>   File 
> "/home/db_user/ciopsdb/venv/lib64/python3.6/site-packages/django/db/models/query.py",
>  
> line 1242, in _fetch_all
> self._result_cache = list(self._iterable_class(self))
>   File 
> "/home/db_user/ciopsdb/venv/lib64/python3.6/site-packages/django/db/models/query.py",
>  
> line 55, in __iter__
> results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, 
> chunk_size=self.chunk_size)
>   File 
> "/home/db_user/ciopsdb/venv/lib64/python3.6/site-packages/django/db/models/sql/compiler.py",
>  
> line 1100, in execute_sql
> cursor.execute(sql, params)
>   File 
> "/home/db_user/ciopsdb/venv/lib64/python3.6/site-packages/django/db/backends/utils.py",
>  
> line 99, in execute
> return super().execute(sql, params)
>   File 
> "/home/db_user/ciopsdb/venv/lib64/python3.6/site-packages/django/db/backends/utils.py",
>  
> line 67, in execute
> return self._execute_with_wrappers(sql, params, many=False, 
> executor=self._execute)
>   File 
> "/home/db_user/ciopsdb/venv/lib64/python3.6/site-packages/django/db/backends/utils.py",
>  
> line 76, in _execute_with_wrappers
> return executor(sql, params, many, context)
>   File 
> "/home/db_user/ciopsdb/venv/lib64/python3.6/site-packages/django/db/backends/ut

Re: django 2.0 to django 2.2 migration

2019-10-17 Thread Simon Charette
This was tracked in https://code.djangoproject.com/ticket/30673 and fixed 
and 2.2.5[0]

Cheers,
Simon

[0] 
https://github.com/django/django/commit/1265a26b2fa3cbd73a2bccd91b700268bc28bc07

Le jeudi 17 octobre 2019 10:31:50 UTC-4, Sijoy Chirayath a écrit :
>
> I am changing one of my application from djanog 2.0.6 to 2.2.2. I have 2 
> model files in two different app consists of model classes. Each model file 
> i mapped to two different databases. Some of the model classes in both 
> model files have the same name for dt_table in the meta class. So while 
> doing makemigrations i am getting an error saying that 
> dt_table tbl_activity_log is used by multiple models: usermanagement, 
> master. But the same is working perfectly in django 2.0.6 version. 
> Following are the error details. 
> Please help.
>
> tbl_activity_log: (models.E028) db_table 'tbl_activity_log' is used by 
> multiple models: usermanagement.ActivityLog, master.ActivityLog.
> tbl_audit_log: (models.E028) db_table 'tbl_audit_log' is used by multiple 
> models: usermanagement.AuditLog, master.AuditLog.
> tbl_business_groups: (models.E028) db_table 'tbl_business_groups' is used 
> by multiple models: usermanagement.BusinessGroups, master.BusinessGroups.
> tbl_categories: (models.E028) db_table 'tbl_categories' is used by 
> multiple models: usermanagement.Categories, master.Categories.
> tbl_client_configuration: (models.E028) db_table 
> 'tbl_client_configuration' is used by multiple models: 
> usermanagement.ClientConfiguration, master.ClientConfiguration.
> tbl_client_groups: (models.E028) db_table 'tbl_client_groups' is used by 
> multiple models: usermanagement.ClientGroups, master.ClientGroups.
> tbl_countries: (models.E028) db_table 'tbl_countries' is used by multiple 
> models: usermanagement.Countries, master.Countries.
> tbl_divisions: (models.E028) db_table 'tbl_divisions' is used by multiple 
> models: usermanagement.Divisions, master.Divisions.
> tbl_domain_countries: (models.E028) db_table 'tbl_domain_countries' is 
> used by multiple models: usermanagement.DomainCountries, 
> master.DomainCountries.
> tbl_domains: (models.E028) db_table 'tbl_domains' is used by multiple 
> models: usermanagement.Domains, master.Domains.
> tbl_form_type: (models.E028) db_table 'tbl_form_type' is used by multiple 
> models: usermanagement.FormType, master.FormType.
> tbl_forms: (models.E028) db_table 'tbl_forms' is used by multiple models: 
> usermanagement.Forms, master.Forms.
> tbl_legal_entities: (models.E028) db_table 'tbl_legal_entities' is used by 
> multiple models: usermanagement.LegalEntities, master.LegalEntities.
> tbl_organisation: (models.E028) db_table 'tbl_organisation' is used by 
> multiple models: usermanagement.Organisation, master.Organisation.
> tbl_reminder_settings: (models.E028) db_table 'tbl_reminder_settings' is 
> used by multiple models: usermanagement.ReminderSettings, 
> master.ReminderSettings.
> tbl_service_providers: (models.E028) db_table 'tbl_service_providers' is 
> used by multiple models: usermanagement.ServiceProviders, 
> master.ServiceProviders.
> tbl_timezones: (models.E028) db_table 'tbl_timezones' is used by multiple 
> models: usermanagement.TimeZones, master.TimeZones.
> tbl_units: (models.E028) db_table 'tbl_units' is used by multiple models: 
> usermanagement.Units, master.Units.
> tbl_user_category: (models.E028) db_table 'tbl_user_category' is used by 
> multiple models: usermanagement.UserCategory, master.UserCategory.
> tbl_users: (models.E028) db_table 'tbl_users' is used by multiple models: 
> usermanagement.Users, master.Users.
> tbl_verification_type: (models.E028) db_table 'tbl_verification_type' is 
> used by multiple models: usermanagement.VerificationType, 
> master.VerificationType.
>

-- 
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/159ab704-3af4-4b6e-b2e9-55ca7e67a660%40googlegroups.com.


Re: QuerySet not iterable

2019-10-08 Thread Simon Charette
Hello there,

>From looking at your code (super() calls) it seems like your are using 
Python 2.

 We've seen similar reports about stdlib functions hiding system level 
exceptions
instead of surfacing them[0] so that might it.

It's hard to tell without the full traceback though.

Best,
Simon

[0] https://code.djangoproject.com/ticket/26600

Le lundi 7 octobre 2019 22:16:16 UTC-4, Abhijeet Viswa a écrit :
>
> Hey guys, 
>
> I need a help with a quirky bug while iterating over a QuerySet:
>
>> TypeError: argument of type 'QuerySet' is not iterable
>
>
> The following is the block of code that produces the error: (the save 
> method overrides the default save method in a Model called *Transaction*)
>
> def save(self, *args, **kwargs):
> obj = self
> if not obj.ref_number:  # the line of code throwing the error
> transactions = Transaction.objects.values_list("ref_number", 
> flat=True) # cache the list
> while True:
> ref_number = random.randint(11, 99)
> if ref_number not in transactions:
> obj.ref_number = ref_number
> super(Transaction, obj).save(*args, **kwargs)
> return
> else:
> super(Transaction, obj).save(*args, **kwargs)
>
>
> This piece of code was working fine until we had modified (what we thought 
> to be) an unrelated part of the source: (this is the modified line of code)
> items = OrderItem.objects.prefetch_related('toppings').select_related(
> 'item').select_related('item__category')
> order = Order.objects.filter(uuid=order_uuid).prefetch_related(
> Prefetch(
> lookup='items',
> queryset=items
> )
> ).select_related('outlet').select_related('user').select_related(
> 'outlet__group') \
>  .select_for_update(of=('self', 'outlet'))
>
>
> We basically added a call to the *select_for_update. *This was required 
> by us since we are modifying both the *Order *as well as *Outlet *models. 
> (Also, the *Transaction* model is a super-model for the *Order *model)
>
> My best guess is that the select_for_update locks certain rows of the the 
> *Order*, *Transaction *and a bunch of other models. This results in the 
> line of code failing because the query to list the value fails. However, I 
> tested this hypothesis out by running a *select_for_update*, populating 
> the *QuerySet *returned and then sleeping for a while while I ran a 
> different query on the Model for which rows were locked. This ran perfectly 
> fine, with no problems.
>
> We are using PostgreSQL as our backend database. Any help would be greatly 
> appreciated. 
>
> Thanks
>
>

-- 
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/9954ffee-6dca-42e0-9943-d73ad0137ed1%40googlegroups.com.


Channels chat consumer behaves differently in prodcution vs development

2019-10-06 Thread Adam Simon


I am using channels 2.x (along with nginx, daphne, redis and gunicorn) 


In the local console I can see the user data I added in the chat consumer 
but not in my production environment 


(in production everything else works, but the user is undefined. Note: the 
user is logged in.


Does anyone have any idea why that might be?


I followed the doc tutorial and the only thing i added was the line 
commented below


class ChatConsumer(WebsocketConsumer):

def chat_message(self, event): 
message = event['message'] # Send message to WebSocket 
self.send(text_data=json.dumps({
'user': self.scope["user"].first_name, # <<< this is the line I 
added 
'message': message 
}))


Thanks,

Adam 

-- 
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/83adb17f-da67-4c2e-aec2-658566a43e7e%40googlegroups.com.


Re: Django Foreign Object

2019-09-26 Thread Simon Charette
This error comes from ForeignObject.resolve_related_fields[0].

If you are using ForeignObject directly you have an incompatible 
from_fields and to_fields
definition. It's hard to debug further without the full traceback.

Cheer,
Simon

[0] 
https://github.com/django/django/blob/4122d9d3f1983eea612f236e941d937bd8589a0d/django/db/models/fields/related.py#L602

Le jeudi 26 septembre 2019 10:48:08 UTC+2, Davin Pore a écrit :
>
> What is the meaning of the this error because the value of these 
> attributes are in string.
>
>
> [image: cap1.JPG]
>

-- 
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/9e6b6030-11ea-4007-aab5-6145f66bac96%40googlegroups.com.


Re: MultipleObjectsReturned: get() returned more than one Site -- it returned 2!

2019-09-05 Thread Simon Charette
It's hard to tell what's wrong from the limited context you provided but 
whatever code
is in django_sites_extensions is highly suspicious.

Best,
Simon

Le jeudi 5 septembre 2019 18:02:49 UTC-4, gh a écrit :
>
> Traceback (most recent call last):
>File 
> "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/core/handlers/base.py",
>  
> line 108, in get_response
>response = middleware_method(request)
>File 
> "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/contrib/sites/middleware.py",
>  
> line 10, in process_request
>request.site = get_current_site(request)
> File 
> "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/contrib/sites/shortcuts.py",
>  
> line 15, in get_current_site
> return Site.objects.get_current(request)
> File 
> "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django_sites_extensions/models.py",
>  
> line 40, in patched_get_current
>  return self._get_site_by_request(request)  # pylint: 
> disable=protected-access
> File 
> "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django_sites_extensions/models.py",
>  
> line 92, in patched_get_site_by_request
>site = self.get(domain__iexact=host)
> File 
> "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/db/models/manager.py",
>  
> line 127, in manager_method
> return getattr(self.get_queryset(), name)(*args, **kwargs)
> File 
> "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/db/models/query.py",
>  
> line 338, in get
> (self.model._meta.object_name, num)
> MultipleObjectsReturned: get() returned more than one Site -- it 
> returned 2!
>

-- 
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/9c938ac7-236b-4f29-a959-858a7db197f3%40googlegroups.com.


Re: Error: Not able to create table using models (Backend mysql)

2019-09-03 Thread Simon Charette
Django 2.0 only supports MySQL 5.5+.

I suspect you're getting a syntax error when Django tries to create a table 
mapping
a model with a DateTimeField since it resolves to DATETIME(6) which is not 
supported
on MySQL < 5.5.

Cheers,
Simon

Le mardi 3 septembre 2019 09:58:19 UTC-4, johnsi rani a écrit :
>
>
>
> i nstalled django2 and mysql 5.0
>> I am getting this error while i give python manage.py migrate
>>
>> raise MigrationSchemaMissing("Unable to create the django_migrations 
>> table (%s)" % exc)
>> django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create 
>> the django_migrations table ((1064, "You have an error in your SQL syntax; 
>> check the manual that corresponds to your MySQL server version for the 
>> right syntax to use near '(6) NOT NULL)' at line 1"))
>>
>>

-- 
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/5f9b7518-952d-4639-a9b8-0304a11ffa91%40googlegroups.com.


Re: Aggregating the results of a .union query without using .raw, is it possible?

2019-08-19 Thread Simon Charette
I'm afraid the ORM doesn't support aggregation over unions yet else I would
have expected the following to work.

objects = Model.objects
querysets = (
objects.filter(city=city).values(
'date', weighted_car_crashes=F('car_crashes') * weight
) for city, weight in weights
)
union = itertools.reduce(QuerySet.union, querysets, querysets[0])
queryset = union.annotate(cc=Sum('weighted_car_crashes')).values('date', 
'cc')

Best,
Simon

Le lundi 19 août 2019 17:10:47 UTC-4, Jo a écrit :
>
> I have a table that looks like this
>
> datecar_crashes city
> 01.01   1   Washington
> 01.02   4   Washington
> 01.03   0   Washington
> 01.04   2   Washington
> 01.05   0   Washington
> 01.06   3   Washington
> 01.07   4   Washington
> 01.08   1   Washington
> 01.01   0   Detroit
> 01.02   2   Detroit
> 01.03   4   Detroit
> 01.04   2   Detroit
> 01.05   0   Detroit
> 01.06   3   Detroit
> 01.07   1   Detroit
>
>
> I want to know how many car crashes for each day happened in the entire 
> nation, and I can do that with this:
>
>
> Model.values("date") \
> .annotate(car_crashes=Sum('car_crashes')) \
> .values("date", "car_crashes")
>
>
>
> Now, let's suppose I have an array like this:
>
> weights = [
> {
> "city": "Washington",
> "weight": 1,
> },
> {
> "city": "Detroit",
> "weight": 2,
> }
> ]
>
>
>
> This means that Detroit's car crashes should be multiplied by 2 before 
> being aggregated with Washington's.
>
> It can be done like this:
>
> from django.db.models import IntegerField
>
>
> when_list = [When(city=w['city'], then=w['weight']) for w in weights]
> case_params = {'default': 1, 'output_field': IntegerField()}
>
>
> Model.objects.values('date') \
> .annotate(
> weighted_car_crashes=Sum(
> F('car_crashes') * Case(*when_list, **case_params)
> ))
>
> However, this generates very slow SQL code, especially as more properties 
> and a larger array are introduced.
>
> Another solution which is way faster but still sub-optimal is using pandas 
> to :
>
> aggregated = false
> for weight in weights:
>
>  ag = Model.values("date") \
>  .annotate(car_crashes=Sum('car_crashes')) \
>  .values("date", "car_crashes")
>
>
>  if aggregated is False:
>  aggregated = ag
>  else:
>  aggregated = aggregated.union(ag)
>
>
> aggregated = pd.DataFrame(aggregated)
> if len(weights) > 1:
>  aggregated = aggregated.groupby("date", as_index=False).sum(level=[1])
>
>
> This is faster, but still not as fast as what happens if, before calling 
> pandas, I take the aggregated.query string and
> wrap it with a few lines of SQL.
>
>
> SELECT "date", sum("car_crashes") FROM (
>
>
> // String from Python
> str(aggregated.query)
>
>
> )
>
>
> This works perfectly when pasted into my database SQL. I could do this in 
> Python/Django using .raw() but the documentation says to ask here before 
> using .raw() as mostly anything could be acomplished with the ORM.
>
> Yet, I don't see how. Once I call .union on 2 querysets, I cannot 
> aggregate further.
>
> aggregated.union(ag).annotate(cc=Sum('car_crashes'))
>
> gives
>
> Cannot compute Sum('car_crashes'): 'car_crashes' is an aggregate
>
>
>
>
> Is this possible to do with the Django ORM or should I use .raw()?
>

-- 
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/3e1aedd7-8eb8-4fd6-9116-ed835719deb6%40googlegroups.com.


Re: Duplicated django_content_type Query

2019-08-16 Thread Simon Charette
Hello there,

These queries should be cached by ContentTypeManager[0] so something must 
be broken
in your Django install or monkey patching this method.

Simon

[0] 
https://github.com/django/django/blob/7da6a28a447dc0db2a2c6ef31894094eb968f408/django/contrib/contenttypes/models.py#L34-L44

Le vendredi 16 août 2019 07:18:08 UTC-4, Gaurav Ravindra Bole a écrit :
>
> [image: Screenshot from 2019-08-16 13-47-45.jpg]
>
>
>
> How we avoid this Duplicated django_content_type Query
>

-- 
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/3b549f51-94ed-4fc9-bdb1-72c166424f8e%40googlegroups.com.


Re: Recreating SQL query in ORM

2019-07-31 Thread Simon Charette
Hello,

assuming you have a FullMatch model mapped to your FullMatches table
the following should do.

FullMatch.objects.filter(
job_id=job_id,
).values(
seq=Concat('loading_code', ...),
ids=Concat('loading_id', ),
).annotate(
total=Count('*'),
).order_by('-total')

Using .values() before an annotation of an aggregate function uses the 
provided columns
from grouping.

Cheers,
Simon

Le mardi 30 juillet 2019 12:56:56 UTC-4, Jonathan Spicer a écrit :
>
> Hello,
>
> I have an sql query that I would like to recreate using the ORM. Would it 
> be possible for someone to give me some pointers.
>
> select count(*) as total,
> 
> concat(loading_code,code1_code,code2_code,code3_code,code4_code) as seq,
> 
> concat(loading_id,',',code1_id,',',code2_id,',',code3_id,',',code4_id) as 
> ids
> from FullMatches where job_id = %s group by seq, ids order 
> by total desc
>
> Thanks in advance.
>
> Johnny
>

-- 
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/276bf123-6990-4594-a9cf-8e9a8432d40e%40googlegroups.com.


Re: What's the best way to find the number of database accesses being done?

2019-07-23 Thread Simon Charette
Hello Don,

Django logs all database queries to the django.db.backends logger. It is not
redirected to STDOUT when using the default settings.LOGGING configuration
but you can enable it yourself[0].

If you wan to assert against a fixed number of queries you can use the
assertNumQueries context manager[1] provided by SimpleTestCase and its
subclasses to do that.

For an easy to setup and per-view breakdown of the number of queries I
suggest you install the django-debug-toolbar[2] and enable the SQL panel.

For more details about optimizing database accesses within a Django project
I suggest you have a look at the dedicated section of the documentation[3].
I've filed a ticket to make sure bulk_update is also mentioned in this 
section
of the documentation.

Cheers,
Simon

[0] https://www.dabapps.com/blog/logging-sql-queries-django-13/
[1] 
https://docs.djangoproject.com/en/2.2/topics/testing/tools/#django.test.TransactionTestCase.assertNumQueries
[2] https://django-debug-toolbar.readthedocs.io/en/latest/
[3] https://docs.djangoproject.com/en/2.2/topics/db/optimization/

Le mardi 23 juillet 2019 12:19:03 UTC-4, Don Baldwin a écrit :
>
> I have a function that runs some database queries and updates.  In the 
> test code for that function, I'd like to check out many times the database 
> is actually being hit.  Does Django provide a way to get that information?
>
> Thanks,
> Don
>

-- 
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/bf8c2c46-40b7-477a-8635-9da5c766bb7d%40googlegroups.com.


Re: What's the best way to update multiple entries in a database based on key/value pairs

2019-07-23 Thread Simon Charette
Hello Don,

If you're on Django 2.2+ you should use bulk_update for this purpose[0]

TestThing.objects.bulk_update((
TestThing(id=id, value=new_value)
for id, value in new_values.items()
), ['value'])

Under the hood it performs a SQL query of the form

UPDATE ... SET value = (CASE WHEN id=1 THEN foo WHEN id=2 THEN ...)

That you can emulate yourself by using Case and When expressions if you're
using Django < 2.2.

Cheers,
Simon

[0] https://docs.djangoproject.com/en/2.2/ref/models/querysets/#bulk-update

Le mardi 23 juillet 2019 12:15:20 UTC-4, Don Baldwin a écrit :
>
> Hi,
>
> I have a dictionary where the key is the primary key from one of my 
> database tables, and the values are the values that I want to update with.
>
> For example, I may have the following dictionary:
>
> new_values = {1:'a', 2:'b', 3:'c'}
>
>
> And the following model:
>
> class TestThing(models.Model):
>
> new_value = models.IntegerField(default=0) 
>
>
> And I want to update the entry with primary key 1 with value 'a', etc.
>
>
> Note that there are other fields in the table that need to be preserved, so I 
> can't just create a new table.
>
>
> Obviously, I could loop through each entry and update each entry 
> individually, but this seems really inefficient, so I think there must be a 
> better way to do this.
>
>
> Also, my table may have entries that aren't represented in my dictionary, so 
> I don't think I can do the following:
>
>
> TestThing.objects.all().update(new_value=new_values[F(id)])
>
>
> Thanks,
>
> Don
>
>

-- 
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/8fe0d69c-0158-4eaa-be5d-435a09a29535%40googlegroups.com.


Re: NotImplemented error combining distinct with annotate

2019-07-21 Thread Simon Charette
Assuming you have a model definition `Salesperson` you could use

Salesperson.object.annotate(
sales_amount=Sum('sales__sales_amount'),
)

But given you mentioned 'salesperson' is a text field you can do

persons = Sales.objects.values('salesperson').annotate(
sum_sales_amount=Sum('sales_amount')
)
for person in persons:
print('Salesperson %s sold %d dollars' % (person['salesperson'], 
person['sum_sales_amount'])

Note that .values() before annotating a an aggregation function results in 
a GROUP BY
which should should prefer over using DISTINCT.

Cheers,
Simon

Le dimanche 21 juillet 2019 21:20:37 UTC-4, John Gateley a écrit :
>
> Hello,
>
> Python version: Python 3.7.2
> Django version: 2.2.3
>
> I want to combine distinct and annotate(Sum(...)), and get the following 
> error:
> NotImplementedError: annotate() + distinct(fields) is not implemented.
>
> To describe: I have a bunch of sales entries like:
> 'John', 100
> 'Sam', 50
> 'John', 200
> (the model is a text field for salesperson and an integer field for 
> sales_amount)
>
> I want to write a query like:
> res = Sales.objects.distinct('salesperson').annotate(Sum('sales_amount'))
> for person in res:
> print('Salesperson %s sold %d dollars' % (person.salesperson, 
> person.sales_amount__count))
>
> I would expect:
> Salesperson John sold 300 dollars
> Salesperson Sam sold 50 dollars
>
> Instead it generates the above error. Is there a way to do this?
>
> Thank you,
>
> John
>

-- 
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/1f28638f-d43e-41d9-ba43-663d9d05df09%40googlegroups.com.


Re: Job board app based in django

2019-06-21 Thread Simon A
Oh really? Yeah I guess it wont be too bad if I create one.

On Fri, Jun 21, 2019 at 6:56 PM Omar Abou Mrad 
wrote:

> There are problem N clones of job boards built with django, this shouldn't
> affect your decision to create one.
>
> On Fri, Jun 21, 2019 at 10:59 AM Simon A  wrote:
>
>> hey guys,
>>
>> I would like to develop a job board app based in django. I was wondering
>> if there is already an available job board app based in django like
>> jobberbase. There is a jobberbase clone made from django but its version
>> too old already.
>>
>> thank you,
>> Simon
>>
>> --
>> 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 post to this group, send email to django-users@googlegroups.com.
>> Visit this group at https://groups.google.com/group/django-users.
>> To view this discussion on the web visit
>> https://groups.google.com/d/msgid/django-users/d607f1a0-9774-4442-82b8-a0431e078c76%40googlegroups.com
>> <https://groups.google.com/d/msgid/django-users/d607f1a0-9774-4442-82b8-a0431e078c76%40googlegroups.com?utm_medium=email_source=footer>
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
> --
> You received this message because you are subscribed to a topic in the
> Google Groups "Django users" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/django-users/q8HFtDGwq-A/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to
> django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/CAFwtXp3puf1iUHge8BTHYVJSB2RUzJefBY36%2Bc4dBL0rDOqB3A%40mail.gmail.com
> <https://groups.google.com/d/msgid/django-users/CAFwtXp3puf1iUHge8BTHYVJSB2RUzJefBY36%2Bc4dBL0rDOqB3A%40mail.gmail.com?utm_medium=email_source=footer>
> .
> For more options, visit https://groups.google.com/d/optout.
>


-- 
Kind Regards,
Simon Arriola

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CABXH83rpCgOrSoSScQvqZvTMS%3DeeOFWRvKDGVWjwYuWDf3cbvA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to store a bank account number generated into a model field

2019-06-21 Thread Simon A
I think the except block won't trigger since if the code 
Profile.objects.get(user=request.user) does not get any results, it will 
return a null result, not throw exception.

instead of exception handling, just check if the return value is null or not

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/a5b3fa33-767b-49fe-b0be-41b94947ac89%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: [Urgent] 500 when requesting a file from browser.

2019-06-21 Thread Simon A
On the last part of your stacktrace, there is a section

File "/usr/lib/python3.6/wsgiref/simple_server.py", line 35, in close
self.status.split(' ',1)[0], self.bytes_sent



could you please check this line out? 

you can try to print what is *self.status *to check what it is trying to 
split

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/32301b79-8595-4f02-8464-ac855499c13b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Job board app based in django

2019-06-21 Thread Simon A
hey guys,

I would like to develop a job board app based in django. I was wondering if 
there is already an available job board app based in django like 
jobberbase. There is a jobberbase clone made from django but its version 
too old already.

thank you,
Simon

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/d607f1a0-9774-4442-82b8-a0431e078c76%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Vicious cycle: Cannot migrate a DB that uses a widget using a model

2019-06-19 Thread Simon Charette
Hello Victor,

You should avoid performing database queries at module loading level as the 
code will
necessary crash if the database is missing or unmigrated.

I suggest you lazily define widgets instead by using a cached property[0]

class PlaceWidget(widgets.MultiWidget):
def __init__(self, attrs=None):
# Bypass MultiWidget.__init__ to allow lazy definition of widgets.
super(widgets.MultiWidget, self).__init__(attrs)

@cached_property
def widgets(self):
return (
... # the _widgets you defined in your __init__.
)

This should make sure the Country.objects.order_by('name') query is only 
executed
when .widgets is accessed for the first time on a PlaceWidget instance 
instead of at
initialization time.

Cheers,
Simon

[0] 
https://docs.djangoproject.com/en/2.2/topics/performance/#cached-property

Le mercredi 19 juin 2019 09:40:23 UTC-4, Victor Porton a écrit :
>
> When I try to migrate my project from empty DB state, it falls into a 
> vicious cycle: Trying to migrate it requests Country.objects.all() because 
> it has form fields using PlaceWidget but this requires it to be already 
> migrated.
>
> How to solve this problem?
>
> class PlaceWidget(widgets.MultiWidget):
> template_name = 'core/widgets/placewidget.html'
>
> class Media:
> js = ('js/placewidget.js',)
>
> def __init__(self, attrs=None):
> _widgets = (
> widgets.Select(choices=[('', '-')] + [(c.pk, c.name) for c in 
> Country.objects.all().order_by('name')],
>attrs={'onchange': "update_places_list(1)", 
> **(attrs or {})}),
> widgets.Select(choices=[('', '-')],
>attrs={'onchange': "update_places_list(2)", 
> **(attrs or {})}),
> widgets.Select(choices=[('', '-')],
>attrs={'onchange': "update_places_list(3)", 
> **(attrs or {})}),
> widgets.Select(choices=[('', '-')],
>attrs={'onchange': "update_places_list(4)", 
> **(attrs or {})}),
> widgets.Select(choices=[('', '-')])
> )
> super().__init__(_widgets, attrs)
>
> def decompress(self, value):
> if value:
> return [value['country'].pk if value['country'] else None,
> value['region'].pk if value['region'] else None,
> value['subregion'].pk if value['subregion'] else None,
> value['city'].pk if value['city'] else None,
> value['district'].pk if value['district'] else None]
> return [None, None, None, None, None]
>
>
>

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/adea5661-b99d-400d-a0f5-cffbaf667abc%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: IndexError: Number of args exceeds number of fields

2019-06-19 Thread Simon Charette
It's hard to tell without the full traceback but Django 1.11 doesn't 
support Python 3.7 so it'd
start by either using Django 2.2 or downgrading to Python 3.6

Cheers,
Simon

Le mercredi 19 juin 2019 08:16:51 UTC-4, Ezequias Rocha a écrit :
>
> Hi everyone
>
> I am doing a modeling of my database on DJANGO and after almost 10 tables 
> I did another model configuration and after making my 
> *admin.site.register(baseclass, 
> basecalassAdmin)* I got the following error message:
>
>
> *IndexError: Number of args exceeds number of fields*
>
> Could anyone tell me what could be wrong with that?
>
> I am using Python 3.7.2 and Django 1.11
>
> 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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/596f1e9a-0b87-4a89-ab1a-46a995109c51%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Package that helps update only changed fields

2019-06-18 Thread Simon Charette
Hello Dan,

I'm not aware of any third party library handling this but a simple way to 
achieve
what you're after would be to subclass ModelForm in order to override save()
and pass commit=False in your super() call.

e.g. (untested)

class UpdateFieldsModelForm(ModelForm):
update_fields = None

def save(self, commit=True):
instance = super().save(commit=False)
if commit:
update_fields = None if instance._state.adding else 
self.update_fields
instance.save(update_fields=self.update_fields)
return instance

Cheers,
Simon

Le mardi 18 juin 2019 11:38:53 UTC-4, Dan Davis a écrit :
>
> So, I recently observed that a Django ModelForm updates all columns when 
> it is updating a model instance. This is appropriate for a typical 
> situation where Django is also in control of the schema.
> I also see that you can control this behavior by passing update_fields 
> <https://docs.djangoproject.com/en/2.2/ref/models/instances/#saving-objects> 
> to the save method, in a particular form:
>
> self.instance.save(update_fields=self.changed_data)
>
> I have some complicated forms that have non-model fields and many-to-many 
> fields mixed in there.   I'm wondering whether there is a module for Django 
> out there that gives me some base ModelForms that do not update all fields, 
> but only changed fields.  I am asking because I don't want to work hard to 
> handle corner cases if there's something already out there.   What I 
> already have is hard-coded to the form where I've made this change to do 
> only a limited update.
>
> Thanks,
>
> -Dan
>

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/8dd0ebb7-3686-4477-b7ee-0b482312d65c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django tests appear to be getting substantially slower

2019-06-16 Thread Simon Charette
Again, it's hard to tell what the slowdown might be caused by without a 
more detailed
investigation. I suggest you use cProfile[0] for that.

Given your tests are only running for a small amount of time relative to 
Django's setup
time I assume two things are causing the apparent slowdown:

1. A slower Django setup(), I think some changes were part of 1.8 -> 1.11
2. Reliance on now lazily loaded part of Django.

Cheers,
Simon

[0] https://docs.python.org/3/library/profile.html

Le samedi 15 juin 2019 11:25:10 UTC-4, Mark Jones a écrit :
>
> Ah, but the slowdown is happening from 1.8 forward, each version of Django 
> make things just a bit slower.  It's a gradual slowdown.
>
> I do think I've got 3.2x libsqlite though.  So we can account for the 
> slowdown on 2.1 -> 2.2
>
> /usr/lib/libsqlite3.0.dylib
> /usr/lib/libsqlite3.dylib
> /usr/local/Cellar/sqlite/3.27.1/lib/libsqlite3.0.dylib
> /usr/local/Cellar/sqlite/3.27.1/lib/libsqlite3.a
> /usr/local/Cellar/sqlite/3.27.1/lib/libsqlite3.dylib
> /usr/local/Cellar/sqlite/3.28.0/lib/libsqlite3.0.dylib
> /usr/local/Cellar/sqlite/3.28.0/lib/libsqlite3.a
> /usr/local/Cellar/sqlite/3.28.0/lib/libsqlite3.dylib
>
>
> On Sat, Jun 15, 2019 at 8:16 AM Simon Charette  > wrote:
>
>> I meant Django 2.0 -> 2.1. As long as you are using Django 2.2 with 
>> SQLite 3.20+
>> the slowdown I mentioned should be effective.
>>
>> Simon
>>
>> Le samedi 15 juin 2019 08:32:56 UTC-4, Mark Jones a écrit :
>>>
>>> Maybe that's the case, I didn't build the python2.7 or 3.7, but I used 
>>> pyenv to install 3.4, 3.5, and 3.6 and they are all using the same version 
>>> of SQLite.  And with each version of python, the tests slow down as the 
>>> version of django increases.  Could this still be the SQLite v2.1->v2.2?
>>>
>>> Django isn't getting slower as the version of python increases, it's 
>>> getting slower as the version of Django increases.
>>>
>>> On Sat, Jun 15, 2019 at 7:20 AM Simon Charette  
>>> wrote:
>>>
>>>> Hi Mark,
>>>>
>>>> It's hard to tell exactly what's going on without more details but 
>>>> assuming you are running tests
>>>> against SQLite the 2.1 to 2.2 slowdown is likely caused by the fact 
>>>> database constraints are
>>>> now checked of each TestCase[0].
>>>>
>>>> Cheers,
>>>> Simon
>>>>
>>>> [0] https://docs.djangoproject.com/en/2.2/releases/2.2/#tests
>>>>
>>>>
>>>> Le samedi 15 juin 2019 07:26:35 UTC-4, Mark Jones a écrit :
>>>>>
>>>>> I was fixing up a Django app 
>>>>> https://github.com/mark0978/django-softdelete and setting up tox to 
>>>>> make sure it worked with all the listed versions because of issues opened 
>>>>> on the original repo.  While I was running tox locally I noticed that 
>>>>> with 
>>>>> every version of Django, the tests ran slower, and from 1.8 -> 2.2 the 
>>>>> test 
>>>>> time was nearly doubled.  This was true for every version of python 
>>>>> tested 
>>>>> from 2.7 - 3.7.
>>>>>
>>>>> If you want to check this on your machine, just grab the repo and run 
>>>>> tox.  I'm including the minimal tox output to show this phenomenon.
>>>>>
>>>>> py27-A installed: DEPRECATION: Python 2.7 will reach the end of its 
>>>>> life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't 
>>>>> be maintained after that date. A future version of pip will drop support 
>>>>> for Python 2.7.,Django==1.8.19,-e 
>>>>> git+...@github.com:mark0978/django-softdelete.git@72b46b0a7823a4fdcb43489663e90713ca7d698d#egg=django_softdelete
>>>>> --
>>>>> Ran 14 tests in 2.821s
>>>>>
>>>>> py27-B installed: DEPRECATION: Python 2.7 will reach the end of its 
>>>>> life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't 
>>>>> be maintained after that date. A future version of pip will drop support 
>>>>> for Python 2.7.,Django==1.9.13,-e 
>>>>> git+...@github.com:mark0978/django-softdelete.git@72b46b0a7823a4fdcb43489663e90713ca7d698d#egg=django_softdelete
>>>>> --
>>>>> Ran 14 tests in 3.036s
>>>>>
>>>>> py27-C installed: DEPRECAT

Re: Django tests appear to be getting substantially slower

2019-06-15 Thread Simon Charette
I meant Django 2.0 -> 2.1. As long as you are using Django 2.2 with SQLite 
3.20+
the slowdown I mentioned should be effective.

Simon

Le samedi 15 juin 2019 08:32:56 UTC-4, Mark Jones a écrit :
>
> Maybe that's the case, I didn't build the python2.7 or 3.7, but I used 
> pyenv to install 3.4, 3.5, and 3.6 and they are all using the same version 
> of SQLite.  And with each version of python, the tests slow down as the 
> version of django increases.  Could this still be the SQLite v2.1->v2.2?
>
> Django isn't getting slower as the version of python increases, it's 
> getting slower as the version of Django increases.
>
> On Sat, Jun 15, 2019 at 7:20 AM Simon Charette  > wrote:
>
>> Hi Mark,
>>
>> It's hard to tell exactly what's going on without more details but 
>> assuming you are running tests
>> against SQLite the 2.1 to 2.2 slowdown is likely caused by the fact 
>> database constraints are
>> now checked of each TestCase[0].
>>
>> Cheers,
>> Simon
>>
>> [0] https://docs.djangoproject.com/en/2.2/releases/2.2/#tests
>>
>>
>> Le samedi 15 juin 2019 07:26:35 UTC-4, Mark Jones a écrit :
>>>
>>> I was fixing up a Django app 
>>> https://github.com/mark0978/django-softdelete and setting up tox to 
>>> make sure it worked with all the listed versions because of issues opened 
>>> on the original repo.  While I was running tox locally I noticed that with 
>>> every version of Django, the tests ran slower, and from 1.8 -> 2.2 the test 
>>> time was nearly doubled.  This was true for every version of python tested 
>>> from 2.7 - 3.7.
>>>
>>> If you want to check this on your machine, just grab the repo and run 
>>> tox.  I'm including the minimal tox output to show this phenomenon.
>>>
>>> py27-A installed: DEPRECATION: Python 2.7 will reach the end of its life 
>>> on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be 
>>> maintained after that date. A future version of pip will drop support for 
>>> Python 2.7.,Django==1.8.19,-e 
>>> git+...@github.com:mark0978/django-softdelete.git@72b46b0a7823a4fdcb43489663e90713ca7d698d#egg=django_softdelete
>>> --
>>> Ran 14 tests in 2.821s
>>>
>>> py27-B installed: DEPRECATION: Python 2.7 will reach the end of its life 
>>> on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be 
>>> maintained after that date. A future version of pip will drop support for 
>>> Python 2.7.,Django==1.9.13,-e 
>>> git+...@github.com:mark0978/django-softdelete.git@72b46b0a7823a4fdcb43489663e90713ca7d698d#egg=django_softdelete
>>> --
>>> Ran 14 tests in 3.036s
>>>
>>> py27-C installed: DEPRECATION: Python 2.7 will reach the end of its life 
>>> on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be 
>>> maintained after that date. A future version of pip will drop support for 
>>> Python 2.7.,Django==1.10.8,-e 
>>> git+...@github.com:mark0978/django-softdelete.git@72b46b0a7823a4fdcb43489663e90713ca7d698d#egg=django_softdelete
>>> --
>>> Ran 14 tests in 3.198s
>>>
>>> py27-D installed: DEPRECATION: Python 2.7 will reach the end of its life 
>>> on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be 
>>> maintained after that date. A future version of pip will drop support for 
>>> Python 2.7.,Django==1.11.21,-e 
>>> git+...@github.com:mark0978/django-softdelete.git@72b46b0a7823a4fdcb43489663e90713ca7d698d#egg=django_softdelete,pytz==2019.1
>>> --
>>> Ran 14 tests in 3.609s
>>>
>>> py34-A installed: DEPRECATION: Python 3.4 support has been deprecated. 
>>> pip 19.1 will be the last one supporting it. Please upgrade your Python as 
>>> Python 3.4 won't be maintained after March 2019 (cf PEP 
>>> 429).,Django==1.8.19,-e 
>>> git+...@github.com:mark0978/django-softdelete.git@72b46b0a7823a4fdcb43489663e90713ca7d698d#egg=django_softdelete
>>> --
>>> Ran 14 tests in 2.733s
>>>
>>> py34-B installed: DEPRECATION: Python 3.4 support has been deprecated. 
>>> pip 19.1 will be the last one supporting it. Please upgrade your Python as 
>>> Python 3.4 won't be maintained after Marc

Re: Django tests appear to be getting substantially slower

2019-06-15 Thread Simon Charette
Hi Mark,

It's hard to tell exactly what's going on without more details but assuming 
you are running tests
against SQLite the 2.1 to 2.2 slowdown is likely caused by the fact 
database constraints are
now checked of each TestCase[0].

Cheers,
Simon

[0] https://docs.djangoproject.com/en/2.2/releases/2.2/#tests


Le samedi 15 juin 2019 07:26:35 UTC-4, Mark Jones a écrit :
>
> I was fixing up a Django app https://github.com/mark0978/django-softdelete 
> and 
> setting up tox to make sure it worked with all the listed versions because 
> of issues opened on the original repo.  While I was running tox locally I 
> noticed that with every version of Django, the tests ran slower, and from 
> 1.8 -> 2.2 the test time was nearly doubled.  This was true for every 
> version of python tested from 2.7 - 3.7.
>
> If you want to check this on your machine, just grab the repo and run 
> tox.  I'm including the minimal tox output to show this phenomenon.
>
> py27-A installed: DEPRECATION: Python 2.7 will reach the end of its life 
> on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be 
> maintained after that date. A future version of pip will drop support for 
> Python 2.7.,Django==1.8.19,-e 
> git+...@github.com:mark0978/django-softdelete.git@72b46b0a7823a4fdcb43489663e90713ca7d698d#egg=django_softdelete
> --
> Ran 14 tests in 2.821s
>
> py27-B installed: DEPRECATION: Python 2.7 will reach the end of its life 
> on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be 
> maintained after that date. A future version of pip will drop support for 
> Python 2.7.,Django==1.9.13,-e 
> git+...@github.com:mark0978/django-softdelete.git@72b46b0a7823a4fdcb43489663e90713ca7d698d#egg=django_softdelete
> --
> Ran 14 tests in 3.036s
>
> py27-C installed: DEPRECATION: Python 2.7 will reach the end of its life 
> on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be 
> maintained after that date. A future version of pip will drop support for 
> Python 2.7.,Django==1.10.8,-e 
> git+...@github.com:mark0978/django-softdelete.git@72b46b0a7823a4fdcb43489663e90713ca7d698d#egg=django_softdelete
> --
> Ran 14 tests in 3.198s
>
> py27-D installed: DEPRECATION: Python 2.7 will reach the end of its life 
> on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be 
> maintained after that date. A future version of pip will drop support for 
> Python 2.7.,Django==1.11.21,-e 
> git+...@github.com:mark0978/django-softdelete.git@72b46b0a7823a4fdcb43489663e90713ca7d698d#egg=django_softdelete,pytz==2019.1
> --
> Ran 14 tests in 3.609s
>
> py34-A installed: DEPRECATION: Python 3.4 support has been deprecated. pip 
> 19.1 will be the last one supporting it. Please upgrade your Python as 
> Python 3.4 won't be maintained after March 2019 (cf PEP 
> 429).,Django==1.8.19,-e 
> git+...@github.com:mark0978/django-softdelete.git@72b46b0a7823a4fdcb43489663e90713ca7d698d#egg=django_softdelete
> --
> Ran 14 tests in 2.733s
>
> py34-B installed: DEPRECATION: Python 3.4 support has been deprecated. pip 
> 19.1 will be the last one supporting it. Please upgrade your Python as 
> Python 3.4 won't be maintained after March 2019 (cf PEP 
> 429).,Django==1.9.13,-e 
> git+...@github.com:mark0978/django-softdelete.git@72b46b0a7823a4fdcb43489663e90713ca7d698d#egg=django_softdelete
> --
> Ran 14 tests in 3.066s
>
> py34-C installed: DEPRECATION: Python 3.4 support has been deprecated. pip 
> 19.1 will be the last one supporting it. Please upgrade your Python as 
> Python 3.4 won't be maintained after March 2019 (cf PEP 
> 429).,Django==1.10.8,-e 
> git+...@github.com:mark0978/django-softdelete.git@72b46b0a7823a4fdcb43489663e90713ca7d698d#egg=django_softdelete
> --
> Ran 14 tests in 3.232s
>
> py34-D installed: DEPRECATION: Python 3.4 support has been deprecated. pip 
> 19.1 will be the last one supporting it. Please upgrade your Python as 
> Python 3.4 won't be maintained after March 2019 (cf PEP 
> 429).,Django==1.11.21,-e 
> git+...@github.com:mark0978/django-softdelete.git@72b46b0a7823a4fdcb43489663e90713ca7d698d#egg=django_softdelete,pytz==2019.1
> --
> Ran 14 tests in 3.564s
>
> py34-E installed: DEPRECATION: Python 3.4 support has

SAVING DATA IN FORMTOOL WIZARD MODELFORM

2019-05-28 Thread Simon John
Hi 
Any one can  help on how to save data using formtool wizard and Modelform

The view of my models and form and views and the error are here

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/ef672c46-4c47-4d45-9838-39dfc5cefbaf%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Formtools Wizard and Modelform saving data

2019-05-28 Thread Simon John
I am trying to save data to db after all the three from have submited and 
still getting and error, any work around

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/9370992b-6f04-4bd3-ad70-3813347f2df4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Filtering Data Based On Foreign Key

2019-05-23 Thread Simon A
Have you tried putting the load_price() code inside the init code? like

def __init__(self, *args, **kwargs):
super(PlayerRegistrationForm, self).__init__(*args, **kwargs)
self.fields['club_id'].widget = forms.HiddenInput()

membership = request.GET.get('membership_title')
title = ClubMemberships.objects.filter(title=membership)
self.fields['price'].queryset = 
ClubMemberships.objects.filter(price=title.price)

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/e032daa3-4ccc-427c-bb6d-fd306b1ac88b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: some random problem

2019-05-23 Thread Simon A
share the code here. I know django devs are lazy but don't be this lazy.

On Wednesday, May 22, 2019 at 8:07:08 PM UTC+8, Soumen Khatua wrote:
>
> Hi Folks,
>
> I'm getting len(cart) is 0 and after iterate *item is not coming from 
> cart* in this project,plese tell me where is my problem.
> I'm sharing my git repo please go through it and please tell me the what i 
> missed.It's urgent.
>
> Here is the link:
> https://github.com/Herosoumen/clothproject 
>
>
> Thank you
>

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/3f62cdd5-6a3c-4577-88cc-f27d6016ae26%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Dealing with global or session objects

2019-05-23 Thread Simon A
Hello fellow Java user,

If I would do it, I'd setup a model to store those configurations.

Then on the app, upon login or upon loading the initial page of the app, I 
will perform the operation to retrieve the details from the database, and 
then dump to the django sessions object.

# get operation
request.session.get('key', None)


# set operation
self.request.session['key'] = value

Please also see https://docs.djangoproject.com/en/2.2/topics/http/sessions/ for 
more information.

Regards,
Simon.

On Wednesday, May 22, 2019 at 9:26:15 PM UTC+8, Jean-Noël Colin wrote:
>
> Hi, 
>
> I'm coming from a java world, where there exists different scopes for 
> objects: application-, session-, request scopes all define different 
> lifecycle for objects. I have some difficulties in finding an equivalent 
> approach in Django. 
>
> Here's the need: my project stores its custom configuration in the 
> database, for persistence; these parameters can be changed by an 
> administrator only, through a custom view/form. However, those parameters 
> are used in many views in the project, in read-only mode. So my idea would 
> be to have one single object, that stores the parameter values, that is 
> initialized when the application starts, that can be read at any time 
> without requiring reading from the DB, and that, when modified by admin, 
> would be saved to the db. How to plug this in the django architecture? 
>
> Thanks a lot
>
> Jean-Noël
>

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/da5dd8d8-e1a3-44cc-8f44-158f4183a99e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django 2.2 creates multiple migration files when AbstractUser is used

2019-05-02 Thread Simon Charette
Hey David,

Could you try explicitly defining an objects manager on your User model and 
see it if helps.

e.g.

from django.contrib.auth.models import UserManager

class User(AbstractUser):
... # fields
objects = UserManager()

I'm also having trouble reproducing locally though.

Simon

Le jeudi 2 mai 2019 05:17:33 UTC-4, Daviddd a écrit :
>
> Dear All,
>
> Empty DB, no migration is applied, I have a core app like:
>
> #core.models
>
> class Institute(models.Model):
> phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message=
> institute_phone_help_text)
>
> name = models.CharField(_('name'), max_length=255)
> description = models.TextField(_('description'), blank=True)
> abbreviation = models.CharField(_('abbreviation'), blank=True, 
> max_length=100)
> address = models.TextField(_('address'), blank=True)
> phone = models.CharField(validators=[phone_regex], max_length=17, 
> blank=True)  # validators should be a list
> websites = ArrayField(models.URLField(max_length=255), verbose_name=_(
> 'websites'), blank=True, null=True)
>
> class Meta:
> verbose_name = _('institute')
> verbose_name_plural = _('institutes')
>
> def __str__(self):
> return '{0} ({1})'.format(self.name, self.abbreviation)
>
>
> class User(AbstractUser):
> id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=
> False)
> institute = models.ForeignKey(Institute, on_delete=models.CASCADE)
> params = JSONField(_('params'), null=True, blank=True,)
> about_me = models.TextField(_('about me'), blank=True,)
>
> The app core is in the INSTALLED_APPS. 
>
> If I run
> ./manage.py migrate
>
> it correctly says that is not finding the core app, hence I run
> ./manage.py makemigrations core
>
> It creates the migration file 001_initial*.
>
> Now I run ./manage.py migrate and it works great,
>
> But if I continue to run ./manage.py makemigrations it continues to add N 
> core app migration file like:
>
> # Generated by Django 2.2.1 on 2019-05-02 08:55
>
> import django.contrib.auth.models
> from django.db import migrations
>
>
> class Migration(migrations.Migration):
> dependencies = [
> ('core', '0001_initial'),
> ]
>
> operations = [
> migrations.AlterModelManagers(
> name='user',
> managers=[
> ('objects', django.contrib.auth.models.UserManager()),
> ],
> ),
> ]
>
>
>
> I tried various combinations but none worked:
>
> ./manage.py makemigrations core
> ./manage.py migrate core
> ./manage.py migrate 
>
> ./manage.py makemigrations core
> ./manage.py makemigrations core
>
> ./manage.py makemigrations
> ./manage.py migrate
>
>
>
>
> Linked to this question:
>
> https://stackoverflow.com/questions/55923797/django-2-2-abstractuser-and-migration-issue
>
> Is it a bug?
> How can I solve this?
>
> Thanks.
>
> D
>

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/4507eecf-b700-4e58-b5ae-e54b3ad6a3c0%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Pagination breaks in ListView after migrating from Django 1.11 to 2.2 with SQLite

2019-04-23 Thread Simon Charette
I assume you are either using a Subquery annotation that returns
multiple results or an __in lookup against a query with multiple columns.

I vaguely remember something changed in this area but it was documented
in one of the 2.0, 2.1 or 2.2 release notes.

Best,
Simon

Le mardi 23 avril 2019 10:31:43 UTC-4, hodossy...@gmail.com a écrit :
>
> Hello,
>
> I am facing the following issue after upgrading to 2.2 from 1.11. Here is 
> the stack trace:
>
> Traceback (most recent call last):
>   File "(...)\.env\lib\site-packages\django\db\backends\utils.py", line 
> 84, in _execute
> return self.cursor.execute(sql, params)
>   File "(...)\.env\lib\site-packages\django\db\backends\sqlite3\base.py", 
> line 383, in execute
> return Database.Cursor.execute(self, query, params)
> sqlite3.OperationalError: only a single result allowed for a SELECT that 
> is part of an expression
>
> The above exception was the direct cause of the following exception:
>
> Traceback (most recent call last):
>   File "(...)\dashboard\deployment\tests\test_view.py", line 53, in 
> test_display_list_view
> response = self.client.get(self.url_my_list)
>   File "(...)\.env\lib\site-packages\django\test\client.py", line 535, in 
> get
> response = super().get(path, data=data, secure=secure, **extra)
>   File "(...)\.env\lib\site-packages\django\test\client.py", line 347, in 
> get
> **extra,
>   File "(...)\.env\lib\site-packages\django\test\client.py", line 422, in 
> generic
> return self.request(**r)
>   File "(...)\.env\lib\site-packages\django\test\client.py", line 503, in 
> request
> raise exc_value
>   File "(...)\.env\lib\site-packages\django\core\handlers\exception.py", 
> line 34, in inner
> response = get_response(request)
>   File "(...)\.env\lib\site-packages\django\core\handlers\base.py", line 
> 115, in _get_response
> response = self.process_exception_by_middleware(e, request)
>   File "(...)\.env\lib\site-packages\django\core\handlers\base.py", line 
> 113, in _get_response
> response = wrapped_callback(request, *callback_args, **callback_kwargs)
>   File "(...)\.env\lib\site-packages\django\views\generic\base.py", line 
> 71, in view
> return self.dispatch(request, *args, **kwargs)
>   File "(...)\.env\lib\site-packages\django\contrib\auth\mixins.py", line 
> 52, in dispatch
> return super().dispatch(request, *args, **kwargs)
>   File "(...)\.env\lib\site-packages\django\views\generic\base.py", line 
> 97, in dispatch
> return handler(request, *args, **kwargs)
>   File "(...)\.env\lib\site-packages\django\views\generic\list.py", line 
> 157, in get
> context = self.get_context_data()
>   File "(...)\dashboard\deployment\views.py", line 53, in get_context_data
> context = super().get_context_data(**kwargs)
>   File "(...)\.env\lib\site-packages\django\views\generic\list.py", line 
> 119, in get_context_data
> paginator, page, queryset, is_paginated = 
> self.paginate_queryset(queryset, page_size)
>   File "(...)\.env\lib\site-packages\django\views\generic\list.py", line 
> 69, in paginate_queryset
> page = paginator.page(page_number)
>   File "(...)\.env\lib\site-packages\django\core\paginator.py", line 70, 
> in page
> number = self.validate_number(number)
>   File "(...)\.env\lib\site-packages\django\core\paginator.py", line 48, 
> in validate_number
> if number > self.num_pages:
>   File "(...)\.env\lib\site-packages\django\utils\functional.py", line 80, 
> in __get__
> res = instance.__dict__[self.name] = self.func(instance)
>   File "(...)\.env\lib\site-packages\django\core\paginator.py", line 97, 
> in num_pages
> if self.count == 0 and not self.allow_empty_first_page:
>   File "(...)\.env\lib\site-packages\django\utils\functional.py", line 80, 
> in __get__
> res = instance.__dict__[self.name] = self.func(instance)
>   *File "(...)\.env\lib\site-packages\django\core\paginator.py", line 91, 
> in count*
> *return c()*
>   File "(...)\.env\lib\site-packages\django\db\models\query.py", line 392, 
> in count
> return self.query.get_count(using=self.db)
>   File "(...)\.env\lib\site-packages\django\db\models\sql\query.py", line 
> 504, in get_count
> number = obj.get_aggregation(using, ['__count'])['__count']
>   File "(...)\.env\lib\site-packages\django\db\models\sql\query.py", line 
> 489, in get_aggregation
> result = compiler.execute_sql(SINGLE)
>   File "(...)\.env\lib\si

Merging multiple Django project into one

2019-04-18 Thread Simon Liu
Hello, 

I am try to migrate users from an old project into a a new project i am 
working on. I have extracted all the models from my old project into a 
reusable app. I was able to connect to multiple database, but i wasn't able 
to make my project be able to read the users and group from my old project. 
I was hoping to be able to write migrations where i read old user data and 
create it in my new project. Since both project use the auth apps for 
authentication i am not sure i am able to tell the db routers where to read 
the users and groups from which db. What would be a good approach to solve 
this problem of reading user/group data from one django project and migrate 
the data to a new project?

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/2286a0a7-21c5-400b-b2b6-cc671ec4f250%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django 2.2 and custom media in the admin

2019-04-09 Thread Simon Charette
Hello Thorsten, this is a change document in the 2.2 release notes[0].

There's even a resolution example for a django.jQuery dependency like you 
have

> For example, widgets depending on django.jQuery must specify
> js=['admin/js/jquery.init.js', ...] when declaring form media assets. [1]

Cheers,
Simon

[0] 
https://docs.djangoproject.com/en/2.2/releases/2.2/#merging-of-form-media-assets
[1] 
https://docs.djangoproject.com/en/2.2/topics/forms/media/#assets-as-a-static-definition

Le mardi 9 avril 2019 11:02:35 UTC-4, Thorsten Sanders a écrit :
>
> Hello,
>
> I insert a custom javascript inside the admin and do use the 
> "django.jquery" this worked fine until updating to Django 2.2.
>
> With 2.2 the order in which the javascripts are loaded changed and the 
> jquery.init.js is now loaded after my custom javascript, is that considered 
> a bug or a change?
>
> Regards,
> Thorsten
>

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/018ab123-2b22-4425-bb6d-efeb1c4f12cf%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: UniqueConstraint raises uncaught IntegrityError in Admin

2019-04-09 Thread Simon Charette
No form validation is implemented for UniqueConstraint(condition) yet as 
that would require
a non-trivial refactor of how it's performed. It was discussed during the 
feature development[0].

I'd suggest you override you form or your model's clean() method to perform 
the validation
yourself until built-in support is added.

Submitting a new Trac ticket so we don't loose track of the issue would 
also be appreciated.

Cheers,
Simon

[0] https://github.com/django/django/pull/10796#discussion_r244216763

Le mardi 9 avril 2019 07:29:53 UTC-4, Ryan Jarvis a écrit :
>
> Hey there,
>
> I'm trying out the new UniqueConstraint functionality in Django 2.2 and 
> seem to be misunderstanding something.  When adding a Constraint to the 
> model I am getting an uncaught IntegrityError in the admin.  
> I've got the following sample code:
>
> *models.py*
>
> class Seminar(models.Model):
> seminar_id = models.CharField(max_length=255, unique=True)
> members = models.ManyToManyField(User, through='SeminarRole', 
> related_name="studies")
>
> class SeminarRole(models.Model):
> LEAD = 1  # Only 1 Lead permitted per seminar
> SUPPORT = 2
> ROLE_CHOICES = (
> (LEAD, 'Lead'),
> (SUPPORT, 'Support'),
> )
>
> user = models.ForeignKey(User, related_name='seminar_roles', 
> on_delete=models.CASCADE)
> seminar = models.ForeignKey('seminar', related_name='roles', 
> on_delete=models.CASCADE)
>
> role = models.IntegerField(choices=ROLE_CHOICES)
>
> class Meta:
> constraints = [
> models.UniqueConstraint(fields=['seminar'], 
> condition=Q(role=1), name="only_one_lead"),
> ]
>
>
>
> For the code above in the Django Admin I can successfully add a 
> SeminarRole with User1 as the Lead for SeminarA, User2 as the Lead for 
> SeminarB, and User1 as Support for SeminarB but if I try and add User2 as 
> another Lead to SeminarA it gives me an Exception.  Should I be seeing the 
> Django Admin catch this before hand?
>
> IntegrityError at /admin/study_management/seminarrole/add/
> duplicate key value violates unique constraint "only_one_lead"
> DETAIL:  Key (seminar_id)=(1) already exists.
>
>
> I'm on Django 2.2, Python 3.7 and Postgres 11.2
>
>

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/12fba4e5-7f07-4491-afb6-b969e73252da%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to deploy migrations to production

2019-04-02 Thread Simon A
Thank you. I'd surely be able to use this when we deploy. But is it really 
necessary to run collectstatic everytime there is a deployment to perform? 
I just use this to make the admin page have the correct styling when 
accessed in production.

On Wednesday, April 3, 2019 at 12:55:31 PM UTC+8, Uri Even-Chen wrote:
>
> I think *makemigrations* should never be used in production. You run it 
> locally and then commit the migrations.
>
> If it's a new production server you are deploying, I think you can delete 
> all your migrations and then run *makemigrations* (locally) to create 
> only initial migrations. But only if you are sure you're not going to need 
> to go back to a previous migration version. But if it's not a new 
> production server, just run *migrate* there after you commit your 
> migrations locally and pull them from the server.
>
> Take a look at  
> https://github.com/speedy-net/speedy-net/blob/master/contrib/deploy.sh  
> אורי
> u...@speedy.net 
>
>
> On Tue, Apr 2, 2019 at 3:51 PM Simon A > 
> wrote:
>
>> There is a workflow section in the migration page from the django project 
>> documentation. But there are somethings I am confused about,
>>
>> It says that the migrations need to be created in the non production 
>> environment and then checked in to the repository along with the changes in 
>> models.py.
>>
>> My question is how would that migration be applied in the production 
>> environment.
>>
>> Once the new migrations and changes in the model are deployed in the 
>> server, should I execute *python manage.py migrate* in the server?
>>
>> Or is it also acceptable to just deploy the changes in production 
>> environment, then execute *makemigrations* and *migrate* in production?
>>
>> FYI, our deployment process is still a bit manual. There is a different 
>> person handling the production servers so I'd still have to document the 
>> deployment steps and endorse to the sysadmins that will perform the change 
>> in the server.
>>
>> -- 
>> 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 post to this group, send email to django...@googlegroups.com 
>> .
>> Visit this group at https://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/35d6d27e-6210-4c8c-b31c-2adb424b9773%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/django-users/35d6d27e-6210-4c8c-b31c-2adb424b9773%40googlegroups.com?utm_medium=email_source=footer>
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/0c5358fd-bfde-4989-abfa-b4bc83ef2ad8%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How to deploy migrations to production

2019-04-02 Thread Simon A
Ah I see. Thank you Jani for clearing that up.

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/7daa2d23-0951-4097-84d0-404e88300c4a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


How to deploy migrations to production

2019-04-02 Thread Simon A
There is a workflow section in the migration page from the django project 
documentation. But there are somethings I am confused about,

It says that the migrations need to be created in the non production 
environment and then checked in to the repository along with the changes in 
models.py.

My question is how would that migration be applied in the production 
environment.

Once the new migrations and changes in the model are deployed in the 
server, should I execute *python manage.py migrate* in the server?

Or is it also acceptable to just deploy the changes in production 
environment, then execute *makemigrations* and *migrate* in production?

FYI, our deployment process is still a bit manual. There is a different 
person handling the production servers so I'd still have to document the 
deployment steps and endorse to the sysadmins that will perform the change 
in the server.

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/35d6d27e-6210-4c8c-b31c-2adb424b9773%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Unit-Testing Django Views

2019-03-28 Thread Simon Charette
This is effectively failing because of a mechanism added in 1.10 to protect
against BREACH attacks[0] by salting the CSRF token.

I'm not aware of any way to disable this mechanism but testing against the
exact HTML returned from a view seems fragile.

I suggest you use assertContains[1] (with or without html=True) and
assertTemplateUsed[2] instead.

Cheers,
Simon

[0] https://docs.djangoproject.com/en/2.1/ref/csrf/#how-it-works
[1] 
https://docs.djangoproject.com/en/2.1/topics/testing/tools/#django.test.SimpleTestCase.assertContains
[2] 
https://docs.djangoproject.com/en/2.1/topics/testing/tools/#django.test.SimpleTestCase.assertTemplateUsed

Le jeudi 28 mars 2019 12:16:43 UTC-4, OnlineJudge95 a écrit :
>
> Hi people,
>
> I am following the book Test-Driven Development with Python 
> <https://www.amazon.in/Test-Driven-Development-Python-Selenium-JavaScript/dp/1491958707>
>  by 
> *Harry J.W. Perceval.* The book is using Django version 1.7 which is 
> outdated as of now so I started with version 2.1.
>
> I am trying to unit test my index view. One unit-test that I have written 
> is testing whether the index view returns correct HTML or not by comparing 
> the input received through
> django.template.loader.render_to_string
> the unit-test fail with the following traceback
> python manage.py test
> Creating test database for alias 'default'...
> .System check identified no issues (0 silenced).
> F.
> ==
> FAIL: test_index_view_returns_correct_html (lists.tests.IndexViewTest)
> --
> Traceback (most recent call last):
>   File "tests.py", line 24, in test_index_view_returns_correct_html
> self.assertEqual(expected_html, actual_html)
> AssertionError: ' chars]lue="BJMT1b9fxuXOGugp00SDypeTYZxvlmc6KtBSYMDon[198 chars]l>\n' != 
> ' chars]l>\n'
>
> --
> Ran 3 tests in 0.006s
>
> FAILED (failures=1)
> Destroying test database for alias 'default'...
>
> Process finished with exit code 1
>
>
> It was clear that the csrf token is causing the test to fail. Is there any 
> way to test it, or should it be tested? I ask this as when I changed my 
> Django version to 1.7, the tests were passing, even after giving the csrf 
> token field in the form. I tried going through the changelogs but 1.7 is 
> far behind (beginner here). Please find the code snippets, directory 
> structure provided below.
>
>
> *lists/views.py*
>
>
>
>
>
>
>
>
>
>
> *from django.http import HttpResponsefrom django.shortcuts import render# 
> Create your views here.def index(request):if request.method == 'POST':
> return HttpResponse(request.POST['item_text'])return render(request, 
> 'index.html')*
>
>
> *lists/test.py*
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> *from django.http import HttpRequestfrom django.template.loader import 
> render_to_stringfrom django.test import TestCasefrom django.urls import 
> resolvefrom lists.views import index# Create your tests here.class 
> IndexViewTest(TestCase):def 
> test_root_url_resolves_to_home_page_view(self):   [...]def 
> test_index_view_returns_correct_html(self):request = HttpRequest()  
>   response = index(request)actual_html = 
> response.content.decode()expected_html = 
> render_to_string('index.html', request=request)
> self.assertEqual(expected_html, actual_html)def 
> test_index_view_can_save_a_post_request(self):   [...]requirements.txt*
>
>
>
>
>
> *Django==2.1.7pytz==2018.9selenium==3.141.0urllib3==1.24.*
> *settings.py*
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> *[...]# Application definitionINSTALLED_APPS = [ 'django.contrib.admin', 
> 'django.contrib.auth', 'django.contrib.contenttypes', 
> 'django.contrib.sessions', 'django.contrib.messages', 
> 'django.contrib.staticfiles', 'lists',][...]*
> *Directory Structure*
>
> [image: Screen Shot 2019-03-28 at 9.36.56 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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/7f0f12be-fc3e-43c3-ba07-e48158def051%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Create models using raw SQL queries

2019-03-27 Thread Simon A
hi Cameron, as Eric said, by doing this you might not fully take advantage 
of the features of django. But if you still want to proceed maybe you can 
use the managed option for 
models. https://docs.djangoproject.com/en/2.1/ref/models/options/#managed.

with this approach, you'll create the database tables manually first 
OUTSIDE of django, then connect django to it afterwards. I haven't tried it 
before but this might be what you need.

also if your teacher requires to perform raw sql queries rather than use 
the ORM, there is an option to use raw sql 
queries. 
https://docs.djangoproject.com/en/2.1/topics/db/sql/#executing-custom-sql-directly

On Thursday, March 28, 2019 at 6:16:54 AM UTC+8, Eric Pascual wrote:
>
> Hi,
>
> Not sure Django is the right choice in your case since one of its main 
> purposes is to hide the SQL stuff by putting the ORM in front. 
>
> You'd better use Flask, Tornado or any other Web framework which does not 
> come with any special feature WRT data access.
>
> Best
>
> Eric
>
> --
> *From:* django...@googlegroups.com  <
> django...@googlegroups.com > on behalf of cameron hochbrg <
> caos...@gmail.com >
> *Sent:* Tuesday, March 26, 2019 21:36
> *To:* Django users
> *Subject:* Create models using raw SQL queries 
>  
> hello,
>
> for a project for a database class, we wanted to create a web app using 
> django. However, our teacher wants us to use raw SQL queries for everything 
> involving the database. As such I was wondering if it was possible to 
> create mdoels using raw SQL queries.
>
> thank you in advance
>
> -- 
> 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 post to this group, send email to djang...@googlegroups.com 
> .
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/django-users/8145efe7-c169-43d6-86e6-e0d64415a764%40googlegroups.com
>  
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/3a449e4d-12fe-48bb-bdf3-45a6d6a5203e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Creating Objects from Annotations and Other Models

2019-03-21 Thread Simon Charette
I'm not sure where r_id comes from but Model.save usually deals with any 
expression correctly
so you could try using a subquery assignment and see if it works.

e.g.

entry = Entry.objects.create(
start=Subquery(
Recurrence.objects.filter(pk=r_id).values('start_time')[:1]
)
)

Note that accessing entry.start right after creation might still return the 
Subquery instance
instead of the created value. This is caused by some backends not 
supporting the
RETURNING clause. There's an open ticket about making such attributes 
available
immediately on backend supporting RETURNING but it was still missing 
consensus about
what to do on other backends. If I remember correctly the two alternatives 
were to defer the
field or perform an immediate SELECT.

Cheers,
Simon

Le jeudi 21 mars 2019 13:06:04 UTC-4, Dylan Young a écrit :
>
> For example using made-up syntax:
>
> Entry.objects.create(start=F(Recurrence.objects.filter(pk=r_id), 
> 'start_time'))
>
> Note that we can't use `get` since the whole point is to avoid all the 
> useless round-trips to the DB.
>
> Best,
>
> Casey
>
> On Thu, 21 Mar 2019 at 13:18, Dylan Young  > wrote:
>
>> It's not a recalculation. It's instantiation.
>>
>> Instance data diverges from the factory data and needs to be 
>> independently editable. 
>>
>> Best, 
>>
>> Casey
>>
>> Le jeu. 21 mars 2019 2:52 a.m., Derek > 
>> a écrit :
>>
>>> Permanently storing data that can be recalculated from existing data is 
>>> a practice specific to the needs of particular applications.  
>>>
>>> Have you perhaps considered making use of the "view" table functionality 
>>> available in most databases?
>>>
>>> For example, in PostgreSQL you can create a materialized view which 
>>> "caches the result of a complex expensive query and then allow you to 
>>> refresh this result periodically." - see 
>>> http://www.postgresqltutorial.com/postgresql-materialized-views/
>>>
>>>
>>> On Tuesday, 19 March 2019 17:34:11 UTC+2, Dylan Young wrote:
>>>>
>>>> Hey all:
>>>>
>>>> I often find myself fetching data from models in the database only to 
>>>> run a few trivial calculations and store the info in a different model.
>>>>
>>>> Is there an established ORM pattern for directly creating objects in 
>>>> the DB based on the fields of other models?
>>>>
>>>> Sorry if this is obvious, but I couldn't find much on this in my web 
>>>> searching. 
>>>>
>>>>
>>>> Best,
>>>>
>>>> Casey 
>>>>
>>> -- 
>>> 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 post to this group, send email to django...@googlegroups.com 
>>> .
>>> Visit this group at https://groups.google.com/group/django-users.
>>> To view this discussion on the web visit 
>>> https://groups.google.com/d/msgid/django-users/a1c55adc-c5fa-465c-8740-3a741bc22686%40googlegroups.com
>>>  
>>> <https://groups.google.com/d/msgid/django-users/a1c55adc-c5fa-465c-8740-3a741bc22686%40googlegroups.com?utm_medium=email_source=footer>
>>> .
>>> For more options, visit https://groups.google.com/d/optout.
>>>
>>

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/7b954a7d-e893-4459-8d75-e7cc1a411e1f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django 2.1.4: Permissions are not updated after migrations

2019-03-18 Thread Simon Charette
> Would the following strategy work? delete all app permission and use, 
create_permissions to recreate them

Yes, but that will delete all the user and group permissions as well; 
you'll have to reassign them.

> How do I know to which db table a given permission points? Or does it 
point to a model?

They point to models through the Permission.content_type foreign key; 
ContentType have an (app_label, model_name)
unique tuple.

Best,
Simon



Le lundi 18 mars 2019 04:35:55 UTC-4, Yevgeny Bar Lev a écrit :
>
> Thanks Simon!
> Two questions:
> a) Would the following strategy work? delete all app permission and use, 
> create_permissions to recreate them
> b) How do I know to which db table a given permission points? Or does it 
> point to a model?
>
> On Mon, Mar 18, 2019 at 6:38 AM Simon Charette  > wrote:
>
>> Hello Yevgeny,
>>
>> I'd start by deleting your stale content types[0] which your permissions 
>> are attached
>> to. That should deal with deleted model case.
>>
>> For the renames I suggest you drop into a shell and manually edit the 
>> Permission.name
>> of the misnamed instances.
>>
>> Best,
>> Simon
>>
>> [0] 
>> https://docs.djangoproject.com/en/2.1/ref/django-admin/#django-contrib-contenttypes
>>
>> Le dimanche 17 mars 2019 15:52:45 UTC-4, Yevgeny Bar Lev a écrit :
>>>
>>> Thanks Simon. Is there some nonmagical solution? I mean, is it possible 
>>> to fix some of the permissions manually without breaking stuff?
>>>
>>> On Sun, Mar 17, 2019, 9:21 PM Simon Charette  wrote:
>>>
>>>> Hello Yevgeny,
>>>>
>>>> I don't have magic solution to suggest to you given the current state 
>>>> of your
>>>> permission data after a few iterations but I just wanted to let you 
>>>> know that
>>>> it's a known issue[0] and a contributor is actively working on getting 
>>>> it fixed[1].
>>>>
>>>> Cheers,
>>>> Simon
>>>>
>>>> [0] https://code.djangoproject.com/ticket/29843
>>>> [1] https://github.com/django/django/pull/10540
>>>>
>>>> Le dimanche 17 mars 2019 13:31:16 UTC-4, Yevgeny Bar Lev a écrit :
>>>>>
>>>>> Hello,
>>>>> I have noticed that the available permissions list, which can be set 
>>>>> to users/groups in the admin doesn't match my models. This happened after 
>>>>> a 
>>>>> few standard migrations, where some models were renamed, some deleted, 
>>>>> and 
>>>>> new models were added. The list is basically not updated, and represents 
>>>>> a 
>>>>> mixed state of the db, before and after the above migrations.
>>>>>
>>>>> manage.py inspectdb show the CORRECT state of the database. 
>>>>>
>>>>> I have tried to follow the following solution, which basically didn't 
>>>>> do much.
>>>>>
>>>>> from django.contrib.auth.management import create_permissionsfrom 
>>>>> django.apps import apps
>>>>>
>>>>> create_permissions(apps.get_app_config('my_app_name'))
>>>>>
>>>>> I will appreciate your help.
>>>>> Best,
>>>>> Yevgeny.
>>>>>
>>>> -- 
>>>> 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 post to this group, send email to django...@googlegroups.com.
>>>> Visit this group at https://groups.google.com/group/django-users.
>>>> To view this discussion on the web visit 
>>>> https://groups.google.com/d/msgid/django-users/9c49dff1-c6b1-43e6-818d-f56ab761558d%40googlegroups.com
>>>>  
>>>> <https://groups.google.com/d/msgid/django-users/9c49dff1-c6b1-43e6-818d-f56ab761558d%40googlegroups.com?utm_medium=email_source=footer>
>>>> .
>>>> For more options, visit https://groups.google.com/d/optout.
>>>>
>>> -- 
>> 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 post to this group, send email to django...@googlegroups.com 
>> .
>> Visit this group at https://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/7f88aa1a-4d3f-4611-9611-c733b81909a6%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/django-users/7f88aa1a-4d3f-4611-9611-c733b81909a6%40googlegroups.com?utm_medium=email_source=footer>
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/1042f212-68ed-4f3c-b82d-58a50989bb0f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django 2.1.4: Permissions are not updated after migrations

2019-03-17 Thread Simon Charette
Hello Yevgeny,

I'd start by deleting your stale content types[0] which your permissions 
are attached
to. That should deal with deleted model case.

For the renames I suggest you drop into a shell and manually edit the 
Permission.name
of the misnamed instances.

Best,
Simon

[0] 
https://docs.djangoproject.com/en/2.1/ref/django-admin/#django-contrib-contenttypes

Le dimanche 17 mars 2019 15:52:45 UTC-4, Yevgeny Bar Lev a écrit :
>
> Thanks Simon. Is there some nonmagical solution? I mean, is it possible to 
> fix some of the permissions manually without breaking stuff?
>
> On Sun, Mar 17, 2019, 9:21 PM Simon Charette  > wrote:
>
>> Hello Yevgeny,
>>
>> I don't have magic solution to suggest to you given the current state of 
>> your
>> permission data after a few iterations but I just wanted to let you know 
>> that
>> it's a known issue[0] and a contributor is actively working on getting it 
>> fixed[1].
>>
>> Cheers,
>> Simon
>>
>> [0] https://code.djangoproject.com/ticket/29843
>> [1] https://github.com/django/django/pull/10540
>>
>> Le dimanche 17 mars 2019 13:31:16 UTC-4, Yevgeny Bar Lev a écrit :
>>>
>>> Hello,
>>> I have noticed that the available permissions list, which can be set to 
>>> users/groups in the admin doesn't match my models. This happened after a 
>>> few standard migrations, where some models were renamed, some deleted, and 
>>> new models were added. The list is basically not updated, and represents a 
>>> mixed state of the db, before and after the above migrations.
>>>
>>> manage.py inspectdb show the CORRECT state of the database. 
>>>
>>> I have tried to follow the following solution, which basically didn't do 
>>> much.
>>>
>>> from django.contrib.auth.management import create_permissionsfrom 
>>> django.apps import apps
>>>
>>> create_permissions(apps.get_app_config('my_app_name'))
>>>
>>> I will appreciate your help.
>>> Best,
>>> Yevgeny.
>>>
>> -- 
>> 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 post to this group, send email to django...@googlegroups.com 
>> .
>> Visit this group at https://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/9c49dff1-c6b1-43e6-818d-f56ab761558d%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/django-users/9c49dff1-c6b1-43e6-818d-f56ab761558d%40googlegroups.com?utm_medium=email_source=footer>
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/7f88aa1a-4d3f-4611-9611-c733b81909a6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django 2.1.4: Permissions are not updated after migrations

2019-03-17 Thread Simon Charette
Hello Yevgeny,

I don't have magic solution to suggest to you given the current state of 
your
permission data after a few iterations but I just wanted to let you know 
that
it's a known issue[0] and a contributor is actively working on getting it 
fixed[1].

Cheers,
Simon

[0] https://code.djangoproject.com/ticket/29843
[1] https://github.com/django/django/pull/10540

Le dimanche 17 mars 2019 13:31:16 UTC-4, Yevgeny Bar Lev a écrit :
>
> Hello,
> I have noticed that the available permissions list, which can be set to 
> users/groups in the admin doesn't match my models. This happened after a 
> few standard migrations, where some models were renamed, some deleted, and 
> new models were added. The list is basically not updated, and represents a 
> mixed state of the db, before and after the above migrations.
>
> manage.py inspectdb show the CORRECT state of the database. 
>
> I have tried to follow the following solution, which basically didn't do 
> much.
>
> from django.contrib.auth.management import create_permissionsfrom django.apps 
> import apps
>
> create_permissions(apps.get_app_config('my_app_name'))
>
> I will appreciate your help.
> Best,
> Yevgeny.
>

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/9c49dff1-c6b1-43e6-818d-f56ab761558d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Why are foreign keys rewritten when adding related_name?

2019-03-01 Thread Simon Charette
Hello HM,

I know that some changes have been made to avoid unnecessary foreign key
rebuilds on some option changes.

Are you experiencing this on 2.1 and 2.2 pre release?

Simon

Le vendredi 1 mars 2019 02:40:01 UTC-5, HM a écrit :
>
> I added "related_name" to an exiting ForeignKey and checked with 
> "django-admin sqlmigrate" what would be done. 
>
> It seems that the foreign key constraint is dropped, then the exact 
> same constraint is added back. Why? 
>
> Example: If we have the classes: 
>
> class Wall(models.Model): 
> .. 
>
> class Door(models.Model): 
> ..wall = models.ForeignKey(Wall) 
>
> and change Door.wall to models.ForeignKey(Wall, related_name='walls'), 
> then: 
>
> Prior to this, there exist (postgres) the constraint: 
>
> "app_door_wall_id_45647_fk_app_wall" FOREIGN KEY (wall_id) REFERENCES 
> app_wall(id) DEFERRABLE INITIALLY DEFERRED. 
>
> "django_admin sqlmigrate" reports: 
>
> SET CONSTRAINTS "app_door_wall_id_45647_fk_app_wall" IMMEDIATE; ALTER 
> TABLE  "app_door" DROP CONSTRAINT 
> "app_door_wall_id_45647_fk_app_wall"; 
> ALTER TABLE "app_door" ADD CONSTRAINT 
> "app_door_wall_id_45647_fk_app_wall" FOREIGN KEY ("wall_id") 
> REFERENCES "app_wall" ("id") DEFERRABLE INITIALLY DEFERRED; 
>
> After running the migration, which is run as there's stuff in the log, 
> there exists seemingly the same constraint as before: 
>
> "app_door_wall_id_45647_fk_app_wall" FOREIGN KEY (wall_id) REFERENCES 
> app_wall(id) DEFERRABLE INITIALLY DEFERRED. 
>
> Why waste a connection this way? 
>
> -- 
> HM 
>

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/a1d9f7a9-be2a-41d5-8a43-4b468ad4a547%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Help with aggregates needed

2019-02-27 Thread Simon Charette
Hello Felix,

month = ...
year = ...
Expenses.objects.filter(
year=year,
).values(
area_name=F('area__name'),
element_name=F('element__name')
).annotate(
year_sum=Sum('cost'),
month_sum=Sum('cost', filter=Q(month=month)),
)

Should generate SQL along the following lines on PostgreSQL

SELECT
area.name AS area_name,
element.name AS element_name,
SUM(expenses.cost) AS year_sum,
SUM(expenses.cost) FILTER (WHERE month = $month) month_sum
FROM
expenses
INNER JOIN area ON (
expenses.area_id = area.id
)
INNER JOIN element ON (
expenses.element_id = element.id
)
WHERE expenses.year = $year
GROUP BY area.name, element.name
ORDER BY area.name, element.name

Cheers,
Simon

Le mercredi 27 février 2019 14:04:21 UTC-5, Felix Lazaro Carbonell a écrit :
>
> Hi to everyone:
>
>  
>
> Having models like these:
>
>  
>
> class Area(models.Model):
>
> name = models.CharField(max_lentgh=30)
>
>  
>
>  
>
> class Element(models.Model):
>
> name = models.CharField(max_lentgh=30)
>
>  
>
>  
>
> class Expenses(models.Model):
>
> area = models.ForeignKey(Area, on_delete=models.CASCADE )
>
> element = models.ForeignKey(Element, on_delete=models.CASCADE )
>
> year = models.SmallIntegerField()
>
> month = models.SmallIntegerField()
>
> cost = model.DecimalField(max_digits=10, decimal_places=2, default=0)
>
>  
>
>  
>
> I would like to group by area, then by element, and then get sum by month 
> and accumulated expenses for that element in the year. how could that be 
> done using Django ORM?
>
>  
>
> Something to show like this
>
>  
>
> Expenses in current
>
> AreaElement   Month   Year
>
> Operations  Cell phone325.65 712.40
>
> Operations   Office consumibles451.00 1028.56
>
> Main office   Cell phone 148.89 284.41
>
> Main office  Office consumibles650.00 1300.00
>
>  
>
> Thanks in advance,
>
> Felix.
>

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/36e57d46-3577-4afd-84cc-63ea31ee3a96%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Working with pk arguments within an included URL

2019-02-18 Thread Simon A
Hi Gavin,

Please see this one.
https://docs.djangoproject.com/en/2.1/topics/http/sessions/. It first needs
to be setup in your settings.py.

Basically, this is just a field in the database that gets retrieved
whenever you want.

# set a session variable
self.request.session['key'] = 'value'

# get a session variable
self.request.session.get('key', None)

On Mon, Feb 18, 2019 at 3:10 PM Gavin Boyle 
wrote:

> Hi Simon,
>
> That’s a great idea, I’ve only ever worked with built in sessions for
> logging in. Would you have a link to some documentation or an example that
> would help me as I’m relatively new to Django and this has been holding me
> back months now.
>
> Thanks
>
> Gavin
>
> On Mon, 18 Feb 2019 at 04:11, Simon A  wrote:
>
>> I think I had a similar scenario a few weeks ago. One option that you
>> have is to store the originally selected PK to the session object. Whenever
>> you load a page, for you can retrieve the PK from the session object. Most
>> likely you'll do this on the get_queryset function
>>
>>
>> On Sunday, February 17, 2019 at 8:24:53 PM UTC+8, GavinB841 wrote:
>>>
>>> Hi,
>>>
>>> To briefly explained:
>>>
>>>- I have a main site which provides links to multiple sports club
>>>pages.
>>>- Currently once clicked it opens the club home page and displays
>>>information based on that club by passing in the pk.
>>>- I then have many other pages associated to the clubs. e.g. Teams,
>>>Player Registration, Shop etc.
>>>- But when I click on the navbar for example "Player Registration" I
>>>have no idea how to continue the URL with the originally selected PK and
>>>how to use that PK in the view.
>>>
>>>
>>> ***Current I have these pages working off the authenticated user but
>>> realistically I want it working off the originally selected club***
>>>
>>> I am not sure how to write the view to allow for this to work and then
>>> pass the pk argument into the nav bar url simiarlary how I did it on the
>>> main site:
>>>
>>> 
>>>
>>>
>>> Would really appreciate any help been stuck on this for a few months
>>> now.
>>>
>>> Below is an example of the Clubs Teams I need this to work for:
>>>
>>> *Urls.py:*
>>>
>>> urlpatterns = [
>>> path('', views.club_home, name='club_home'),
>>> path('/', include([
>>> path('home/', views.club_home, name='club_home_with_pk'),
>>> path('teams/', views.TeamInfo.as_view(), name='teams'),
>>> ])),
>>>
>>>
>>> *Nav bar for club pages:*
>>>
>>> Home
>>> Team
>>> Pitches
>>> Memberships
>>>
>>>
>>>
>>> *Views.py*
>>>
>>>
>>> def club_home(request, pk=None):
>>> if pk:
>>> club = ClubInfo.objects.filter(pk=pk)
>>> club_posts = ClubPosts.objects.filter(club_id=club[0])
>>> elif request.user.is_authenticated:
>>> club = ClubInfo.objects.filter(user=request.user)
>>> club_posts = ClubPosts.objects.filter(club_id=club[0])
>>> # photo = model.club_logo.ImageField(storage=profile_pics)
>>> args = {'club': club,
>>> 'club_posts': club_posts
>>> }
>>> return render(request, 'club_home_page.html', args)
>>>
>>>
>>> class TeamInfo(APIView):
>>> renderer_classes = [TemplateHTMLRenderer]
>>> template_name = 'teams.html'
>>>
>>> def get(self, request):
>>> form = TeamForm()
>>> user = ClubInfo.objects.filter(user=request.user).first()
>>> teams = Team.objects.filter(club_id=user.pk)
>>> return Response({'form': form,
>>>  'teams': teams,
>>>  })
>>>
>>> def post(self, request):
>>> form = TeamForm(data=request.data)
>>> user = ClubInfo.objects.filter(user=request.user).first()
>>> teams = Team.objects.filter(club_id=user.pk)
>>> if form.is_valid():
>>> form.save()
>>> return Response({'form': form,
>>>  'teams': teams
>>>  })
>>>
>>>
>>>
>>> --
>> You received this message because you are subscribed to a topic in the
>

Re: REG: Why my django email settings not sending email notifications?

2019-02-17 Thread Simon A
Just to add, please try to create a python file with the simplest 
implementation of send mail just to check if it actually works. 

On Monday, February 18, 2019 at 11:43:22 AM UTC+8, Sid wrote:
>
> can you check if you your email server is somehow blocking your emails? 
> Have you enabled your debug settings ON?
>
> On Sun, Feb 17, 2019 at 2:49 PM 'Amitesh Sahay' via Django users <
> django...@googlegroups.com > wrote:
>
>> I have created a registration page that sends an email notification on 
>> successful registration. I do have my email notification in place. But it 
>> doesn't seem to be working, neither it is throwing any error. Below is the 
>> code snippet.
>> views.py
>>
>> def register(request):
>> validators = [MinimumLengthValidator, NumberValidator, 
>> UppercaseValidator]
>> if request.method == 'POST':
>> first_name = request.POST['first_name']
>> last_name = request.POST['last_name']
>> email = request.POST['email']
>> username = request.POST['username']
>> password = request.POST['password']
>> try:
>> for validator in validators:
>> validator().validate(password)
>> except ValueError as e:
>> messages.error(request, str(e))
>> return redirect('register')
>> password2 = request.POST['password2']
>>
>> # check if the password match
>> if password == password2:
>>
>> if User.objects.filter(username=username).exists():
>> messages.error(request, 'username already exist')
>> return redirect('register')
>> else:
>> if User.objects.filter(email=email).exists():
>> messages.error(request, 'Registration Failed - Try 
>> different email address')
>> return redirect('register')
>> else:
>> user = User.objects.create_user(username=username, 
>> password=password, email=email,
>> first_name=first_name, 
>> last_name=last_name)
>> user.save()
>> messages.success(request, 'Registration complete, please 
>> proceed to login')
>> return redirect('register')
>> else:
>> messages.error(request, 'password dose not match')
>> return redirect('register')
>> else:
>> return render(request, 'ACCOUNTS/register.html')
>>
>> def ThankYou(request, register):
>> if request.method == 'POST':
>> if register.is_valid():
>> save_it = register.save(commit=False)
>> save_it.save()
>> subject = 'Registration successful'
>> message = 'Thank you for registration, please continue with 
>> the login'
>> from_email = settings.EMAIL_HOST_USER
>> to_list = [save_it.email, settings.EMAIL_HOST_USER]
>> try:
>> send_mail(
>> subject,
>> message,
>> from_email,
>> [to_list],
>> fail_silently=False,
>> )
>> except ValueError:
>> return HttpResponse('Invalid header found.')
>> else:
>> messages.success(request, 'thank you ')
>> return redirect('register')
>> else:
>> return redirect('index')
>>
>> Below is my settings.py
>>
>> EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
>> EMAIL_USE_TLS = False
>> EMAIL_HOST = 'smtp.gmail.com'
>> EMAIL_PORT = 587
>> EMAIL_HOST_USER = 'ami@gmail.com '
>> EMAIL_HOST_PASSWORD = '123'
>> DEFAULT_FROM_EMAIL = 'ami@gmail.com '
>>
>> I have gone through a couple of Stackoverflow posts and made some changes 
>> as suggested. But they do not seem to have any effect. Below is one of the 
>> link.
>>
>> Django Doesn't Send Email Notifications 
>> 
>> Regards,
>> Amitesh Sahay
>> *91-750 797 8619*
>>
>> -- 
>> 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 post to this group, send email to django...@googlegroups.com 
>> .
>> Visit this group at https://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/1493971974.505339.1550394996512%40mail.yahoo.com
>>  
>> 
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>
>
> -- 
> Thank you
> Siddharth Tamang
> AWS Certified Solutions Architect - Associate
>

-- 

Re: Working with pk arguments within an included URL

2019-02-17 Thread Simon A
I think I had a similar scenario a few weeks ago. One option that you have 
is to store the originally selected PK to the session object. Whenever you 
load a page, for you can retrieve the PK from the session object. Most 
likely you'll do this on the get_queryset function

On Sunday, February 17, 2019 at 8:24:53 PM UTC+8, GavinB841 wrote:
>
> Hi,
>
> To briefly explained:
>
>- I have a main site which provides links to multiple sports club 
>pages.
>- Currently once clicked it opens the club home page and displays 
>information based on that club by passing in the pk.
>- I then have many other pages associated to the clubs. e.g. Teams, 
>Player Registration, Shop etc.
>- But when I click on the navbar for example "Player Registration" I 
>have no idea how to continue the URL with the originally selected PK and 
>how to use that PK in the view.
>
>
> ***Current I have these pages working off the authenticated user but 
> realistically I want it working off the originally selected club***
>
> I am not sure how to write the view to allow for this to work and then 
> pass the pk argument into the nav bar url simiarlary how I did it on the 
> main site:
>
> 
>
>
> Would really appreciate any help been stuck on this for a few months now. 
>
> Below is an example of the Clubs Teams I need this to work for:
>
> *Urls.py:*
>
> urlpatterns = [
> path('', views.club_home, name='club_home'),
> path('/', include([
> path('home/', views.club_home, name='club_home_with_pk'),
> path('teams/', views.TeamInfo.as_view(), name='teams'),
> ])),
>
>
> *Nav bar for club pages:*
>
> Home
> Team
> Pitches
> Memberships
>
>
>
> *Views.py*
>
>
> def club_home(request, pk=None):
> if pk:
> club = ClubInfo.objects.filter(pk=pk)
> club_posts = ClubPosts.objects.filter(club_id=club[0])
> elif request.user.is_authenticated:
> club = ClubInfo.objects.filter(user=request.user)
> club_posts = ClubPosts.objects.filter(club_id=club[0])
> # photo = model.club_logo.ImageField(storage=profile_pics)
> args = {'club': club,
> 'club_posts': club_posts
> }
> return render(request, 'club_home_page.html', args)
>
>
> class TeamInfo(APIView):
> renderer_classes = [TemplateHTMLRenderer]
> template_name = 'teams.html'
>
> def get(self, request):
> form = TeamForm()
> user = ClubInfo.objects.filter(user=request.user).first()
> teams = Team.objects.filter(club_id=user.pk)
> return Response({'form': form,
>  'teams': teams,
>  })
>
> def post(self, request):
> form = TeamForm(data=request.data)
> user = ClubInfo.objects.filter(user=request.user).first()
> teams = Team.objects.filter(club_id=user.pk)
> if form.is_valid():
> form.save()
> return Response({'form': form,
>  'teams': teams
>  })
>
>
>
>

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/c508e2ee-d73a-4a02-923d-d033e467efe3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: select_for_update Documentation is confusing(?)

2019-02-15 Thread Simon Charette
Hello Philoj,

> Does this mean that the above code example will raise 
TransactionManagementError...

It won't cause a TransactionManagementError because of the lazy nature of 
queryset.

Even if the QuerySet.select_for_update() call is made outside of the atomic 
block the query
is really only executed when entries are iterated over.

Given the documentation clearly mentions "*Evaluating* a queryset" and 
"Building a queryset"
I don't think it's worth amending it.

Cheers,
Simon

Le vendredi 15 février 2019 07:40:51 UTC-5, Philoj Johny a écrit :
>
> In the documentation for select_for_update 
> <https://docs.djangoproject.com/en/2.1/ref/models/querysets/#select-for-update>,
>  
> given code example is:
>
> from django.db import transaction
> entries = Entry.objects.select_for_update().filter(author=request.user)with 
> transaction.atomic():
> for entry in entries:
> ...
>
> At the same time, below in the description it says that:
>
> *Evaluating a queryset with select_for_update() in autocommit mode on
> backends which support SELECT ... FOR UPDATE is a
> TransactionManagementError 
> <https://docs.djangoproject.com/en/2.1/ref/exceptions/#django.db.transaction.TransactionManagementError>
>  error because the
> rows are not locked in that case.*
>
> *Does this mean that the above code example will raise 
> **TransactionManagementError , since the select_for_update_query is evaluated 
> outside atomic block?*
>
>
> *(I have'nt actually tried this out yet, will soon. I think may be a 
> correction is required in the code example)*
>
>

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/15abcd7c-c0a3-48c9-a50a-80c71512cc3d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: select_for_update Documentation is confusing(?)

2019-02-15 Thread Simon Charette
I meant, and *not* "Building a queryset" in my previous reply.

Le vendredi 15 février 2019 14:18:27 UTC-5, Simon Charette a écrit :
>
> Hello Philoj,
>
> > Does this mean that the above code example will raise 
> TransactionManagementError...
>
> It won't cause a TransactionManagementError because of the lazy nature of 
> queryset.
>
> Even if the QuerySet.select_for_update() call is made outside of the 
> atomic block the query
> is really only executed when entries are iterated over.
>
> Given the documentation clearly mentions "*Evaluating* a queryset" and 
> "Building a queryset"
> I don't think it's worth amending it.
>
> Cheers,
> Simon
>
> Le vendredi 15 février 2019 07:40:51 UTC-5, Philoj Johny a écrit :
>>
>> In the documentation for select_for_update 
>> <https://docs.djangoproject.com/en/2.1/ref/models/querysets/#select-for-update>,
>>  
>> given code example is:
>>
>> from django.db import transaction
>> entries = Entry.objects.select_for_update().filter(author=request.user)with 
>> transaction.atomic():
>> for entry in entries:
>> ...
>>
>> At the same time, below in the description it says that:
>>
>> *Evaluating a queryset with select_for_update() in autocommit mode on
>> backends which support SELECT ... FOR UPDATE is a
>> TransactionManagementError 
>> <https://docs.djangoproject.com/en/2.1/ref/exceptions/#django.db.transaction.TransactionManagementError>
>>  error because the
>> rows are not locked in that case.*
>>
>> *Does this mean that the above code example will raise 
>> **TransactionManagementError , since the select_for_update_query is 
>> evaluated outside atomic block?*
>>
>>
>> *(I have'nt actually tried this out yet, will soon. I think may be a 
>> correction is required in the code example)*
>>
>>

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/7805f266-aa5e-401f-8171-17e4a7484ee9%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Is there a package for user-tagging and user-properties?

2019-02-14 Thread Simon A
This might not be a package but django allows to extend the User object via 
a one to one relationship. Once extended, you can add as many fields as you 
like. It will be better though if this will happen at the start of the 
project. Using this method at the middle of the project might cause a lot 
of refactoring.

https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#extending-the-existing-user-model

On Thursday, February 14, 2019 at 7:54:43 AM UTC+8, Charles Thayer wrote:
>
> I'm aware of django-taggit (and similar) but I'm wondering if there's a 
> package for tagging Users with properties that have values of different 
> types, such as strings, ints, datetimes, etc.  For example, one might tag a 
> user with "power-user", add a property for "last-visited-on" as 
> datetime(2019, 02, 13), or add a property for "favorite-color" with the 
> value "purple". These would be open-ended property/tag names where 
> admin-users may be creating these ad-hoc.
>
> Thanks,
> /charles
>
>

-- 
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 post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/e1e72a68-3072-4087-b9a5-b6ed1ad6abb3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


  1   2   3   4   5   6   7   >