Django bugfix releases: 2.0.4 and 1.11.12

2018-04-02 Thread Tim Graham
Details are available on the Django project weblog:

https://www.djangoproject.com/weblog/2018/apr/02/bugfix-releases/

-- 
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/CAD-rxRDT3gCaU7ikr%2B4Yc09VV8cFtkb5hOTh6_aDPU_-ONzYvQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Request Timed Out When Generating Huge Data

2018-04-02 Thread tango ward
I tried loading the site locally to see how long will it take to load a
record of 1800 students. It took about a minute and a half locally. The
request timed out problem occurs when I try to generate a CSV report and
PDF. Both result to timed out even locally.

On Tue, Apr 3, 2018 at 8:12 AM, tango ward  wrote:

> Hi,
>
> SLR.
>
> At the moment, the largest number of students we have is 2000 in one
> campus. I haven't played around with the code but when I check it we're
> using a get_queryset function to get the data and filter it using Q. Then
> display it using get_context_data
>
> Code:
>
> class FinancialReportView(ApplicantReportMixin, ListView):
> template_name = 'education/dashboard/reports/financial_report.html'
> paginate_by = 50
>
> def get_queryset(self):
>
> student_filter = self.request.GET.get('student_filter', '')
>
> filter_date = self.request.GET.get('date', '')
> if not filter_date and not student_filter:
> return Recipient.objects.none()
>
> if student_filter in ['None', None]:
> student_filter = ''
> recipients = self.get_recipients()
> recipients = recipients.filter(enrolled=1)
> recipients = recipients.filter(enrollmentinfo__isnull=False)
>
> campus = self.request.GET.get('campus', '')
> if campus:
> recipients = recipients.filter(department__school=campus)
> year_level = self.request.GET.get('year_level', '')
>
> if year_level:
> recipients = recipients.filter(year_level=year_level)
>
> if student_filter and not student_filter == 'None':
> recipients = recipients.filter(
> Q(first_name__icontains=student_filter) |
> Q(last_name__icontains=student_filter) |
> Q(student_id__icontains=student_filter))
> recipients = recipients.select_related('department', 'program')
> return recipients
>
> def get_context_data(self, **kwargs):
> context = super(FinancialReportView, self).get_context_data(**
> kwargs)
>
> filter_form = FinancialReportFilterForm(
> data=self.request.GET,
> school_manager=self.request.user.schoolmanager,
> )
> output = []
> recipients = self.get_queryset()
>
> filter_date = self.request.GET.get('date', '')
> if filter_date in ['None', None]:
> filter_date = ''
> if filter_date:
> filter_date = dateutil.parser.parse(filter_date).date()
> page = self.request.GET.get('page', 1)
>
> for ctr, recipient in enumerate(recipients):
> total_amount = 0
> enrollment_info = recipient.get_current_enrollment_info()
> if enrollment_info:
> if filter_date:
> invoices = enrollment_info.
> philsmileinvoice_set.filter(
> due_date__lte=filter_date)
> else:
> invoices = enrollment_info.philsmileinvoice_set.all()
>
> for invoice in invoices:
> total_amount += invoice.get_remaining_balance()
>
> output.append([ctr, recipient, total_amount])
>
> if self.paginate_by:
> paginator = Paginator(output, self.paginate_by)
> try:
> output = paginator.page(page)
> except PageNotAnInteger:
> output = paginator.page(1)
> except EmptyPage:
> output = paginator.page(paginator.num_pages)
> context.update({
> 'paginator': paginator
> })
>
> context.update({
> 'outputs': output,
> 'form': filter_form,
> 'school_system': self.request.user.
> schoolmanager.school_system,
> })
> return context
>
>
>
>
> On Mon, Apr 2, 2018 at 1:54 PM, Babatunde Akinyanmi 
> wrote:
>
>> Hi,
>> How many records are we talking about? What code are you using to fetch
>> the records? In other words, add more information so that it's easier to
>> troubleshoot
>>
>> On Mon, 2 Apr 2018, 02:27 tango ward,  wrote:
>>
>>>
>>> Good day,
>>>
>>> I need suggestions on how to approach this problem.
>>>
>>> I am working on a task that needs to generate the list students per
>>> school. When the school has larger number of students, I am getting a
>>> request timed out error. I can filter the school per campus to lessen the
>>> number of students but the performance in displaying the list of students
>>> is still taking too long.
>>>
>>>
>>> Thanks,
>>> Jarvis
>>>
>>> --
>>> 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://grou

