Replicating complex query with two dense_rank() functions using ORM

2020-11-03 Thread 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/3d8106a7-df44-4697-91fe-06c861132ae6n%40googlegroups.com.


Re: Newbie looking for some help with Postgres <> Django connection

2020-11-03 Thread David Nugent
On 4 Nov 2020, at 03:45, Marc Johnson 
mailto:marcjohnson...@gmail.com>> wrote:
...
1. Since this app is dockerized, I have my existing env vars in my 
docker-compose-prod.yml file. Is that where I should list DATABASE_URL? Like:

db:
image: postgres:11
volumes:
  - postgres_data:/var/lib/postgresql/data/
environment:
- DATABASE_URL=postgresql://:@:/


Looks good, but to be certain jump into your container (exec or run) and verify 
that the DATABASE_URL is set correctly. It should be.


2. Does the below formatting look correct to you from my settings.py? I am 
running into issues with the env var DATABASE_URL and getting this error:  
Environment variable "{}" not set'

DATABASES = {
'default': dj_database_url.config(env("DATABASE_URL"), 
default="postgres://postgres@db/postgres", conn_max_age=1800),
'ENGINE': 'django.db.backends.postgresql',
}

There was a mistake in my previous response, so looks like that led you astray.

First, omit "ENGINE" here - unnecessary as postgres (or postgresql) scheme in 
the URL will drive that.

Second, you don't need to specify "DATABASE_URL" directly, that is the default 
variable used if you don't override it, or you can specify 'DATABASE_URL' 
there, or use env='DATABASE_URL'. Your choice.

If you do extract the url prior calling .config(), then use the  default= 
keyword, even though DATABASE_URL will override it. If you pass a positional 
argument to .config it will be used as the environment variable, not the value. 
If you have an already extracted value, then alternatively you can use .parse() 
instead of .config() which takes the url as the first positional arg.

dj_database_url is a pretty simple single module package. Check out the source 
code, it isn't too hard to comprehend.

DATABASES = {
'default': dj_database_url.config(conn_max_age=1800)
}

should do the trick on heroku.

3. I am also getting this error when running locally. Do you have any advice 
for troubleshooting?