Re: Request Timed Out When Generating Huge Data

2018-04-02 Thread tango ward
Hi,

SLR.

At the moment, the largest number of students we have is 2000 in one
campus. I haven't played around with the code but when I check it we're
using a get_queryset function to get the data and filter it using Q. Then
display it using get_context_data

Code:

class FinancialReportView(ApplicantReportMixin, ListView):
template_name = 'education/dashboard/reports/financial_report.html'
paginate_by = 50

def get_queryset(self):

student_filter = self.request.GET.get('student_filter', '')

filter_date = self.request.GET.get('date', '')
if not filter_date and not student_filter:
return Recipient.objects.none()

if student_filter in ['None', None]:
student_filter = ''
recipients = self.get_recipients()
recipients = recipients.filter(enrolled=1)
recipients = recipients.filter(enrollmentinfo__isnull=False)

campus = self.request.GET.get('campus', '')
if campus:
recipients = recipients.filter(department__school=campus)
year_level = self.request.GET.get('year_level', '')

if year_level:
recipients = recipients.filter(year_level=year_level)

if student_filter and not student_filter == 'None':
recipients = recipients.filter(
Q(first_name__icontains=student_filter) |
Q(last_name__icontains=student_filter) |
Q(student_id__icontains=student_filter))
recipients = recipients.select_related('department', 'program')
return recipients

def get_context_data(self, **kwargs):
context = super(FinancialReportView,
self).get_context_data(**kwargs)

filter_form = FinancialReportFilterForm(
data=self.request.GET,
school_manager=self.request.user.schoolmanager,
)
output = []
recipients = self.get_queryset()

filter_date = self.request.GET.get('date', '')
if filter_date in ['None', None]:
filter_date = ''
if filter_date:
filter_date = dateutil.parser.parse(filter_date).date()
page = self.request.GET.get('page', 1)

for ctr, recipient in enumerate(recipients):
total_amount = 0
enrollment_info = recipient.get_current_enrollment_info()
if enrollment_info:
if filter_date:
invoices = enrollment_info.philsmileinvoice_set.filter(
due_date__lte=filter_date)
else:
invoices = enrollment_info.philsmileinvoice_set.all()

for invoice in invoices:
total_amount += invoice.get_remaining_balance()

output.append([ctr, recipient, total_amount])

if self.paginate_by:
paginator = Paginator(output, self.paginate_by)
try:
output = paginator.page(page)
except PageNotAnInteger:
output = paginator.page(1)
except EmptyPage:
output = paginator.page(paginator.num_pages)
context.update({
'paginator': paginator
})

context.update({
'outputs': output,
'form': filter_form,
'school_system': self.request.user.schoolmanager.school_system,
})
return context




On Mon, Apr 2, 2018 at 1:54 PM, Babatunde Akinyanmi 
wrote:

> Hi,
> How many records are we talking about? What code are you using to fetch
> the records? In other words, add more information so that it's easier to
> troubleshoot
>
> On Mon, 2 Apr 2018, 02:27 tango ward,  wrote:
>
>>
>> Good day,
>>
>> I need suggestions on how to approach this problem.
>>
>> I am working on a task that needs to generate the list students per
>> school. When the school has larger number of students, I am getting a
>> request timed out error. I can filter the school per campus to lessen the
>> number of students but the performance in displaying the list of students
>> is still taking too long.
>>
>>
>> Thanks,
>> Jarvis
>>
>> --
>> 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/CAA6wQLKn98Yq9JrbQQLVncm2pkEUz
>> aCYm_un0zZFMXQC8ewzrg%40mail.gmail.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

Re: Decoupling Postgres database credentials in django for deployment.

2018-04-02 Thread Mike Dewhirst

On 3/04/2018 8:49 AM, Mike Dewhirst wrote:

On 2/04/2018 7:59 PM, Cictani wrote:

Hi,

You could rename your dev settings file to for example 
'settings_dev.py' and only commit this file (add settings.py to 
.gitignore).


I wrote a tiny utility to read a file and retrieve credentials for any 
purpose but especially for keeping database credentials out of the 
repository.


It means I have to store the credentials files (separate file for each 
eg database, email etc) in a place accessible to the web server but 
out of the doc root.


The settings file only contains calls to the utility like this ...

# production.py

from .base import *



SITE_ID = 1  # prd



ALLOWED_HOSTS += ['redacted',]



# Databases  # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
# # # # #


dbdefault = getcreds(fname='db.host', project="{0}-prd".format(PROJECT))

DATABASES = {

    'default': {

    'ENGINE': 'django.db.backends.postgresql_psycopg2',

    'NAME': PROJECT,

    'USER': dbdefault[0],

    'PASSWORD': dbdefault[1],

    'HOST': dbdefault[2],

    'PORT': dbdefault[3],

    }

}



email_creds = getcreds(fname='smtp.host', 
project="{0}-prd".format(PROJECT))


EMAIL_HOST = email_creds[0]

EMAIL_PORT = email_creds[1]

EMAIL_HOST_USER = email_creds[2]

EMAIL_HOST_PASSWORD = email_creds[3]

DEFAULT_FROM_EMAIL = email_creds[4]

#EMAIL_USE_TLS = True

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

DEFAULT_CHARSET = 'utf-8'


And for local testing ...

# mike-test.py

from .local import *



SITE_ID = 3

DEBUG = True

SESSION_COOKIE_SECURE = False

CSRF_COOKIE_SECURE = False

SECURE_BROWSER_XSS_FILTER = False

SECURE_SSL_REDIRECT = False



TEMPLATES[0]['OPTIONS']['debug'] = DEBUG

TEST_RUNNER = 'django.test.runner.DiscoverRunner'



INSTALLED_APPS = DEFAULT_APPS + THIRD_PARTY_APPS + LOCAL_APPS



# # # # # # # # # # IN-MEMORY TEST DATABASE

dbdefault = getcreds(fname='db.host', 
project="{0}-local".format(PROJECT))


Just realised I don't need to make that call for the in-memory database. 
I should have posted the local.py settings which uses a local postgres 
database. But you get the idea. Apologies for wasting space on the list.


M.



DATABASES = {

    'default': {

    "ENGINE": "django.db.backends.sqlite3",

    "NAME": ":memory:",

    "USER": "",

    "PASSWORD": "",

    "HOST": "",

    "PORT": "",

    }

}



EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'


And here is the utility ...

#getcreds.py

from __future__ import unicode_literals, absolute_import, division



import os





def getcreds(fname, project, credsroot='/var/www/creds', credsdir=None):

    """ return a list of userid and password and perhaps other data """

    if credsdir is None:

    credsdir = os.path.join(credsroot, project)

    creds = list()

    fname = os.path.join(credsdir, fname).replace("\\", "/")

    with open(fname, 'r') as f:

    for line in f:

    # remove leading/trailing whitespace and append to list

    creds.append(line.strip())

    assert creds, "The list of credentials is empty"

    return creds








On your Linux Server you could create a new directory in /etc

like:

/etc/django

/etc/django/app1
/etc/django/app2
...

There you store your production 'settings.py'

In your app directory you can create a symbolic link to these files:

|
ln -s /etc/django/app1/settings.py /path/to/app1/app1/
|

You have to make sure the directory in /etc is readably by www-data 
or whatever user you run your webserver with:


Now you can change the settings in the /etc directory and the 
settings are quite secure since only root will be able to change them 
by default. And you now do it the Linux way by storing all settings 
in /etc