web_1  | [2020-11-03 16:35:59 +] [7] [ERROR] Error handling request /NDCs/
web_1  | Traceback (most recent call last):
web_1  |   File 
"/usr/local/lib/python3.8/site-packages/gunicorn/workers/sync.py", line 134, in 
handle
web_1  | self.handle_request(listener, req, client, addr)
web_1  |   File 
"/usr/local/lib/python3.8/site-packages/gunicorn/workers/sync.py", line 175, in 
handle_request
web_1  | respiter = self.wsgi(environ, resp.start_response)
web_1  |   File 
"/usr/local/lib/python3.8/site-packages/django/core/handlers/wsgi.py", line 
131, in __call__
web_1  | signals.request_started.send(sender=self.__class__, 
environ=environ)
web_1  |   File 
"/usr/local/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 
177, in send
web_1  | return [
web_1  |   File 
"/usr/local/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 
178, in 
web_1  | (receiver, receiver(signal=self, sender=sender, **named))
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/db/__init__.py", 
line 46, in reset_queries
web_1  | for conn in connections.all():
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/db/utils.py", 
line 229, in all
web_1  | return [self[alias] for alias in self]
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/db/utils.py", 
line 229, in 
web_1  | return [self[alias] for alias in self]
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/db/utils.py", 
line 211, in __getitem__
web_1  | self.ensure_defaults(alias)
web_1  |   File "/usr/local/lib/python3.8/site-packages/django/db/utils.py", 
line 176, in ensure_defaults
web_1  | conn.setdefault('ATOMIC_REQUESTS', False)
web_1  | AttributeError: 'str' object has no attribute 'setdefault'

I think this is the fallout from above, passing the url as the first positional 
instead of an environment variable name or just omitting it.




-- 
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/3BF1BFA9-00EB-40D2-9EED-5DF1B2313BD5%40uniquode.io.


Linking an Image detection Project to Django

2020-11-03 Thread ahmed.he...@gmail.com
Hi,

I am working on a colour detection project and I am trying to link it to my 
Django Project, but I don't know where to start.

In my Django project, I have a Post CreateView where users can upload 
images.

Here is the function that I am trying to link the colours in the image to 
Post.colors but I don't know how to make it generated directly once the 
image is uploaded

Here is the models.py:
```
class Post(models.Model):
title = models.TextField(max_length=100)
design = models.ImageField(
blank=False, null=True, upload_to='new designs')
date_posted = models.DateTimeField(default=timezone.now)
colors= models.TextField(max_length=10,blank=True, null=True)

def __str__(self):
return self.title

def imagecolors(self, *args, **kwargs):
img = Image.open(self.design)
size = w, h = img.size
data = img.load()

colors = []
for x in range(w):
for y in range(h):
color = data[x, y]
hex_color_lower = ''.join([hex(c)[2:].rjust(2, '0') for c 
in color])
hex_color = hex_color_lower.upper()
colors.append(hex_color)

total = w * h

color_hex = []
color_count = []
color_percent = []

df = pd.DataFrame()
for color, count in Counter(colors).items():
percent = count / total * \
  100  # Do not make it int. Majority of colors are < 
1%, unless you want >= 1%
if percent > 1:
color_hex.append(color)
color_count.append(count)
color_percent.append(percent)
Post.colors=color_hex
print(Post.colors)
```
with the above it showing none in the template:
```
{{ post.colors }}
```

-- 
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/fbdef2f2-f417-47fb-a967-bcaf3a862ffcn%40googlegroups.com.


Re: Deploying an app on heroku

2020-11-03 Thread programmer 262
thanks a lot man i already deployed it but thanks i appreciate it


Le sam. 31 oct. 2020 à 23:54, Ayser shuhaib  a
écrit :

> please set debug value to True then deploy, that will allow us to see what
> is causing the server error
>
> On Sun, Nov 1, 2020 at 12:46 AM programmer 262 
> wrote:
>
>> hy guys i want to deploy my app on heroku and i having a bad time this is
>> the website that i deployed
>> https://khadijaoumelmouminine.herokuapp.com/
>> if someone could help me on deploying it. i will be very GLADE and i will
>> be very thankful if someone can talk to me on facebook
>> https://www.facebook.com/achraf.chahin.3/
>> thanks t everyone
>>
>> --
>> 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/0352f07b-2d6f-4e0c-ab95-c4ce8dd32226n%40googlegroups.com
>> 
>> .
>>
> --
> 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/yhV3OaJrFzk/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/CAE0AZG%2BmBoqd2KEToXuGd65JtYM5x-PsKP3QHOcUEXvAgf4m7g%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/CAHfJf4sOraBnL632ce-VrmJOxsyPNx_5TRO73VSjZaX%2B%3DxVUYQ%40mail.gmail.com.


reusable App XOR custom user model?

2020-11-03 Thread guettli
Quoting the Docs 

:

*> If you’re starting a new project, it’s highly recommended to set up a 
custom user model, even if the default User 

 model 
is sufficient for you. This model behaves identically to the default user 
model, but you’ll be able to customize it in the future if the need arises:*

But this means: My code won't be reusable.

Some lines below:

*> Reusable apps shouldn’t implement a custom user model. A project may use 
many apps, and two reusable apps that implemented a custom user model 
couldn’t be used together. If you need to store per user information in 
your app, use a ForeignKey 

 or OneToOneField 

 to settings.AUTH_USER_MODEL as 
described below.*

I think both sentences somehow contradict, since AFAIK it is highly 
recommended to
write reusable apps.

What do you recommend

*reusable App   XORcustom user model?*

Regards,
  Thomas

-- 
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/d75e460a-1f3a-4338-b936-23a797ee335cn%40googlegroups.com.


Re: Newbie looking for some help with Postgres <> Django connection

2020-11-03 Thread Marc Johnson
Hi David,

Thanks for the feedback!

I'm checking out dj_database_url and have a few follow up questions I was
hoping you (or someone) could help me with.

1. Since this app is dockerized, I have my existing env vars in my
docker-compose-prod.yml file. Is that where I should list DATABASE_URL?
Like:






*db:image: postgres:11volumes:  -
postgres_data:/var/lib/postgresql/data/environment:-
DATABASE_URL=postgresql://:@:/
- *2. Does the below formatting look correct to you from my settings.py? I
am running into issues with the env var DATABASE_URL and getting this
error:  Environment variable "{}" not set'





*DATABASES = {'default': dj_database_url.config(env("DATABASE_URL"),
default="postgres://postgres@db/postgres", conn_max_age=1800),'ENGINE':
'django.db.backends.postgresql',}*
3. I am also getting this error when running locally. Do you have any
advice for troubleshooting?

web_1  | [2020-11-03 16:35:59 +] [7] [ERROR] Error handling request
/NDCs/

web_1  | Traceback (most recent call last):

web_1  |   File
"/usr/local/lib/python3.8/site-packages/gunicorn/workers/sync.py", line
134, in handle

web_1  | self.handle_request(listener, req, client, addr)

web_1  |   File
"/usr/local/lib/python3.8/site-packages/gunicorn/workers/sync.py", line
175, in handle_request

web_1  | respiter = self.wsgi(environ, resp.start_response)

web_1  |   File
"/usr/local/lib/python3.8/site-packages/django/core/handlers/wsgi.py", line
131, in __call__

web_1  | signals.request_started.send(sender=self.__class__,
environ=environ)

web_1  |   File
"/usr/local/lib/python3.8/site-packages/django/dispatch/dispatcher.py",
line 177, in send

web_1  | return [

web_1  |   File
"/usr/local/lib/python3.8/site-packages/django/dispatch/dispatcher.py",
line 178, in 

web_1  | (receiver, receiver(signal=self, sender=sender, **named))

web_1  |   File
"/usr/local/lib/python3.8/site-packages/django/db/__init__.py", line 46, in
reset_queries

web_1  | for conn in connections.all():

web_1  |   File
"/usr/local/lib/python3.8/site-packages/django/db/utils.py", line 229, in
all

web_1  | return [self[alias] for alias in self]

web_1  |   File
"/usr/local/lib/python3.8/site-packages/django/db/utils.py", line 229, in


web_1  | return [self[alias] for alias in self]

web_1  |   File
"/usr/local/lib/python3.8/site-packages/django/db/utils.py", line 211, in
__getitem__

web_1  | self.ensure_defaults(alias)

web_1  |   File
"/usr/local/lib/python3.8/site-packages/django/db/utils.py", line 176, in
ensure_defaults

web_1  | conn.setdefault('ATOMIC_REQUESTS', False)

web_1  | AttributeError: 'str' object has no attribute 'setdefault'

Many thanks in advance for any insights.

Best,
Marc

On Sat, Oct 31, 2020 at 11:45 PM David Nugent  wrote:

> It's been a while since I used heroku, but iirc it just uses a formatted
> pg url.
>
> Install the module dj-database-url and use this in settings instead of the
> default DATABASES layout, something like:
>
>
> DATABASES = {
> 'default':
> dj_database_url.config(os.environ['DATABASE_URL'], conn_max_age=1800)
> }
>
>
> Then set DATABASE_URL in the heroku (and your development) environment.
> This setting will be of the form:
>
> DATABASE_URL=postgresql://:@:/
>
>
> Again, its been a while but I also seem to recall that the DATABASE_URL is
> provided to your app automagically(?) a part of the provisioning so does
> not need to be explicitly set there.  Using the dj_database_url module in
> your settings above is the key.
>
>
>
>

-- 
M: +1-646-541-2108
W: marcjohnson.info 

-- 
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/CACH3BCQi2f7uybMPb%3DXXmLuczNwX3%2Bi-enyS-4Lmk_%2Ba7etYbw%40mail.gmail.com.


Re: Having issues with django and Heroku

2020-11-03 Thread Farai M
I used whitenoise 5.0.1 it works fine you can updated your version and see
what will happen

On Tue, Nov 3, 2020, 6:31 PM Odeyale Kehinde  wrote:

> Can any one assist me to fix this issue, I uploaded my django website on
> heroku but I'm get this errors
> ImportError at /Your WhiteNoise configuration is incompatible with
> WhiteNoise v4.0 This can be fixed by following the upgrade instructions at:
> http://whitenoise.evans.io/en/stable/changelog.html#v4-0
>
> this is the link of my website: http://alphatechsolutions.herokuapp.com/
>
>
> 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/5cb042a7-2d18-4f9d-8072-a9bd54dfc9b8n%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/CAMeub5NuxSPWFi5W2f2GQ6%3DFdzzip9oj6mGA6_Nh3d0o1gfRjg%40mail.gmail.com.


Having issues with django and Heroku

2020-11-03 Thread Odeyale Kehinde
Can any one assist me to fix this issue, I uploaded my django website on 
heroku but I'm get this errors
ImportError at /Your WhiteNoise configuration is incompatible with 
WhiteNoise v4.0 This can be fixed by following the upgrade instructions at: 
http://whitenoise.evans.io/en/stable/changelog.html#v4-0 

this is the link of my website: http://alphatechsolutions.herokuapp.com/


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/5cb042a7-2d18-4f9d-8072-a9bd54dfc9b8n%40googlegroups.com.


null=True and blank=True? null=False and blank=True?

2020-11-03 Thread rik...@gmail.com
https://djangodoctor.medium.com/the-real-difference-between-blank-true-and-null-true-may-surprise-you-982a9ac3b9da

-- 
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/84dc68d1-3bb1-4aa8-a795-84e43702a212n%40googlegroups.com.