Since you added settings.py to .gitignore it won't get overwritten. 
You should make backups of your whole /etc directory anyways so your 
django settings also get saved.


--
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/8f3d6ebb-9db1-455e-99e3-d337490ffab5%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...@googlegr

Re: Decoupling Postgres database credentials in django for deployment.

2018-04-02 Thread Mike Dewhirst

On 2/04/2018 7:59 PM, Cictani wrote:

Hi,

You could rename your dev settings file to for example 
'settings_dev.py' and only commit this file (add settings.py to 
.gitignore).


I wrote a tiny utility to read a file and retrieve credentials for any 
purpose but especially for keeping database credentials out of the 
repository.


It means I have to store the credentials files (separate file for each 
eg database, email etc) in a place accessible to the web server but out 
of the doc root.


The settings file only contains calls to the utility like this ...

# production.py

from .base import *



SITE_ID = 1  # prd



ALLOWED_HOSTS += ['redacted',]



# Databases  # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

dbdefault = getcreds(fname='db.host', project="{0}-prd".format(PROJECT))

DATABASES = {

    'default': {

    'ENGINE': 'django.db.backends.postgresql_psycopg2',

    'NAME': PROJECT,

    'USER': dbdefault[0],

    'PASSWORD': dbdefault[1],

    'HOST': dbdefault[2],

    'PORT': dbdefault[3],

    }

}



email_creds = getcreds(fname='smtp.host', project="{0}-prd".format(PROJECT))

EMAIL_HOST = email_creds[0]

EMAIL_PORT = email_creds[1]

EMAIL_HOST_USER = email_creds[2]

EMAIL_HOST_PASSWORD = email_creds[3]

DEFAULT_FROM_EMAIL = email_creds[4]

#EMAIL_USE_TLS = True

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

DEFAULT_CHARSET = 'utf-8'


And for local testing ...

# mike-test.py

from .local import *



SITE_ID = 3

DEBUG = True

SESSION_COOKIE_SECURE = False

CSRF_COOKIE_SECURE = False

SECURE_BROWSER_XSS_FILTER = False

SECURE_SSL_REDIRECT = False



TEMPLATES[0]['OPTIONS']['debug'] = DEBUG

TEST_RUNNER = 'django.test.runner.DiscoverRunner'



INSTALLED_APPS = DEFAULT_APPS + THIRD_PARTY_APPS + LOCAL_APPS



# # # # # # # # # # IN-MEMORY TEST DATABASE

dbdefault = getcreds(fname='db.host', project="{0}-local".format(PROJECT))

DATABASES = {

    'default': {

    "ENGINE": "django.db.backends.sqlite3",

    "NAME": ":memory:",

    "USER": "",

    "PASSWORD": "",

    "HOST": "",

    "PORT": "",

    }

}



EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'


And here is the utility ...

#getcreds.py

from __future__ import unicode_literals, absolute_import, division



import os





def getcreds(fname, project, credsroot='/var/www/creds', credsdir=None):

    """ return a list of userid and password and perhaps other data """

    if credsdir is None:

    credsdir = os.path.join(credsroot, project)

    creds = list()

    fname = os.path.join(credsdir, fname).replace("\\", "/")

    with open(fname, 'r') as f:

    for line in f:

    # remove leading/trailing whitespace and append to list

    creds.append(line.strip())

    assert creds, "The list of credentials is empty"

    return creds








On your Linux Server you could create a new directory in /etc

like:

/etc/django

/etc/django/app1
/etc/django/app2
...

There you store your production 'settings.py'

In your app directory you can create a symbolic link to these files:

|
ln -s /etc/django/app1/settings.py /path/to/app1/app1/
|

You have to make sure the directory in /etc is readably by www-data or 
whatever user you run your webserver with:


Now you can change the settings in the /etc directory and the settings 
are quite secure since only root will be able to change them by 
default. And you now do it the Linux way by storing all settings in /etc


Since you added settings.py to .gitignore it won't get overwritten. 
You should make backups of your whole /etc directory anyways so your 
django settings also get saved.


--
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/8f3d6ebb-9db1-455e-99e3-d337490ffab5%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/b6895f2c-4bce-11f1-6934-6d36241015eb%40dewhirst.c

Re: Error H10 while deploying Django project

2018-04-02 Thread Andréas Kühne
Hi,

You need to give us more information. You should be able to get logs from
the python part of the application, because all this is saying currently is
that there is an error in your code (or at least the way heroku expects the
code to be).
A 503 error (which you are getting) means that the python part is not
responding correctly.

Regards,

Andréas

2018-04-02 22:05 GMT+02:00 prince gosavi :

> heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/"
> host=miniprojectcc.herokuapp.com  dyno= connect= service= status=503
> bytes= protocol=http
> ^C(miniproject-wxhZ76U4)
>  heroku ps -a miniprojectcc
> Free dyno hours quota remaining this month: 549h 30m (99%)
>
> === web (Free): gunicorn -t 3000 miniproject.wsgi (1)
> web.1: crashed 2018/04/03 01:20:39 +0530 (~ 5m ago)
> Help please.
>
> --
> 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/d4c2f92d-e8ef-4ed3-9a38-8c43df5e6db6%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/CAK4qSCf93NqALfHxiuzT%2BRAknPbB-xPM5JeBmz3g6yz5s5xVHg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Error H10 while deploying Django project

2018-04-02 Thread prince gosavi
heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" 
host=miniprojectcc.herokuapp.com  dyno= connect= service= status=503 bytes= 
protocol=http
^C(miniproject-wxhZ76U4)
 heroku ps -a miniprojectcc
Free dyno hours quota remaining this month: 549h 30m (99%)

=== web (Free): gunicorn -t 3000 miniproject.wsgi (1)
web.1: crashed 2018/04/03 01:20:39 +0530 (~ 5m ago)
Help please.

-- 
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/d4c2f92d-e8ef-4ed3-9a38-8c43df5e6db6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Having trouble writing loop in Django template

2018-04-02 Thread shawnmhy


Hello guys I am currently working on django views and templates and met 
some problems. I have a model named 'metabolites', which contains: id, 
name, compartment, charge and formula 5 components. I have another model 
named 'Reactionsmeta', which contains: id(reactions), name, metabolie1, 
metabolite2,  metabolite6. The table of this model is not filled 
complete, because sometimes one id corresponds to 5 metabolites, but 
sometimes even 20.

I write a template which can displays all the reaction, when I click on the 
reaction and enter the detail page, I also want to display the metabolites 
that involve in this reactions. My views.py and templates are written as 
below:


reactions_detail.html
{% extends 'Recon/Base.html' %}{% load static %}{% block title %}Reaction 
Details{% endblock %}{% block body %}{{ reactionsmeta.id }}{{ 
reactionsmeta.name}}



{% if reactionsmeta.id %}

{% else %}
No image to display
{% endif %}

{{ reactionsmeta.id }} {{ reactionsmeta.name 
}}



[image: index.html] 

views.pyfrom django.views import genericfrom .models import 
Reactionsmeta,Metabolites,Reactionsfrom django.shortcuts import render

class IndexView(generic.ListView):
template_name = 'Recon/index.html'
context_object_name = 'Reactions_object'
def get_queryset(self):
return Reactionsmeta.objects.all()

class DetailsView(generic.DetailView):
model = Reactionsmeta
template_name = 'Recon/reactions_detail.html'
def get_context_data(self, **kwargs):
context = super(DetailsView, self).get_context_data(**kwargs)
context['metabolite'] = Metabolites.objects.all()
context['reactions'] = Reactions.objects.all()

# And so on for more models
return context

How can I write the loop in reaction_detail.html???

-- 
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/76028827-99ad-43a3-8bb1-831f8f6df183%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Infinite scrolling, Ajax, Phone or PC?

2018-04-02 Thread Julio Biason
Hi Jamaldin,

Yeah, there is nothing to do with Django, except for a part in the infinite
scrolling.

For infinite scrolling, you'll keep loading more data from the server and
adding it to the DOM when the page position reaches a certain point. Both
of those can be done with jQuery, for example, but you'll need to write
both the checker for position, loading more data and appending to the DOM
using JavaScript. The only difference is that instead of loading all the
page, you'll return only your list, either as a JSON to be "templated" by
JavaScript or returning the piece of HTML you want to add (basically, your
template won't need to `{% extend "base.html" %}`, so to say.)

Going through pages without reloading is, again, a job for JavaScript. You
basically do the same thing you did above, but instead of appending more
stuff to the DOM, you replace it.

For buttons, you can check the user agent (which you can get from
`request.meta['USER-AGENT']` on your views). But you'll need a bunch of
list of browsers and it's not really reliable (people can replace the user
agent at free will, with extensions). One solution would use the viewport
size (the area available for the browser to render) and do that directly in
JS or event CSS -- check Bootstrap "hide-xs" and the likes.

But, again, your questions are more towards JavaScript than Django.

On Mon, Apr 2, 2018 at 10:44 AM, Jamaldin Pro 
wrote:

>  Hello.
>
>How can I make Infinite scrolling html? example: https://www.megacom.
> kg/hype/ru.html#instruction
>How can I go from first url to another without reloading the website?
>How can I know if the user is entering my website from phone or pc? If
> user is entering from phone it should show the Whatsapp button and If user
> is entering from PC it should hide it.
>
> " I can't find any place to ask this thing, and this place might be the
> wrong place. SORRY if it is like that. If you can answer even one of this
> answer it plz "
>
> 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/16c617ca-c229-4056-b0de-8e5f1424dc00%40googlegroups.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>



-- 
*Julio Biason*, Sofware Engineer
*AZION*  |  Deliver. Accelerate. Protect.
Office: +55 51 3083 8101   |  Mobile: +55 51
*99907 0554*

-- 
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/CAEM7gE10ECahgmb%2BsFLtFRQV6ERaaSqygk1tswssaKRzNh69Ew%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Subquery and FieldError: Expression contains mixed types. You must set output_field.

2018-04-02 Thread Fabio Andrés García Sánchez
Hi!

What I am trying to do is filtering using queryset, get a value when 
verified is true. It works fine when:

mano_obra = 
HoraHojaTrabajo.objects.values('literal__proyecto__id_proyecto').annotate(
 cantidad_horas=ExpressionWrapper(Sum((F('cantidad_minutos') / 60)),
 output_field=DecimalField(max_digits=4)),
 costo_total=ExpressionWrapper(
 Sum((F('cantidad_minutos') / 60) * (F('hoja__tasa__costo') / 
F('hoja__tasa__nro_horas_mes'))),
 output_field=DecimalField(max_digits=4))
).filter(
 literal__proyecto__id_proyecto=OuterRef('id_proyecto')
)
qs = Proyecto.objects.prefetch_related(
 'mis_literales'
).annotate(costo_mano_obra=Subquery(mano_obra.values('costo_total')),
 cantidad_horas_mano_obra=Subquery(mano_obra.values('cantidad_horas')))


but later, when I add in the filter (verificado=True)

mano_obra = HoraHojaTrabajo.objects.values('literal__proyecto__id_proyecto'
).annotate(
 cantidad_horas=ExpressionWrapper(Sum((F('cantidad_minutos') / 60)),
 output_field=DecimalField(max_digits=4)),
 costo_total=ExpressionWrapper(
 Sum((F('cantidad_minutos') / 60) * (F('hoja__tasa__costo') / F(
'hoja__tasa__nro_horas_mes'))),
 output_field=DecimalField(max_digits=4))
).filter(
 literal__proyecto__id_proyecto=OuterRef('id_proyecto'),
 verificado=True
)
qs = Proyecto.objects.prefetch_related(
 'mis_literales'
).annotate(costo_mano_obra=Subquery(mano_obra.values('costo_total')),
 cantidad_horas_mano_obra=Subquery(mano_obra.values('cantidad_horas')))

and I got the following message:


Request Method: GET
Request URL: http://127.0.0.1:8000/api/proyectos/
Django Version: 2.0.1
Exception Type: FieldError
Exception Value: 

Expression contains mixed types. You must set output_field.

Exception Location: 
/Users/fabioandresgarciasanchez/PycharmProjects/virtualenv/proyectos_intranet_env/lib/python3.6/site-packages/django/db/models/expressions.py
 
in _resolve_output_field, line 298
Python Executable: 
/Users/fabioandresgarciasanchez/PycharmProjects/virtualenv/proyectos_intranet_env/bin/python
Python Version: 3.6.3


How can I get this working?

-- 
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/6dbf3cc6-6941-4cc8-bffd-b31105b872e2%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Infinite scrolling, Ajax, Phone or PC?

2018-04-02 Thread Jamaldin Pro
 Hello.

   How can I make Infinite scrolling html? example: 
https://www.megacom.kg/hype/ru.html#instruction
   How can I go from first url to another without reloading the website?
   How can I know if the user is entering my website from phone or pc? If 
user is entering from phone it should show the Whatsapp button and If user 
is entering from PC it should hide it.

" I can't find any place to ask this thing, and this place might be the 
wrong place. SORRY if it is like that. If you can answer even one of this 
answer it plz "

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/16c617ca-c229-4056-b0de-8e5f1424dc00%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Templates and URL Mappings

2018-04-02 Thread Daniel Roseman
On Monday, 2 April 2018 12:00:31 UTC+1, Will Burchell wrote:


 

> from django.conf.urls import url
> from . import views
>
> app_name = 'stock' # Referenced by template, ie  item in index.html
>
> urlpatterns = [
> # /stock/
> url(r'^$', views.index, name="index"),
> # /stock/nnn/
> url(r'^(?P[0-9]+)/$', views.detail, name="detail"),
> # /stock/supplier
> url(r'^supplier', views.supplier, name="supplier"),
> # /stock/supplier/nnn/
> url(r'^supplier/(?P[0-9]+)/$', views.supplierdetail, name
> ="supplierdetail"),
> ] 
>


Firstly, as a clarification, URLs don't map to templates at all; they map 
to views, and views may or may not render templates. But you do seem to 
know this.

Your problem however is simply to do with regexes; you don't terminate your 
supplier pattern, so it matches everything beginning with "supplier". It 
should be:

url(r'^supplier$', views.supplier, name="supplier"),

or use the new path syntax in Django 2.0:

path('supplier', ...)

-- 
DR.

-- 
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/5b9ca4ab-63e3-4437-aca6-925cbdccd7e9%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Templates and URL Mappings

2018-04-02 Thread Will Burchell
Hi all, I'm having some trouble understanding fairly basic URL mappings and 
how they rout through to templates. I have an app "stock" which is 
registered in my base admin.py. I have three classes in my app, 
stock\models.py listed below:

from django.db import models


class Supplier(models.Model):
supplierName = models.CharField(max_length=64, default='')
def __str__(self):
return self.supplierName


class Stock(models.Model):
stockCode = models.CharField(max_length=32, default='null')
stock_supplier = models.ManyToManyField(Supplier, through=
'SupplierStock') # Populated automatically
stockDescription = models.CharField(max_length=128)
retailPrice = models.CharField(max_length=16, default='')

def __str__(self):
return self.stockCode + '; ' + self.stockDescription + ' @£' + self.
retailPrice

#Quote
class SupplierStock(models.Model):
stock = models.ForeignKey(Stock, on_delete=models.CASCADE)
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
supplierCode = models.CharField(max_length=32)
supplierPrice = models.CharField(max_length=16)
quoteRef = models.CharField(max_length=32, default="")
unitSize = models.PositiveSmallIntegerField(default=1)

def __str__(self):
return self.supplierCode + ', £' + self.supplierPrice + ' Per ' + 
str(self.unitSize) + '; ' + self.quoteRef
  
The app is a basic stock record for stock items, suppliers, and quotes as 
per "SupplierStock". I am playing around trying to get the individual 
classes in my stock\models.py to map to templates in 
"stock\templates\stock\" but am only having partial success. I can get my 
index.html and details.html to display a list of stock Items, and details 
for the stock items respectfully, but am having trouble displaying similar 
results for the supplier.html template and supplierdetail.html.  Here's my 
code for stock\urls.py

from django.conf.urls import url
from . import views

app_name = 'stock' # Referenced by template, ie  item in index.html

urlpatterns = [
# /stock/
url(r'^$', views.index, name="index"),
# /stock/nnn/
url(r'^(?P[0-9]+)/$', views.detail, name="detail"),
# /stock/supplier
url(r'^supplier', views.supplier, name="supplier"),
# /stock/supplier/nnn/
url(r'^supplier/(?P[0-9]+)/$', views.supplierdetail, name=
"supplierdetail"),
]

The stock\views.py code:


from django.shortcuts import render, get_object_or_404
from .models import Stock, Supplier, SupplierStock


def index(request):
all_stock = Stock.objects.all()
return render(request, 'stock/index.html', {'all_stock' : all_stock})

def detail(request, stock_id):
stock = get_object_or_404(Stock, id=stock_id)
return render(request, 'stock/detail.html', {'stock' : stock})

def supplier(request):
all_supplier = Supplier.objects.all()
return render(request, 'stock/supplier.html', {'all_supplier' : 
all_supplier})

def supplierdetail(request, supplier_id):
supplier = get_object_or_404(Supplier, id=supplier_id)
return render(request, 'stock/supplierdetail.html', {'supplier' : 
supplier})


The code for stock\templates\stock\index.html:

{% if all_stock %}
Stock list

{% for stock in all_stock %}
{{ stock.stockCode 
}}; {{ stock.stockDescription }}
{% endfor %}

{% else %}
No stock found
{% endif %}

...and a simple stock\templates\stock\detail.html that shows detail for the 
stock item as expected:

{{ stock }}

I thought I would be able to get away with copying most of the code to 
achieve similar results for the supplier and supplierdetail templates. My 
stock\supplier.html correctly displays a list of links to suppliers, but 
the links do not work, the it just stays on the page. Here's what I have 
for stock\templates\stock\supplier.html

{% if all_supplier %}
Supplier list

{% for supplier in all_supplier %}
{{ 
supplier.supplierName }}
{% endfor %}

{% else %}
No Supplier found
{% endif %}

...and for stock\templates\stock\supplierdetail.html

Supplier details here
{{ supplier }}

As mentioned, the index.html and detail.html templates render fine, but the 
links in supplier.html are dead. I'll be trying to connect the models up in 
one template to display individual quotes from suppliers but am having 
trouble getting past this step. The project is using Django 1.11.8 and 
Python 3.6.2 on Windows 8.1 Pro.

I should also mention that the Django admin page displays all the 
information I'm trying to display fine. Thanks for taking the time to read 
my issue, and I'll be very grateful for any assistance offered!

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

Re: Decoupling Postgres database credentials in django for deployment.

2018-04-02 Thread Cictani
Hi,

You could rename your dev settings file to for example 'settings_dev.py' 
and only commit this file (add settings.py to .gitignore).

On your Linux Server you could create a new directory in /etc

like:

/etc/django

/etc/django/app1
/etc/django/app2
...

There you store your production 'settings.py'

In your app directory you can create a symbolic link to these files:

ln -s /etc/django/app1/settings.py /path/to/app1/app1/

You have to make sure the directory in /etc is readably by www-data or 
whatever user you run your webserver with:

Now you can change the settings in the /etc directory and the settings are 
quite secure since only root will be able to change them by default. And 
you now do it the Linux way by storing all settings in /etc

Since you added settings.py to .gitignore it won't get overwritten. You 
should make backups of your whole /etc directory anyways so your django 
settings also get saved.

-- 
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/8f3d6ebb-9db1-455e-99e3-d337490ffab5%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.