Re: Using {% include %} and getting context with me

2019-02-13 Thread Mikkel Kromann
Bah! I should really read the docs more carefully.

>From the docs: "*Include:* *Loads a template and renders it with the 
current context.*" 
https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#include

The example I posted actually works perfectly fine with regards to the 
include.
I just needed to fix spelling errors in the {% block %} names.
And in my_page1.html I also forgot the block from the base.html.
A working example of base.html and my_page1.html ought to look like this.

base.html:

{% block content %}
{% endblock %}


my_page1.html:
{% extends "base.html" %}
{% block % content %}

{% block foo %}
{% include foo.html %}
{% endblock foo % }

{% block bar %}
{% include bar.html %}
{% endblock bar % }

{% block baz %}
{% include baz.html %}
{% endblock baz % }

{% endblock content % }

Sorry. Keep calm, carry on :)

Mikkel

onsdag den 13. februar 2019 kl. 15.47.10 UTC+1 skrev Mikkel Kromann:
>
> Hi.
>
> I have a collection of apps where I find repeating myself when rendering 
> tables in the templates.
> In the stylised example below I have three types of tables, foo, bar and 
> baz.
> Each app is supposed to render various combinations of tables from its own 
> models, but also from other models' tables.
> (yes, it is a hideously complex structure - and believe me, I've tried to 
> simplify it a lot - even with some success)
>
> Can I - in a page which extends a base, include various "template 
> snippets", so that I can reuse the template snippets across several apps?
>
> base.html:
> 
> ...
> 
>
> my_page1.html:
> {% extends "base.html" %}
>
> {% block foo %}
> {% include foo.html %}
> {% endblock % }
>
> {% block bar %}
> {% include bar.html %}
> {% endblock % }
>
> {% block baz %}
> {% include baz.html %}
> {% endblock % }
>
> foo.html:
> {% if foo_context %}
> 
> {% endif %}
>
> bar.html:
> {% if bar_context %}
> 
> {% endif %}
>
> baz.html:
> {% if baz_context %}
> 
> {% endif %}
>
> As I understand, the snippets are evaluated without the context of 
> my_page1.html, right (e.g. foo_context).
> The docs (
> https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#include) 
> seem to suggest that I could work around the context problem by writing:
>
> {% include foo.html with foo_context=foo_context %}
>
>
> Is that correctly understood in this case?
>
>
> thanks, Mikkel
>
>  
>
>

-- 
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/811a1421-4d7f-432f-ad1c-95e4f6015af7%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Using {% include %} and getting context with me

2019-02-13 Thread Mikkel Kromann
Hi.

I have a collection of apps where I find repeating myself when rendering 
tables in the templates.
In the stylised example below I have three types of tables, foo, bar and 
baz.
Each app is supposed to render various combinations of tables from its own 
models, but also from other models' tables.
(yes, it is a hideously complex structure - and believe me, I've tried to 
simplify it a lot - even with some success)

Can I - in a page which extends a base, include various "template 
snippets", so that I can reuse the template snippets across several apps?

base.html:

...


my_page1.html:
{% extends "base.html" %}

{% block foo %}
{% include foo.html %}
{% endblock % }

{% block bar %}
{% include bar.html %}
{% endblock % }

{% block baz %}
{% include baz.html %}
{% endblock % }

foo.html:
{% if foo_context %}

{% endif %}

bar.html:
{% if bar_context %}

{% endif %}

baz.html:
{% if baz_context %}

{% endif %}

As I understand, the snippets are evaluated without the context of 
my_page1.html, right (e.g. foo_context).
The docs 
(https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#include) 
seem to suggest that I could work around the context problem by writing:

{% include foo.html with foo_context=foo_context %}


Is that correctly understood in this case?


thanks, Mikkel

 

-- 
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/8b0eca46-1d00-4bdd-8aba-d8d3a2043a1b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How can I read child model class' DecimalField attribute 'decimal_places' from inside a parent Meta class

2018-12-27 Thread Mikkel Kromann
Ah! It turns out that there is a _meta method for that.

class Vehicles(models.Model):

def get_speed_decimal_places(self):
return self._meta.get_field('speed').decimal_places


Though I'm still wondering why my first shot at the problem worked from 
within the child class, but not from the parent class.


Mikkel

torsdag den 27. december 2018 kl. 20.59.43 UTC+1 skrev Mikkel Kromann:
>
>
> Hello.
>
> I have a parent Meta class and some child classes.
> I would like to read the decimal_places attribute from DecimalField of my 
> child instances using a function in my parent class.
> I am able to read the attribute from inside my child classes, but I cant 
> crack how to read from a function in the parent class.
> Using @classmethod I get one error, not using it, I get another (see 
> comments in the condensed example code below).
>
> I'm presently learning Python and Django, so please feel free to educate 
> me a bit here :)
>
> thanks, Mikkel
>
>
> from django.db import models
> from django.shortcuts import render
>
> class Vehicles(models.Model):
> 
> speed = models.DecimalField(max_digits=5, decimal_places=2)
> 
> @classmethod
> def get_speed_decimal_places(self):
> # @classmethod: Will raise 'DeferredAttribute' object has no attribute 
> 'decimal_places'
> # no classmethod:   Will raise 'NoneType' object has no attribute 
> 'decimal_places'
> return self.speed.decimal_places
> 
> class Meta:
> abstract = True
>
> class Train(Vehicles):
> speed = models.DecimalField(max_digits=5, decimal_places=2)
> train_speed_decimals = speed.decimal_places
> 
> class Aeroplane(Vehicles):
> speed = models.DecimalField(max_digits=5, decimal_places=1)
> aeroplane_speed_decimals = speed.decimal_places
> 
> def SpeedView(request):
> t = Train()
> context = {}
> # This works just fine
> context['decimals_own'] = t.train_speed_decimals
> # This raises error in get_speed_decimal_places()
> context['decimals_cls'] = t.get_speed_decimal_places()
> 
> return render(request,'speed_index.html',context)
>
>
>

-- 
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/6123eb77-5c35-49e9-961d-860e06b9d7cb%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


How can I read child model class' DecimalField attribute 'decimal_places' from inside a parent Meta class

2018-12-27 Thread Mikkel Kromann

Hello.

I have a parent Meta class and some child classes.
I would like to read the decimal_places attribute from DecimalField of my 
child instances using a function in my parent class.
I am able to read the attribute from inside my child classes, but I cant 
crack how to read from a function in the parent class.
Using @classmethod I get one error, not using it, I get another (see 
comments in the condensed example code below).

I'm presently learning Python and Django, so please feel free to educate me 
a bit here :)

thanks, Mikkel


from django.db import models
from django.shortcuts import render

class Vehicles(models.Model):

speed = models.DecimalField(max_digits=5, decimal_places=2)

@classmethod
def get_speed_decimal_places(self):
# @classmethod: Will raise 'DeferredAttribute' object has no attribute 
'decimal_places'
# no classmethod:   Will raise 'NoneType' object has no attribute 
'decimal_places'
return self.speed.decimal_places

class Meta:
abstract = True

class Train(Vehicles):
speed = models.DecimalField(max_digits=5, decimal_places=2)
train_speed_decimals = speed.decimal_places

class Aeroplane(Vehicles):
speed = models.DecimalField(max_digits=5, decimal_places=1)
aeroplane_speed_decimals = speed.decimal_places

def SpeedView(request):
t = Train()
context = {}
# This works just fine
context['decimals_own'] = t.train_speed_decimals
# This raises error in get_speed_decimal_places()
context['decimals_cls'] = t.get_speed_decimal_places()

return render(request,'speed_index.html',context)


-- 
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/27f4b78d-86f8-4c73-b4bd-707ee677e530%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Point-in-Time version history with Django with propose and commit or reject

2018-10-01 Thread Mikkel Kromann

Dear Django users.

I am looking into the so-called Point-In-Time architecture for databases 
with version history. See e.g.
https://www.red-gate.com/simple-talk/sql/database-administration/database-design-a-point-in-time-architecture/

One reason I like PTA is that a version history for my project is a 
"nice-to".
The "need-to" reason is, however, that I need to have a general system for 
"propose, then commit or reject" updates to my data tables.

With "propose and commit or reject" I specifically think of users uploading 
CSV tables through a table web interface.
The website will then inform the user of the number of rows changed, total 
number of rows and perhaps even more detailed information.

I am aware that I could perhaps store the information in another table 
until the new data is committed or rejected.
However, what I am trying to build is a sort of mini-data warehouse 
framework for storing and modifying data for scientific calculations.
A central feature is, that the (super)users themselves are defining the 
tables they want in the data warehouse by coding simple Django models.
So, what I need is a structure which allows me to add the necessary columns 
to whatever model the user creates.
Enter "class meta" - yay, I can add version_begin and version_end to keep 
PTA on all tables the user creates, if she/he uses my meta class.

Let's take the most complicated example of updating a record. Let's say I 
have two tables: 
- Country (a primary key field, and a text field for the name)
- City (a primary key field, a foreign key to country, and a text field for 
the name)
Both tables additionally have columns describing "version_begin", 
"version_end" and "previous_primary_key"

Now, if I have misspelled the name of a country, I'd like not to have a new 
primary key for the correctly spelled country.
In that case, I'd have to correct the all the foreign keys of the city 
table.
So, why not simply insert a new country record (with a new PK) in the 
"propose" stage.
Then, if I commit, I simply switch the content of the data column (here the 
two misspelled names, using the previous_primary_key, and also fixing the 
previous primary key as well).
Simple! What could possibly go wrong?
Also, the database will be quite heavy with the "city" like tables, i.e. a 
lot of big tables with multiple foreign keys to the primary keys only 
tables (like country).
So, it seems more efficient - albeit a bit hacky - to make a small 
manipulation of the primary table, rather than correct potentially a lot of 
foreign keys.
Probably a lot, but my database knowledge barely stretches to third 
normalisation, so ... help!

QUESTION 1:
Are there any Django modules with propose-commit/reject functionality that 
I can use already (please correct me if I got something wrong)?

- Django-Reversion: is a duplicate history table, so a no-go 
- django-simple-histroy: Also (?) a duplicate table or transaction history
- django-dirtyfields: updates other tables with foreign key links
- cleanerversion: Seems to be PTA, but can I implement the 
propose-commit/reject that I need?
- django-easy-audit: Logs transactions, don't allow "propose-commit/reject" 
(?)
... and then some others which seemed not that relevant (again, I may have 
missed something).

Also, a nice reference to "slowly changing dimensions", though it seems 
less Django specific (i.e. primary key is combination of multple colums).
https://en.wikipedia.org/wiki/Slowly_changing_dimension#Type_2


QUESTION 2:
Or is the "switch values" approach just ugly, but not completely 
far-fetched?
My +40 years database experienced father in-law quite rightly named this as 
"hammering a screw", 
But if it has a chance of working, I'm a quite pragmatic guy (my apologies 
to database afficinados already) ...


Do ask questions if I'm not entirely clear. 
I could have written many pages of text more, but tried to keep it a bit 
short.



thanks, Mikkel

-- 
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/3e6a3154-f3ef-4b17-9d77-7db27cdeb473%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: GROUP BY

2018-08-14 Thread Mikkel Kromann
Thanks for your patience Matthew.I finally got it. 
I'm still learning the ropes of Django, and I got caught up in multiple 
errors (the order of lines in the query and picking out query values as 
dict elements or object elements).

The running code with GROUP BY using annotated functions looks like this:

contract_query = ( Project.objects
  .filter(department=department_id)
  .filter(datePipeline__year=year)
  .filter(stage="WON")
  .annotate(contracted=Sum('ownProduction'))
  .annotate(week=ExtractWeek('dateContract'))
  .values('market__market','week','contracted')
  ) 


cheers + thanks again, Mikkel
tirsdag den 14. august 2018 kl. 20.40.16 UTC+2 skrev Matthew Pava:
>
> Sometimes it helps to print out the results one function at a time to get 
> an idea what Django is returning.
>
>  
>
> If you want to include “contracted” in your result set, you have to 
> include “contracted” in your values function.  Values limits the result set 
> to the columns you specify.
>
>  
>
> I suggest reviewing the annotation and values docs here:
>
>
> https://docs.djangoproject.com/en/2.1/topics/db/aggregation/#order-of-annotate-and-values-clauses
>
>  
>
>  
>
> *From:* django...@googlegroups.com  [mailto:
> django...@googlegroups.com ] *On Behalf Of *Mikkel Kromann
> *Sent:* Tuesday, August 14, 2018 1:27 PM
> *To:* Django users
> *Subject:* Re: GROUP BY
>
>  
>
>  
>
> @galan: 
>
> the __ is reference to a foreign key name for market, and __year is a 
> function extracting the year from the datefield.
>
> Sorry for not posting the model, that would have helped avoiding this.
>
>  
>
> @matthew
>
> Yes, that's right. That was one error down. The following code works well, 
> except that it doesn't group by week.
>
>  
>
> contract_query = ( Project.objects
>   .values('market__market')
>   .filter(department=department_id)
>   .filter(datePipeline__year=year)
>   .filter(stage="WON")
>   .annotate(contracted=Sum('ownProduction'))
>   .annotate(week=ExtractWeek('dateContract'))
>
>
> So, we can't add week to the first values line, since week has yet to be 
> defined. So I tried moving it to the line after annotation of week:
>
>  
>
> contract_query = ( Project.objects
>   .filter(department=department_id)
>   .filter(datePipeline__year=year)
>   .filter(stage="WON")
>   .annotate(contracted=Sum('ownProduction'))
>   .annotate(week=ExtractWeek('dateContract'))
>   .values('market__market','week')
>
>  
>
> WIth the code above, however, the error comes back: I get a "key error" 
> for "contracted". So is that because of week? I tried:
>
>  
>
> contract_query = ( Project.objects
>   .filter(department=department_id)
>   .filter(datePipeline__year=year)
>   .filter(stage="WON")
>   .annotate(contracted=Sum('ownProduction'))
>   .annotate(week=ExtractWeek('dateContract'))
>   .values('market__market')
>
>  
>
> No, same "key error" for "contracted". It seems to me that having the 
> values() statement after the annotation deletes the annotation- is that 
> correct?
>
> And is that intended behavior?
>
>  
>
> If so, how can I then group by the week function of a datefield?
>
> Or is there something that I got completely wrong?
>
>  
>
> thanks + cheers, Mikkel
>
>  
>
>
> tirsdag den 14. august 2018 kl. 15.28.01 UTC+2 skrev Matthew Pava:
>
> Ah, the error has the answer.  contract_row is a dictionary, so you need 
> to access it as if it were a dictionary.
>
> contract_sum = contract_row['contracted']
>
>  
>
> *From:* django...@googlegroups.com [mailto:django...@googlegroups.com] *On 
> Behalf Of *Mikkel Kromann
> *Sent:* Monday, August 13, 2018 11:51 PM
> *To:* Django users
> *Subject:* Re: GROUP BY
>
>  
>
>  
>
> Thanks. But strange - exactly same error: 
>
> 'dict' object has no attribute 'contracted'
>
>  
>
> con

Re: GROUP BY

2018-08-14 Thread Mikkel Kromann

@galan: 
the __ is reference to a foreign key name for market, and __year is a 
function extracting the year from the datefield.
Sorry for not posting the model, that would have helped avoiding this.

@matthew
Yes, that's right. That was one error down. The following code works well, 
except that it doesn't group by week.

contract_query = ( Project.objects
  .values('market__market')
  .filter(department=department_id)
  .filter(datePipeline__year=year)
  .filter(stage="WON")
  .annotate(contracted=Sum('ownProduction'))
  .annotate(week=ExtractWeek('dateContract'))

So, we can't add week to the first values line, since week has yet to be 
defined. So I tried moving it to the line after annotation of week:

contract_query = ( Project.objects
  .filter(department=department_id)
  .filter(datePipeline__year=year)
  .filter(stage="WON")
  .annotate(contracted=Sum('ownProduction'))
  .annotate(week=ExtractWeek('dateContract'))
  .values('market__market','week')

WIth the code above, however, the error comes back: I get a "key error" for 
"contracted". So is that because of week? I tried:

contract_query = ( Project.objects
  .filter(department=department_id)
  .filter(datePipeline__year=year)
  .filter(stage="WON")
  .annotate(contracted=Sum('ownProduction'))
  .annotate(week=ExtractWeek('dateContract'))
  .values('market__market')

No, same "key error" for "contracted". It seems to me that having the 
values() statement after the annotation deletes the annotation- is that 
correct?
And is that intended behavior?

If so, how can I then group by the week function of a datefield?
Or is there something that I got completely wrong?

thanks + cheers, Mikkel


tirsdag den 14. august 2018 kl. 15.28.01 UTC+2 skrev Matthew Pava:
>
> Ah, the error has the answer.  contract_row is a dictionary, so you need 
> to access it as if it were a dictionary.
>
> contract_sum = contract_row['contracted']
>
>  
>
> *From:* django...@googlegroups.com  [mailto:
> django...@googlegroups.com ] *On Behalf Of *Mikkel Kromann
> *Sent:* Monday, August 13, 2018 11:51 PM
> *To:* Django users
> *Subject:* Re: GROUP BY
>
>  
>
>  
>
> Thanks. But strange - exactly same error: 
>
> 'dict' object has no attribute 'contracted'
>
>  
>
> contract_query = (Project.objects.all()
>  .filter(department=department_id)
>  .filter(datePipeline__year=year)
>  .filter(stage="WON")
>  .annotate(week=ExtractWeek('dateContract'
> ))
>  .annotate(contracted=Sum('ownProduction'
> ))
>  .values('week','market__name', 
> 'contracted')
> )
> for contract_row in contract_query:
> contract_sum = contract_row.contracted
>
>  
>
> I am somewhat confused by this ...
>
>  
>
> Mikkel
>
>  
>
>  
>
> mandag den 13. august 2018 kl. 22.24.48 UTC+2 skrev Matthew Pava:
>
> You need to include “ownProduction” in your values list prior to the 
> annotation.
>
>  
>
>  
>
> *From:* django...@googlegroups.com [mailto:django...@googlegroups.com] *On 
> Behalf Of *Mikkel Kromann
> *Sent:* Monday, August 13, 2018 3:22 PM
> *To:* Django users
> *Subject:* GROUP BY
>
>  
>
> I'm trying to sum the field "ownProduction", grouping it by the foreign 
> key "market" (using the market's human readable name, __name from the 
> Market table) and the week number (which is built-in function __year of the 
> date field "dateContract").
>
> However, when I try to read the results of the query in the last line in 
> the code example below., I get the error:
>
>  
>
> "'dict' object has no attribute 'ownProduction'" 
>
>  
>
> So "ownProduction" is to my surprise not a field in the query.
>
> What am I doing wrong?
>
>  
>
> contract_query = (Project.objects.all()
>  .filter(department=department_id)
>  .filter(datePipeline__year=year)
>  .filter(stage="WON&qu

Re: GROUP BY

2018-08-14 Thread Mikkel Kromann
@galan: 
market__market is foreign key relation to the human readable value for 
market, rather than it's id
datePipeline__year is the year of the datefield column called datePipeline
Sorry for not posting the models, that would have avoided the confusion.
But thanks anyways :)

@Matthew:

Yes, you're right. Dictionary solved part of the problem. The following 
formulation (not grouping by week number as is the final intent) works:

contract_query = ( Project.objects
  .values('market__market')
  .filter(department=department_id)
  .filter(datePipeline__year=year)
  .filter(stage="WON")
  .annotate(contracted=Sum('ownProduction'))
  .annotate(week=ExtractWeek('dateContract'))


So, trying to include the week number in my group by is 


tirsdag den 14. august 2018 kl. 15.28.01 UTC+2 skrev Matthew Pava:
>
> Ah, the error has the answer.  contract_row is a dictionary, so you need 
> to access it as if it were a dictionary.
>
> contract_sum = contract_row['contracted']
>
>  
>
> *From:* django...@googlegroups.com  [mailto:
> django...@googlegroups.com ] *On Behalf Of *Mikkel Kromann
> *Sent:* Monday, August 13, 2018 11:51 PM
> *To:* Django users
> *Subject:* Re: GROUP BY
>
>  
>
>  
>
> Thanks. But strange - exactly same error: 
>
> 'dict' object has no attribute 'contracted'
>
>  
>
> contract_query = (Project.objects.all()
>  .filter(department=department_id)
>  .filter(datePipeline__year=year)
>  .filter(stage="WON")
>  .annotate(week=ExtractWeek('dateContract'
> ))
>  .annotate(contracted=Sum('ownProduction'
> ))
>  .values('week','market__name', 
> 'contracted')
> )
> for contract_row in contract_query:
> contract_sum = contract_row.contracted
>
>  
>
> I am somewhat confused by this ...
>
>  
>
> Mikkel
>
>  
>
>  
>
> mandag den 13. august 2018 kl. 22.24.48 UTC+2 skrev Matthew Pava:
>
> You need to include “ownProduction” in your values list prior to the 
> annotation.
>
>  
>
>  
>
> *From:* django...@googlegroups.com [mailto:django...@googlegroups.com] *On 
> Behalf Of *Mikkel Kromann
> *Sent:* Monday, August 13, 2018 3:22 PM
> *To:* Django users
> *Subject:* GROUP BY
>
>  
>
> I'm trying to sum the field "ownProduction", grouping it by the foreign 
> key "market" (using the market's human readable name, __name from the 
> Market table) and the week number (which is built-in function __year of the 
> date field "dateContract").
>
> However, when I try to read the results of the query in the last line in 
> the code example below., I get the error:
>
>  
>
> "'dict' object has no attribute 'ownProduction'" 
>
>  
>
> So "ownProduction" is to my surprise not a field in the query.
>
> What am I doing wrong?
>
>  
>
> contract_query = (Project.objects.all()
>  .filter(department=department_id)
>  .filter(datePipeline__year=year)
>  .filter(stage="WON")
>  .annotate(week=ExtractWeek('dateContract'))
>  .values('week','market__name')
>  .annotate(Sum('ownProduction'))
>  )
> for contract_row in contract_query:
> contract_sum = contract_row.ownProduction
>
>  
>
> It doesn't change anything using
>
>  .annotate(ownProduction = Sum('ownProduction'
> ))
>
>  
>
>  
>
> cheers + thanks, Mikkel
>
> -- 
> 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 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/525b78b7-ada3-4a49-818a-c02fc1bf51b0%40googlegroups.com
>  
> <https://groups.google.com/d/msgid/django-users/525b78b7-ada3-4a49-818a-c02fc1bf51b0%40googlegroups.com?utm_medium=email_source=footer>
> .
> For more options, visit https://groups.google.com/d/optout.
>
> -- 

Re: GROUP BY

2018-08-13 Thread Mikkel Kromann

Thanks. But strange - exactly same error: 

'dict' object has no attribute 'contracted'


contract_query = (Project.objects.all()
 .filter(department=department_id)
 .filter(datePipeline__year=year)
 .filter(stage="WON")
 .annotate(week=ExtractWeek('dateContract'))
 .annotate(contracted=Sum('ownProduction'))
 .values('week','market__name', 'contracted'
)
)
for contract_row in contract_query:
contract_sum = contract_row.contracted

I am somewhat confused by this ...

Mikkel


mandag den 13. august 2018 kl. 22.24.48 UTC+2 skrev Matthew Pava:
>
> You need to include “ownProduction” in your values list prior to the 
> annotation.
>
>  
>
>  
>
> *From:* django...@googlegroups.com  [mailto:
> django...@googlegroups.com ] *On Behalf Of *Mikkel Kromann
> *Sent:* Monday, August 13, 2018 3:22 PM
> *To:* Django users
> *Subject:* GROUP BY
>
>  
>
> I'm trying to sum the field "ownProduction", grouping it by the foreign 
> key "market" (using the market's human readable name, __name from the 
> Market table) and the week number (which is built-in function __year of the 
> date field "dateContract").
>
> However, when I try to read the results of the query in the last line in 
> the code example below., I get the error:
>
>  
>
> "'dict' object has no attribute 'ownProduction'" 
>
>  
>
> So "ownProduction" is to my surprise not a field in the query.
>
> What am I doing wrong?
>
>  
>
> contract_query = (Project.objects.all()
>  .filter(department=department_id)
>  .filter(datePipeline__year=year)
>  .filter(stage="WON")
>  .annotate(week=ExtractWeek('dateContract'))
>  .values('week','market__name')
>  .annotate(Sum('ownProduction'))
>  )
> for contract_row in contract_query:
> contract_sum = contract_row.ownProduction
>
>  
>
> It doesn't change anything using
>
>  .annotate(ownProduction = Sum('ownProduction'
> ))
>
>  
>
>  
>
> cheers + thanks, Mikkel
>
> -- 
> 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 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/525b78b7-ada3-4a49-818a-c02fc1bf51b0%40googlegroups.com
>  
> <https://groups.google.com/d/msgid/django-users/525b78b7-ada3-4a49-818a-c02fc1bf51b0%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/d2748446-4d61-44a4-b435-c77eb4957818%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


GROUP BY

2018-08-13 Thread Mikkel Kromann
I'm trying to sum the field "ownProduction", grouping it by the foreign key 
"market" (using the market's human readable name, __name from the Market 
table) and the week number (which is built-in function __year of the date 
field "dateContract").
However, when I try to read the results of the query in the last line in 
the code example below., I get the error:

"'dict' object has no attribute 'ownProduction'" 

So "ownProduction" is to my surprise not a field in the query.
What am I doing wrong?

contract_query = (Project.objects.all()
 .filter(department=department_id)
 .filter(datePipeline__year=year)
 .filter(stage="WON")
 .annotate(week=ExtractWeek('dateContract'))
 .values('week','market__name')
 .annotate(Sum('ownProduction'))
 )
for contract_row in contract_query:
contract_sum = contract_row.ownProduction

It doesn't change anything using
 .annotate(ownProduction = Sum('ownProduction'))



cheers + thanks, Mikkel

-- 
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/525b78b7-ada3-4a49-818a-c02fc1bf51b0%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: A query with "GROUP BY" and summation of products of two columns

2018-08-04 Thread Mikkel Kromann
Apologies. The code I posted is actually correct and well functioning. 
The reason that the results looked wrong was that the data handled by the 
code was faulty.
In my research, I found another way to do the trick:

contracts = (Project.objects.values('stage')
.annotate(contract_sum=Sum('contractSum'))
.annotate(expected_own_production_sum=Sum(
'id', field='contractSum * probability'))
)

cheers, Mikkel



lørdag den 4. august 2018 kl. 14.11.27 UTC+2 skrev Mikkel Kromann:
>
> Dear Django users.
>
> I'm trying to do the sums of the product of two columns ('contract_sum' 
> and 'probability', decimal fields), grouping by a third column, 'stage' (a 
> choice variable).
> I'm also reporting the grouped sums of one of the single columns 
> ('contract_sum')
> The single column works just fine, but I just can't get it right with the 
> product columns.
> Below is my code so far:
>
> contracts = (Project.objects.values('stage')
> .annotate(contract_sum=Sum('contractSum'))
> .annotate(expected_own_production_sum=F(
> 'contractSum')*F('probability'))
> )
>
> a) When I run the query with the single column query, the results are 
> right.
> b) When I run the query with both selections, not only is the column 
> product, wrong, but the single column sums also become wrong.
> c) When I run the query with only the product columns, the query returns 
> zero for all groups, which is definitely wrong.
>
> Can I do this right without going to raw sql?
>
>
> cheers + thanks, Mikkel
>

-- 
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/a38df7fa-dc7b-4042-886f-4fa7a74f2c45%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


A query with "GROUP BY" and summation of products of two columns

2018-08-04 Thread Mikkel Kromann
Dear Django users.

I'm trying to do the sums of the product of two columns ('contract_sum' and 
'probability', decimal fields), grouping by a third column, 'stage' (a 
choice variable).
I'm also reporting the grouped sums of one of the single columns 
('contract_sum')
The single column works just fine, but I just can't get it right with the 
product columns.
Below is my code so far:

contracts = (Project.objects.values('stage')
.annotate(contract_sum=Sum('contractSum'))
.annotate(expected_own_production_sum=F(
'contractSum')*F('probability'))
)

a) When I run the query with the single column query, the results are right.
b) When I run the query with both selections, not only is the column 
product, wrong, but the single column sums also become wrong.
c) When I run the query with only the product columns, the query returns 
zero for all groups, which is definitely wrong.

Can I do this right without going to raw sql?


cheers + thanks, Mikkel

-- 
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/4a6af6b6-d76e-43f7-8223-23da3ead38da%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Is it possible to construct reversible url names in urls.py using , regex etc

2018-06-25 Thread Mikkel Kromann
Thank you so much for your help, Melvyn.
With your help I managed to the the code running :)
Here it is, if somebody should find it helpful.

cheers, Mikkel

>From somewhere, e.g. models.py
# The list of model names (just add your model names to it)
def GetItemNames():
return [ 'Year', 'Vintage', 'Region', 'Location' ] 

# The generator of paths
def GetItemPaths():
paths = [ ]
for i in GetItemNames():
m = apps.get_model('items', i)
paths.append(path( 'list/'+i+'/' , ItemListView.as_view(
model=m),  name=i+'_list'   ) )
paths.append(path( 'create/'+i+'/',ItemCreateView.as_view(
model=m),name=i+'_create' ) )
paths.append(path( 'update/'+i+'//',   ItemUpdateView.as_view(
model=m),name=i+'_update' ) )
paths.append(path( 'delete/'+i+'//',   ItemDeleteView.as_view(
model=m),name=i+'_delete' ) )

return paths

>From urls.py:
from . models import GetItemPaths
urlpatterns = GetItemPaths() + [
path('/to/some/other/views/'otherview.asView(), name='other_name'),
]




lørdag den 23. juni 2018 kl. 15.08.04 UTC+2 skrev Melvyn Sopacua:
>
> On zaterdag 23 juni 2018 14:30:08 CEST Mikkel Kromann wrote: 
>
> > In models.py: 
> > def GetItemPaths():paths = [ ] 
> > for i in [ 'Model1', 'Model2', 'Model3' ]: 
> > p = path( i + '/list/', ItemListView.as_view(model=i), name=i + 
> > '_list' ) 
> > paths.append(p) 
> > 
> > return paths 
> > 
> > However, there seems to be a problem with trying to pass the model name 
> to 
> > my CBV ItemListView. 
> > Unless I replace the model=i with e.g. model=Model1 I get the following 
> > error: 
> > 
> > 'str' object has no attribute '_default_manager' 
> > 
> > 
> > So it certainly seems that using model=i will not pass the model name. 
> > Is this because the argument for model= expects not a string but an 
> object? 
>
> Yes. You can use import_module from django.functional to pass a dotted 
> path. 
> Or you can use apps.get_model() to get a model class for a app name / 
> model 
> name combo. 
>
> -- 
> Melvyn Sopacua 
>

-- 
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/72b5c5e6-b07d-41b8-a9b5-6a471ffe65cd%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Is it possible to construct reversible url names in urls.py using , regex etc

2018-06-23 Thread Mikkel Kromann
So, I think I have a neat idea for solving my problem, simply make a 
function which returns a list of path() returns.

In urls.py
urlpatterns = GetItemPaths() + [
# other paths
]

In models.py:
def GetItemPaths():paths = [ ]
for i in [ 'Model1', 'Model2', 'Model3' ]:
p = path( i + '/list/', ItemListView.as_view(model=i), name=i + 
'_list' )
paths.append(p) 

return paths

However, there seems to be a problem with trying to pass the model name to 
my CBV ItemListView.
Unless I replace the model=i with e.g. model=Model1 I get the following 
error:

'str' object has no attribute '_default_manager'


So it certainly seems that using model=i will not pass the model name.
Is this because the argument for model= expects not a string but an object?


thanks, Mikkel

torsdag den 21. juni 2018 kl. 10.19.08 UTC+2 skrev Mikkel Kromann:
>
> I have a lot of models (say 30 or 40) which are so similar, that I have 
> handled them using slightly modified class based views.
>
> In urls.py:
> urlpatterns = [
> path('list//',ItemListView.as_view()),
> path('create//',  ItemCreateView.as_view()),
> path('update//',  ItemUpdateView.as_view()),
> path('delete//',  ItemDeleteView.as_view()),
> ]
>
> However, I'd really like to give all my urls names so that they can be 
> easily reversed (e.g. success links).
> urlpatterns = [
> path('list//',ItemListView.as_view(),  name
> =mName+'_list'),
> ]
>
> From what I can see, my model name mName is passed only to the view and 
> apparently not to the name constructor inside urls.py
> Also, while I do not entirely understand the reverse naming process, I 
> sense that it might not be too easy to reverse the url name if it is not 
> spelled out directly.
>
> Are there any options for handling this in urls.py?
> Or should I make a filter that will transform the model name and operation 
> name to an url and accept that I have to code url logic outside urls.py
> Or could I reprogram the path() function to make this possible?
> Or should I violate DRY and simply write 4 path lines for each of my 40 
> models?
>
>
> cheers + thanks, Mikkel
>

-- 
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/e44a11ea-3115-4414-9af7-c1889c4f2f5c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Is it possible to construct reversible url names in urls.py using , regex etc

2018-06-21 Thread Mikkel Kromann
I have a lot of models (say 30 or 40) which are so similar, that I have 
handled them using slightly modified class based views.

In urls.py:
urlpatterns = [
path('list//',ItemListView.as_view()),
path('create//',  ItemCreateView.as_view()),
path('update//',  ItemUpdateView.as_view()),
path('delete//',  ItemDeleteView.as_view()),
]

However, I'd really like to give all my urls names so that they can be 
easily reversed (e.g. success links).
urlpatterns = [
path('list//',ItemListView.as_view(),  name=
mName+'_list'),
]

>From what I can see, my model name mName is passed only to the view and 
apparently not to the name constructor inside urls.py
Also, while I do not entirely understand the reverse naming process, I 
sense that it might not be too easy to reverse the url name if it is not 
spelled out directly.

Are there any options for handling this in urls.py?
Or should I make a filter that will transform the model name and operation 
name to an url and accept that I have to code url logic outside urls.py
Or could I reprogram the path() function to make this possible?
Or should I violate DRY and simply write 4 path lines for each of my 40 
models?


cheers + thanks, Mikkel

-- 
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/9cc50a2b-b613-4427-a8e4-101f9bf394d9%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Help with context_processor

2018-06-20 Thread Mikkel Kromann
Thank you both. 
Clearly, I also missed some important points about dictionaries.
Mistakes are good teachers, but it surely helps having competent people on 
a mailing list :)

I'll sum up the simple solution to context processors that worked for me, 
if somebody would find it useful some day.

Basically in any of your .py files you can put a definition taking 
'request' as argument and returning a dictionary.
Recommended file is /contextprocessor.py (my  is named items) 
def GetItemDictionary(request):
return {
 'itemDictionary': [
{'name': 'region', 'readable': 'Region', 'urlname': 
'region_list' }, 
{'name': 'location', 'readable': 'Location', 'urlname': 
'location_list' },
]
}



This will allow you to iterate over the dictionary 'itemDictionary' in all 
your templates, e.g. in template.html
{% for item in itemDictionary %}
{{ item.readable }}
{% endfor %}


To ensure that Django passes the itemDictionary dict to the template, you 
will need to register it in settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
BASE_DIR + '/templates/',
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'items.contextprocessor.GetItemDictionary',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

And that's about it. Thanks again to Matthew and Andréas for helping me out 
here.


cheers, Mikkel



onsdag den 20. juni 2018 kl. 20.34.50 UTC+2 skrev Andréas Kühne:
>
> Hi Matthew,
>
> That's true, You would then be able to get the dictionary values once 
> more. Hadn't thought of that. Good point! Thanks :-)
>
> Regards,
>
> Andréas
>
> 2018-06-20 15:55 GMT+02:00 Matthew Pava >:
>
>> Well, you can access a dictionary like a list using these:
>>
>> items.keys(), template:
>>
>> for k in items.keys
>>
>>  
>>
>> items.values(), template:
>>
>> for v in items.values
>>
>>  
>>
>> items.items(), template:
>>
>> for k, v in items.items
>>
>>  
>>
>>  
>>
>> *From:* django...@googlegroups.com  [mailto:
>> django...@googlegroups.com ] *On Behalf Of *Andréas Kühne
>> *Sent:* Wednesday, June 20, 2018 2:28 AM
>> *To:* django...@googlegroups.com 
>> *Subject:* Re: Help with context_processor
>>
>>  
>>
>> Hi Mikkel,
>>
>>  
>>
>> No - you can't loop over a dictionary that way. However - You don't need 
>> to resort to doing that either. If you want to loop over something use a 
>> list. Like this:
>>
>>  
>>
>> return {
>>
>>   'items': [
>>
>>{'name': 'year', 'readable': 'Year', 'urlname': 'year_list' },
>>
>>   {'name': 'region', 'readable': 'Region', 'urlname': 
>> 'region_list' },
>>
>>   {'name': 'location', 'readable': 'Location', 'urlname': 
>> 'location_list' }
>>
>>   ]
>>
>> }
>>
>>  
>>
>> Then in the template:
>>
>> {% for item in Items %}
>> {{item.readable}}
>> {% endfor %}
>>
>>
>> Regards,
>>
>>  
>>
>> Andréas
>>
>>  
>>
>> 2018-06-19 20:59 GMT+02:00 Mikkel Kromann > >:
>>
>> Thank you so much Andreas.
>>
>> This is very helpful.
>>
>>  
>>
>> I wasn't able to figure that from the documentation (not sure who to 
>> blame, though ;)
>>
>> So I relied on various stackoverflow posts, which were quite confusing to 
>> say the least.
>>
>>  
>>
>> Now, is there anyway I can loop over the items in the dictionary?
>>
>> In the end, I will probably query my dictionary from another model of 
>> mine.
>>
>>  
>>
>> Would the { for item in items } still hold? 
>>
>>  
>>
>>  
>>
>> cheers, Mikkel
>>
>>  
>>
>> mandag den 18. juni 2018 kl. 22.55.29 UTC+2 skrev Andréas Kühne:
>>
>> First of all - that is not how a context processor works.
>>
>>  
>>
>> You are confusing template tags and context processors. A template tag is 
>> one of the following:
>>
>> https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/
>>
>>  
>>
>> It must then be registered and then included in

Re: Help with context_processor

2018-06-19 Thread Mikkel Kromann
Thank you so much Andreas.
This is very helpful.

I wasn't able to figure that from the documentation (not sure who to blame, 
though ;)
So I relied on various stackoverflow posts, which were quite confusing to 
say the least.

Now, is there anyway I can loop over the items in the dictionary?
In the end, I will probably query my dictionary from another model of mine.

Would the { for item in items } still hold? 


cheers, Mikkel

mandag den 18. juni 2018 kl. 22.55.29 UTC+2 skrev Andréas Kühne:
>
> First of all - that is not how a context processor works.
>
> You are confusing template tags and context processors. A template tag is 
> one of the following:
> https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/
>
> It must then be registered and then included in your template. So then you 
> should put it in the templatetags module and load it into your template. It 
> should NOT be added to the OPTIONS dictionary.
>
> However, a context processor is called EVERYTIME a request is handled and 
> returns it's content to the template - WITHOUT the need of calling anything 
> OR adding it to your template. So in your case you would need to move the 
> context processor from the templatetags module, not load it with register, 
> and also load use {% include %} in your template. And finally don't call it.
>
> What happens with the context processor is that it autmatically gets 
> called and the dictionary result is added to the context of the template.
>
> So your context processor should look like this:
> def GetItemDictionary(request):
> # For now pass a hardcoded dictionary - replace with query later
> return {
> 'year': {'name': 'year', 'readable': 'Year', 'urlname': 
> 'year_list' },
> 'region': {'name': 'region', 'readable': 'Region', 'urlname': 
> 'region_list' }, 
> 'location': {'name': 'location', 'readable': 'Location', 'urlname'
> : 'location_list' },
> }
>
> Without registering it or anything.
>
> This way you will be able to get the information in your template like 
> this:
> {% block sidebar %}
> 
> {{year.readable}}
> {{region.readable}}
> {{location.readable}}
> 
> {% endblock %}
>
> The reason for needing to add year, region and location, is because that 
> is the way you are creating the dictionary in your context processor.
>
> Best regards,
>
> Andréas
>
> 2018-06-18 21:16 GMT+02:00 Mikkel Kromann  >:
>
>> Hi.
>>
>> Once again thanks for all your invaluable advice to me so far. Now, I'm 
>> battling context_processors.
>> I really struggle to find a good example that can help me understand how 
>> to use them.
>> They seem quite helpful to a lot of stuff I plan to do.
>>
>> I think I got the configuration in settings.py and @register right as my tag 
>> is accepted as registered.
>> What baffles me is whether to include "request" as argument to my context 
>> processor GetItemDictionary() 
>> The error I get now (without declaring request as an argument) is 
>>
>> "GetItemDictionary() takes 0 positional arguments but 1 was given"
>>
>>
>> With request as argumetn to GetItemDictionary(request) I get this error:
>>
>> 'GetItemDictionary' did not receive value(s) for the argument(s): 'request'
>>
>>
>> Should I pass request to my GetItemDictionary somewhere in my view, or is 
>> that done automagically by the template?
>> I realise that I've probably done something wrong elsewhere, but I'm at a 
>> loss to guess where ...
>> I suspect that the @register.simple_tag stuff I do may be the culprit as 
>> the tag may not be simple.
>>
>>
>> thanks, Mikkel
>>
>> From project/app/templatetags/items_extra.py
>> from django import template
>> register = template.Library() 
>>
>> @register.simple_tag()
>> def GetItemDictionary():
>> # For now pass a hardcoded dictionary - replace with query later
>> return {
>> 'year': {'name': 'year', 'readable': 'Year', 'urlname': 
>> 'year_list' },
>> 'region': {'name': 'region', 'readable': 'Region', 'urlname': 
>> 'region_list' }, 
>> 'location': {'name': 'location', 'readable': 'Location', 
>> 'urlname': 'location_list' },
>> }
>>
>>
>> From my settings.py
>> TEMPLATES = [
>> {
>> 'BACKEND': 'django.template.backends.django.DjangoTemplates',
>> 'DIRS': [
>> BASE_DIR + '/templates/',
>> ],
>> 'APP_DIRS': True,
>> 'OPTIONS': {
>> 'context_processors': [
>>  

Help with context_processor

2018-06-18 Thread Mikkel Kromann
Hi.

Once again thanks for all your invaluable advice to me so far. Now, I'm 
battling context_processors.
I really struggle to find a good example that can help me understand how to 
use them.
They seem quite helpful to a lot of stuff I plan to do.

I think I got the configuration in settings.py and @register right as my tag is 
accepted as registered.
What baffles me is whether to include "request" as argument to my context 
processor GetItemDictionary() 
The error I get now (without declaring request as an argument) is 

"GetItemDictionary() takes 0 positional arguments but 1 was given"


With request as argumetn to GetItemDictionary(request) I get this error:

'GetItemDictionary' did not receive value(s) for the argument(s): 'request'


Should I pass request to my GetItemDictionary somewhere in my view, or is 
that done automagically by the template?
I realise that I've probably done something wrong elsewhere, but I'm at a 
loss to guess where ...
I suspect that the @register.simple_tag stuff I do may be the culprit as 
the tag may not be simple.


thanks, Mikkel

>From project/app/templatetags/items_extra.py
from django import template
register = template.Library() 

@register.simple_tag()
def GetItemDictionary():
# For now pass a hardcoded dictionary - replace with query later
return {
'year': {'name': 'year', 'readable': 'Year', 'urlname': 'year_list' 
},
'region': {'name': 'region', 'readable': 'Region', 'urlname': 
'region_list' }, 
'location': {'name': 'location', 'readable': 'Location', 'urlname': 
'location_list' },
}


>From my settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
BASE_DIR + '/templates/',
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'items.templatetags.items_extra.GetItemDictionary',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
'libraries':{
'items_extra': 'items.templatetags.items_extra',
},
},
},
]


>From my template:
{% load items_extra  %}
{% GetItemDictionary as Items %}
{% block sidebar %}

{% for item in Items %}
item.readable
{% endfor %}

I: {{ Items }}
{% endblock %}





-- 
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/54694b80-86ae-4934-913f-7a03e215463e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Nested for loops in templates

2018-06-15 Thread Mikkel Kromann
Thanks Matthew. 

The field_list is a list strings containnig the field names hardcoded in 
Models.py by the programmer.
I.e. the field names that shoud appear in the Class Based Views.
So, perhaps this answers my question to Vijay - that the row in the 
iteration is in fact the Model object.
And that I can get the contents of the field specified by the contents of 
the "field" string using getattr()

And since (unless the programmer entered wrong values for the field names, 
I can use a simplified version of the filter, e.g.:


def getattribute(value, arg): 
"""Gets an attribute of an object dynamically from a string name""" 
if hasattr(value, str(arg)): 
return getattr(value, arg)
else
return ""


thanks, Mikkel

torsdag den 14. juni 2018 kl. 00.19.24 UTC+2 skrev Matthew Pava:
>
> field is a string – a name of a field, field is not actually an attribute 
> of row.  You’ll need a template tag to get the attribute named field from 
> row.
>
> This StackOverflow question may help you:
>
>
> https://stackoverflow.com/questions/844746/performing-a-getattr-style-lookup-in-a-django-template?utm_medium=organic_source=google_rich_qa_campaign=google_rich_qa
>
>  
>
>  
>
> *From:* django...@googlegroups.com  [mailto:
> django...@googlegroups.com ] *On Behalf Of *Mikkel Kromann
> *Sent:* Wednesday, June 13, 2018 3:54 PM
> *To:* Django users
> *Subject:* Nested for loops in templates
>
>  
>
> Dear Django users.
>
>  
>
> Thanks to the good advice of many people on this list, I've managed to 
> create some nice generic class based views that work simultaneously with 
> many models.
>
> The models may differ from each other with regards to the number of 
> columns in their data tables as well as the naming of the columns.
>
> In order to use the same ListView template for many models, I will need to 
> iterate not only over the rows of the queries, but also the columns.
>
>  
>
> I managed to pass a field_list into the context_data - it works as it 
> shows nicely in the table headers.
>
> However, when I iterate over the rows of the query result table, I'm not 
> able to pinpoint the fields of the data row using the field iterator. 
>
>  
>
> My template.html is:
>
> 
> 
> {% for fields in field_list %}
> {{field}}
> {% endfor %}
> {% for row in row_list %}
> 
> {% for field in field_list %}
> {{row.field}}
> {% endfor %}
> {% endfor %}
> 
>
>
> Besides trying with {{row.field}}, I've tried with {{row}}.{{field}}, as 
> well as {{ row.{{field}} }} (yeah, long shot ...)
>
>  
>
> Any ideas, or should I try to create an entirely different data structure 
> in my view, which can be parsed more easily by Django templates?
>
>  
>
>  
>
> cheers + thanks, Mikkel
>
> -- 
> 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 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/c9e29d66-f93c-4fc4-ae9f-dbeae93a2e45%40googlegroups.com
>  
> <https://groups.google.com/d/msgid/django-users/c9e29d66-f93c-4fc4-ae9f-dbeae93a2e45%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/2bf96986-c977-49bb-b71a-6d789a1c996b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Nested for loops in templates

2018-06-15 Thread Mikkel Kromann
Thank you Vijay.

That link seems to be a feasible path for me to take (reproduced below).

Perhaps you or others can help me with an additional question (I am a bit 
new to both Python and Django), that I'm struggling with:
Which type of data structure is Django iterating over in the templates 
(i.e. the {% for row in row_list %} in my code example above).
Is "row" the Model object or is it some sort of dictionary / array data 
structure?
I've been browsing through the Classy CBV ListView pages to try to get hold 
of that, but I was not able to clarify this myself.

thank you, Mikkel


Create a template tag like this (in yourproject/templatetags):
@register.filter 
def keyvalue(dict, key): 
return dict[key] 


Usage in template:

{{dictionary|keyvalue:key_variable}} 




torsdag den 14. juni 2018 kl. 00.17.26 UTC+2 skrev Vijay Khemlani:
>
> As far as I know you can't do it directly in the templating system
>
> Yo could write a template tag as described here
>
>
> https://stackoverflow.com/questions/2894365/use-variable-as-dictionary-key-in-django-template/10700142#10700142
>
> or use a different data structure, for example each row as a list of the 
> values in the order that they should appear
>
> On Wed, Jun 13, 2018 at 4:54 PM Mikkel Kromann  > wrote:
>
>> Dear Django users.
>>
>> Thanks to the good advice of many people on this list, I've managed to 
>> create some nice generic class based views that work simultaneously with 
>> many models.
>> The models may differ from each other with regards to the number of 
>> columns in their data tables as well as the naming of the columns.
>> In order to use the same ListView template for many models, I will need 
>> to iterate not only over the rows of the queries, but also the columns.
>>
>> I managed to pass a field_list into the context_data - it works as it 
>> shows nicely in the table headers.
>> However, when I iterate over the rows of the query result table, I'm not 
>> able to pinpoint the fields of the data row using the field iterator. 
>>
>> My template.html is:
>> 
>> 
>> {% for fields in field_list %}
>> {{field}}
>> {% endfor %}
>> {% for row in row_list %}
>> 
>> {% for field in field_list %}
>> {{row.field}}
>> {% endfor %}
>> {% endfor %}
>> 
>>
>>
>> Besides trying with {{row.field}}, I've tried with {{row}}.{{field}}, as 
>> well as {{ row.{{field}} }} (yeah, long shot ...)
>>
>> Any ideas, or should I try to create an entirely different data structure 
>> in my view, which can be parsed more easily by Django templates?
>>
>>
>> cheers + thanks, Mikkel
>>
>> -- 
>> 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/c9e29d66-f93c-4fc4-ae9f-dbeae93a2e45%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/django-users/c9e29d66-f93c-4fc4-ae9f-dbeae93a2e45%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/6d443c64-0c68-412b-9eb9-0a5640aab37d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Nested for loops in templates

2018-06-13 Thread Mikkel Kromann
Dear Django users.

Thanks to the good advice of many people on this list, I've managed to 
create some nice generic class based views that work simultaneously with 
many models.
The models may differ from each other with regards to the number of columns 
in their data tables as well as the naming of the columns.
In order to use the same ListView template for many models, I will need to 
iterate not only over the rows of the queries, but also the columns.

I managed to pass a field_list into the context_data - it works as it shows 
nicely in the table headers.
However, when I iterate over the rows of the query result table, I'm not 
able to pinpoint the fields of the data row using the field iterator. 

My template.html is:


{% for fields in field_list %}
{{field}}
{% endfor %}
{% for row in row_list %}

{% for field in field_list %}
{{row.field}}
{% endfor %}
{% endfor %}



Besides trying with {{row.field}}, I've tried with {{row}}.{{field}}, as 
well as {{ row.{{field}} }} (yeah, long shot ...)

Any ideas, or should I try to create an entirely different data structure 
in my view, which can be parsed more easily by Django templates?


cheers + thanks, Mikkel

-- 
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/c9e29d66-f93c-4fc4-ae9f-dbeae93a2e45%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Accessing the model attribute of UpdateView & friends

2018-06-07 Thread Mikkel Kromann
Thanks Daniel.

I actually tried to implement it in the __init__ but it didn't work.
I'll read through your explanation more carefully - I'm sure I could use a 
bit better understanding on the ways of Python and Django :)
Again, thank you for your very useful replies

cheers, Mikkel

torsdag den 7. juni 2018 kl. 00.24.03 UTC+2 skrev Daniel Germano Travieso:
>
> I'm glad it helped.
>
> As you can see, the dispatch method I wrote does override the default 
> definition, but I return the super() dispatch method, so on the default 
> flow the end result is the same (the validity of the request would be 
> checked anyway, only after you set your class atribute). 
> To avoid this work that would be invalid if there is an error on the 
> request you could write a dispatch method that first gets the result of the 
> super (). dispatch, check if it was ok then do the work you need and return 
> the result of the dispatch after that.
>
> And you could as well use the __init__ method for the class, but I'm not 
> sure the .as_view() function works as a constructor like that, I would need 
> to confirm the documentation, but there were some implementations that I 
> worked with that customized the __init__ of the view class so it would 
> probably work. A more philosophical question is if it is the proper 
> location for that work to be done, as the __init__ method could be called 
> even if the request is invalid, making your code try to do something weird.
>
> Anyway, good luck on your project!
>
> On Wed, Jun 6, 2018, 14:51 Mikkel Kromann  > wrote:
>
>> Thanks Daniel. 
>>
>> Both your proposed solutions worked very well.
>> For now, I don't have other information stuffed into my model 
>> definitions, so the urls.py approach could do.
>> However, if I decide to put more information into models.py, the def 
>> dispatch() approach could be useful.
>>
>> One question though: 
>> Do I understand correctly, that your version of def dispatch() overwrites 
>> the Django dispatch method from UpdateView.
>> As far as I can see, it checks the validity of the request method.
>> Could I use def __init__ instead of def dispatch
>>
>>
>> thanks + cheers, Mikkel
>>
>>
>> From 
>> https://ccbv.co.uk/projects/Django/2.0/django.views.generic.edit/UpdateView/
>> def dispatch(self, request, *args, **kwargs):
>> # Try to dispatch to the right method; if a method doesn't exist,
>> # defer to the error handler. Also defer to the error handler if the
>> # request method isn't on the approved list.
>> if request.method.lower() in self.http_method_names:
>> handler = getattr(self, request.method.lower(), self.
>> http_method_not_allowed)
>> else:
>> handler = self.http_method_not_allowed
>> return handler(request, *args, **kwargs)
>>
>>
>>
>>
>> onsdag den 6. juni 2018 kl. 16.12.06 UTC+2 skrev Daniel Germano Travieso:
>>
>>> Ok! I think I see your problem.
>>>
>>> It is a deeper understanding of python classes that may be the problem.
>>> You see, "model" and "self" are class atributes of the python class that 
>>> houses your class based view (as every class in django is first a python 
>>> class).
>>>
>>> So, if you try to access the attribute "model" of the class, or the 
>>> attribute "self", a attribute that houses the instance of the class, on 
>>> it's class attributes definitions you will have problems, as the python 
>>> interpreter only load these modules lazyly, not actually going through on 
>>> finding the value for the attribute you referenced.
>>>
>>> One solution is to have that value (for the attribute "field" as a 
>>> @property that is a function that then the python interpreter will go 
>>> through and execute the reference lookup.
>>>
>>> Another solution is to set that value to be initially None, and set the 
>>> value for the fields on the dispatch method of the view, something like 
>>> class ItemUpdateView(UpdateView):
>>>   template_name="foo.html"
>>>   fields = None
>>>  
>>>   def dispatch (self, request, *args, **kwargs):
>>> self.fields = self.model.fields
>>> return super(ItemUpdateView, self).dispatch(request, *args, **kwargs)
>>>
>>>
>>>
>>> But as of my understanding of your problem, you are trying to just 
>>> customize which form fields to display to the user based on which model the 
>>> user is updating, so you could just 

Re: Accessing the model attribute of UpdateView & friends

2018-06-06 Thread Mikkel Kromann
Thanks Daniel. 

Both your proposed solutions worked very well.
For now, I don't have other information stuffed into my model definitions, 
so the urls.py approach could do.
However, if I decide to put more information into models.py, the def 
dispatch() approach could be useful.

One question though: 
Do I understand correctly, that your version of def dispatch() overwrites 
the Django dispatch method from UpdateView.
As far as I can see, it checks the validity of the request method.
Could I use def __init__ instead of def dispatch


thanks + cheers, Mikkel


From 
https://ccbv.co.uk/projects/Django/2.0/django.views.generic.edit/UpdateView/
def dispatch(self, request, *args, **kwargs):
# Try to dispatch to the right method; if a method doesn't exist,
# defer to the error handler. Also defer to the error handler if the
# request method isn't on the approved list.
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.
http_method_not_allowed)
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)




onsdag den 6. juni 2018 kl. 16.12.06 UTC+2 skrev Daniel Germano Travieso:
>
> Ok! I think I see your problem.
>
> It is a deeper understanding of python classes that may be the problem.
> You see, "model" and "self" are class atributes of the python class that 
> houses your class based view (as every class in django is first a python 
> class).
>
> So, if you try to access the attribute "model" of the class, or the 
> attribute "self", a attribute that houses the instance of the class, on 
> it's class attributes definitions you will have problems, as the python 
> interpreter only load these modules lazyly, not actually going through on 
> finding the value for the attribute you referenced.
>
> One solution is to have that value (for the attribute "field" as a 
> @property that is a function that then the python interpreter will go 
> through and execute the reference lookup.
>
> Another solution is to set that value to be initially None, and set the 
> value for the fields on the dispatch method of the view, something like 
> class ItemUpdateView(UpdateView):
>   template_name="foo.html"
>   fields = None
>  
>   def dispatch (self, request, *args, **kwargs):
> self.fields = self.model.fields
> return super(ItemUpdateView, self).dispatch(request, *args, **kwargs)
>
>
>
> But as of my understanding of your problem, you are trying to just 
> customize which form fields to display to the user based on which model the 
> user is updating, so you could just specify the form_class attribute on the 
> path (just as you did with the model).
>
> Hope it helps!
>
>
> On Wed, Jun 6, 2018, 10:36 Mikkel Kromann  > wrote:
>
>> Hello Daniel.
>>
>> Thank you for your reply. Perhaps I was not explicit enough in describing 
>> my problem - it is far simpler than your solution indicates.
>> In my model definitions, I already have a list of the fields to be 
>> represented in the form of UpdateView - it is an attribute in the form of a 
>> simple array called "fields".
>> I don't want UpdateView to make a form for all columns of the model's 
>> data table, just the fields from my custom array in the Model objects.
>>
>> My problem is simply: How to access my custom attribute "field" in the 
>> Model attribute passed to the Class Based View function.
>> As described, I get compilation errors, complaining that "model" and 
>> "self" are names not defined.
>> From the documentation (and my so far not too great Python understandign) 
>> it is not clear to me whether "Model" is simply the name of the model, or 
>> if it is the entire Model object instance.
>>
>>
>> thanks again, Mikkel
>>
>>
>> onsdag den 6. juni 2018 kl. 15.01.05 UTC+2 skrev Daniel Germano Travieso:
>>>
>>> Hello!
>>>
>>> As you see on the documentation (
>>> https://docs.djangoproject.com/en/2.0/topics/class-based-views/) for 
>>> the class based views, any arguments you pass to the class based view 
>>> .as_view() method will override attributes of the class based view, so if 
>>> you set MyCView.as_view(model=Foo) is the same as setting class MyCView: 
>>> model=Foo directly.
>>>
>>> Now to access the field names of the Model, you used to be able to call 
>>> a .get_field_names() or something like that but that is depreciated since 
>>> 1.10. Now to do that you should use the Model._meta to get_fields(). Check 
>>> the documentation for the Mod

Re: Accessing the model attribute of UpdateView & friends

2018-06-06 Thread Mikkel Kromann
Hello Daniel.

Thank you for your reply. Perhaps I was not explicit enough in describing 
my problem - it is far simpler than your solution indicates.
In my model definitions, I already have a list of the fields to be 
represented in the form of UpdateView - it is an attribute in the form of a 
simple array called "fields".
I don't want UpdateView to make a form for all columns of the model's data 
table, just the fields from my custom array in the Model objects.

My problem is simply: How to access my custom attribute "field" in the 
Model attribute passed to the Class Based View function.
As described, I get compilation errors, complaining that "model" and "self" 
are names not defined.
>From the documentation (and my so far not too great Python understandign) 
it is not clear to me whether "Model" is simply the name of the model, or 
if it is the entire Model object instance.


thanks again, Mikkel


onsdag den 6. juni 2018 kl. 15.01.05 UTC+2 skrev Daniel Germano Travieso:
>
> Hello!
>
> As you see on the documentation (
> https://docs.djangoproject.com/en/2.0/topics/class-based-views/) for the 
> class based views, any arguments you pass to the class based view 
> .as_view() method will override attributes of the class based view, so if 
> you set MyCView.as_view(model=Foo) is the same as setting class MyCView: 
> model=Foo directly.
>
> Now to access the field names of the Model, you used to be able to call a 
> .get_field_names() or something like that but that is depreciated since 
> 1.10. Now to do that you should use the Model._meta to get_fields(). Check 
> the documentation for the Model._meta to check its full potential.
>
> Hope it helps!
>
> On Wed, Jun 6, 2018, 07:33 Mikkel Kromann  > wrote:
>
>> Thanks for the advice, Andréas.
>> But the response is the same:
>>
>>   File "C:\Users\ ... xxx   ... \items\views.py", line 7, in 
>> ItemUpdateView
>> fields = self.model.fields
>> NameError: name 'self' is not defined
>>
>>
>>
>> As far as I understood, model is an attribute, not a method (though I'm 
>> new to Python and Django, so I'm unsure about this).
>> Does attribute/method make a difference in this case?
>>
>> cheers, Mikkel
>> tirsdag den 5. juni 2018 kl. 22.10.31 UTC+2 skrev Andréas Kühne:
>>>
>>> Hi,
>>>
>>> Have you tried self.model? It should be present in all methods in the 
>>> class?
>>>
>>> Regards,
>>>
>>> Andréas
>>>
>>> 2018-06-05 21:56 GMT+02:00 Mikkel Kromann :
>>>
>>>> Dear Django-users.
>>>>
>>>> I'm slowly working towards a Django "data-warehouse" framework, where I 
>>>> can easily add a lot of models (each containing a table with data), while 
>>>> sticking to only few reusable views.
>>>>
>>>> I've realised that in urls.py, it is possible to specify the model on 
>>>> which the UpdateView is going to do its magic.
>>>> This allows me to use a generic UpdateView (which I called 
>>>> ItemUpdateView) and template for all my models, which will save me a ton 
>>>> of 
>>>> almost identical lines of code.
>>>>
>>>> However, in the generic ItemUpdateView, I of course need to specify the 
>>>> fields of the specific model chosen in urls.py.
>>>> As I ideally only want a few generic views (i.e. ItemCreateView, 
>>>> ItemUpdateView, ItemDeleteView and ItemListView), I've chosen to place the 
>>>> field array in my model definition, hoping to be able to access it from my 
>>>> generic Class Based Views
>>>>
>>>> But how do I access the model attribute in (Item)UpdateView
>>>>
>>>>
>>>> thanks, Mikkel
>>>>
>>>> From views.py
>>>> from django.views.generic import CreateView, ListView, UpdateView, 
>>>> DeleteView
>>>>
>>>> class ItemUpdateView(UpdateView):
>>>> template_name = "item_form.html"
>>>> # How do I access the model attribute of ItemUpdateView as given in 
>>>> urls.py?
>>>> # This line below returns the error "NameError: name 'model' not 
>>>> defined"
>>>> fields = model.fields
>>>>
>>>> From urls.py
>>>> from django.urls import path
>>>> from . views import ItemUpdate
>>>> from . models import Region, Location
>>>>
>>>> # Awesome! I can specify the model to be used by ItemUpdateView
>>

Re: Accessing the model attribute of UpdateView & friends

2018-06-06 Thread Mikkel Kromann
Thanks for the advice, Andréas.
But the response is the same:

  File "C:\Users\ ... xxx   ... \items\views.py", line 7, in 
ItemUpdateView
fields = self.model.fields
NameError: name 'self' is not defined



As far as I understood, model is an attribute, not a method (though I'm new 
to Python and Django, so I'm unsure about this).
Does attribute/method make a difference in this case?

cheers, Mikkel
tirsdag den 5. juni 2018 kl. 22.10.31 UTC+2 skrev Andréas Kühne:
>
> Hi,
>
> Have you tried self.model? It should be present in all methods in the 
> class?
>
> Regards,
>
> Andréas
>
> 2018-06-05 21:56 GMT+02:00 Mikkel Kromann  >:
>
>> Dear Django-users.
>>
>> I'm slowly working towards a Django "data-warehouse" framework, where I 
>> can easily add a lot of models (each containing a table with data), while 
>> sticking to only few reusable views.
>>
>> I've realised that in urls.py, it is possible to specify the model on 
>> which the UpdateView is going to do its magic.
>> This allows me to use a generic UpdateView (which I called 
>> ItemUpdateView) and template for all my models, which will save me a ton of 
>> almost identical lines of code.
>>
>> However, in the generic ItemUpdateView, I of course need to specify the 
>> fields of the specific model chosen in urls.py.
>> As I ideally only want a few generic views (i.e. ItemCreateView, 
>> ItemUpdateView, ItemDeleteView and ItemListView), I've chosen to place the 
>> field array in my model definition, hoping to be able to access it from my 
>> generic Class Based Views
>>
>> But how do I access the model attribute in (Item)UpdateView
>>
>>
>> thanks, Mikkel
>>
>> From views.py
>> from django.views.generic import CreateView, ListView, UpdateView, 
>> DeleteView
>>
>> class ItemUpdateView(UpdateView):
>> template_name = "item_form.html"
>> # How do I access the model attribute of ItemUpdateView as given in 
>> urls.py?
>> # This line below returns the error "NameError: name 'model' not defined"
>> fields = model.fields
>>
>> From urls.py
>> from django.urls import path
>> from . views import ItemUpdate
>> from . models import Region, Location
>>
>> # Awesome! I can specify the model to be used by ItemUpdateView
>> urlpatterns = [
>> path('update/region/',ItemUpdateView.as_view(model=Region), 
>> name='region_update'),
>> path('update/location/',  ItemUpdateView.as_view(model=Location), 
>>   name='location_update'),
>> ] 
>>
>>
>>
>> From models.py (Region and Location are only two of my tables, I'd like 
>> to have say 20 or 30 models 
>> from django.db import models
>>
>> # Abstract class for our items including common methods, data and 
>> definitions
>> class ItemModel(models.Model):
>>
>> fields = [ 'label', 'short', 'descr' ]
>> label   = models.CharField(max_length=10)
>> short   = models.CharField(max_length=15)
>> descr   = models.CharField(max_length=40)
>>
>> def __str__(self):
>> return self.short
>>
>> class Meta:
>> abstract = True
>>
>> class Region(ItemModel):
>> fields  = [ 'label', 'short', 'descr' ]
>>
>> class Location(ItemModel):
>> fields  = [ 'label', 'short', 'descr', 'region' ]
>> region  = models.ForeignKey(Region, on_delete=models.CASCADE)
>>
>> class Plant(ItemModel):
>> fields  = [ 'label', 'short', 'descr', 'location', 'capex', 'opex', 
>> 'capacity' ]
>> location= models.ForeignKey(Location, on_delete=models.CASCADE)
>> capex   = models.DecimalField(decimal_places=3, max_digits=8)
>> opex= models.DecimalField(decimal_places=3, max_digits=8)
>> capacity= models.DecimalField(decimal_places=3, max_digits=8)
>>
>>
>> -- 
>> 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/ec4634e5-2279-49a7-9045-21712de87584%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/django-users/ec4634e5-2279-49a7-9045-21712de87584%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/95db9cca-58ca-4460-ae39-9150bb199bff%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Accessing the model attribute of UpdateView & friends

2018-06-05 Thread Mikkel Kromann
Dear Django-users.

I'm slowly working towards a Django "data-warehouse" framework, where I can 
easily add a lot of models (each containing a table with data), while 
sticking to only few reusable views.

I've realised that in urls.py, it is possible to specify the model on which 
the UpdateView is going to do its magic.
This allows me to use a generic UpdateView (which I called ItemUpdateView) 
and template for all my models, which will save me a ton of almost 
identical lines of code.

However, in the generic ItemUpdateView, I of course need to specify the 
fields of the specific model chosen in urls.py.
As I ideally only want a few generic views (i.e. ItemCreateView, 
ItemUpdateView, ItemDeleteView and ItemListView), I've chosen to place the 
field array in my model definition, hoping to be able to access it from my 
generic Class Based Views

But how do I access the model attribute in (Item)UpdateView


thanks, Mikkel

>From views.py
from django.views.generic import CreateView, ListView, UpdateView, 
DeleteView

class ItemUpdateView(UpdateView):
template_name = "item_form.html"
# How do I access the model attribute of ItemUpdateView as given in urls.py?
# This line below returns the error "NameError: name 'model' not defined"
fields = model.fields

>From urls.py
from django.urls import path
from . views import ItemUpdate
from . models import Region, Location

# Awesome! I can specify the model to be used by ItemUpdateView
urlpatterns = [
path('update/region/',ItemUpdateView.as_view(model=Region), 
name='region_update'),
path('update/location/',  ItemUpdateView.as_view(model=Location),   
name='location_update'),
] 



>From models.py (Region and Location are only two of my tables, I'd like to 
have say 20 or 30 models 
from django.db import models

# Abstract class for our items including common methods, data and 
definitions
class ItemModel(models.Model):

fields = [ 'label', 'short', 'descr' ]
label   = models.CharField(max_length=10)
short   = models.CharField(max_length=15)
descr   = models.CharField(max_length=40)

def __str__(self):
return self.short

class Meta:
abstract = True

class Region(ItemModel):
fields  = [ 'label', 'short', 'descr' ]

class Location(ItemModel):
fields  = [ 'label', 'short', 'descr', 'region' ]
region  = models.ForeignKey(Region, on_delete=models.CASCADE)

class Plant(ItemModel):
fields  = [ 'label', 'short', 'descr', 'location', 'capex', 'opex', 
'capacity' ]
location= models.ForeignKey(Location, on_delete=models.CASCADE)
capex   = models.DecimalField(decimal_places=3, max_digits=8)
opex= models.DecimalField(decimal_places=3, max_digits=8)
capacity= models.DecimalField(decimal_places=3, max_digits=8)


-- 
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/ec4634e5-2279-49a7-9045-21712de87584%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Re-using CreateView, UpdateView & friendship

2018-04-29 Thread Mikkel Kromann
Hmmm. It might be my question 3 after all.
After a good night's sleep, I re-read the Figure 8.1 on Function vs Class 
Based Views in Two Scoops of Django ...

1) No generic view match closely what I have in mind (I think?)
2) I don't think I need to subclass my view
3) I suspect my CBV will need to process a lot of slightly different forms

So, I should make 4 function based views for create, read, update and 
delete that can handle my many quite similar Models.
Have I understood the difference between FBV and CBV correctly?

thanks, Mikkel



søndag den 29. april 2018 kl. 22.06.01 UTC+2 skrev Mikkel Kromann:
>
> Dear Django users.
>
> I'm testing whether Django is a good choice for a web based application 
> that I need to handle (create, read, update, delete) a lot of data tables.
> I've discovered the built-in Class Based View, which are going to save me 
> from a lot of repetitive code lines - yay! 
>
> Now, I've got an awful lot of models for my data tables (well, around 
> 20-30 ...) and looking at my code so far, it strikes me that it will 
> quickly become a bit repetitive, which I agree is a bad thing.
>
> From urls.py:
>
>
> urlpatterns = [
> # Urls for truck forms & actions
> path('data/trucks/list/',views.TruckListView.as_view(), name=
> 'truck_list'),
> path('data/trucks/create/',views.TruckCreateView.as_view(), name=
> 'truck_create'),
> path('data/trucks/update//',views.TruckUpdateView.as_view(), name=
> 'truck_update'),
> path('data/trucks/delete//',views.TruckDeleteView.as_view(), name=
> 'truck_delete'),
>
> # Urls for container forms & actions
> path('data/containers/list/',views.ContainersListView.as_view(), name=
> 'containers_list'),
> path('data/containers/create/',views.ContainersCreateView.as_view(), 
> name='containers_create'),
> path('data/containers/update//',views.ContainersUpdateView.as_view
> (), name='containers_update'),
> path('data/containers/delete//',views.ContainersDeleteView.as_view
> (), name='containers_delete'),
>
> # Urls for destination forms & actions
> # ... guess what will come here ...
>
> ]
>
> From views.py
>
> # Create views
> class TruckCreateView(CreateView):
> model = Truck
> fields = ['label', 'description', 'max_speed', 'max_weight', 
> 'max_volume' ]
>
> def get_success_url(self):
> return reverse("truck_list")
>
> class ContainerCreateView(CreateView):
> model = Container
> fields = ['label', 'description', 'max_weight', 'max_volume' ]
>
> def get_success_url(self):
> return reverse("container_list")
>
> # ... drum-whirl ... what is next? ... 
>
>
> I suppose my task at hand may be a bit unusual, but I aIso think I can't 
> be the first facing this problem.
> Basically, I want to do more or less the same with all my models (maybe in 
> 2 or 3 variations). So, 
>
> 1) did someone perhaps already make a nice package of Class Based Views 
> which can take an Model name as argument, with the model capable of 
> providing the necessary data, e.g. field list?
> 2) How advisable / possible would it be to take the object name from the 
> url and pass that on to the generic class based view?
> 3) Did I miss something very obvious? :)
>
>
> Thanks for your help, Mikkel
>

-- 
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/3e6e5850-0afc-4b8c-af49-17ba467a540f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re-using CreateView, UpdateView & friendship

2018-04-29 Thread Mikkel Kromann
Dear Django users.

I'm testing whether Django is a good choice for a web based application 
that I need to handle (create, read, update, delete) a lot of data tables.
I've discovered the built-in Class Based View, which are going to save me 
from a lot of repetitive code lines - yay! 

Now, I've got an awful lot of models for my data tables (well, around 20-30 
...) and looking at my code so far, it strikes me that it will quickly 
become a bit repetitive, which I agree is a bad thing.

>From urls.py:


urlpatterns = [
# Urls for truck forms & actions
path('data/trucks/list/',views.TruckListView.as_view(), name=
'truck_list'),
path('data/trucks/create/',views.TruckCreateView.as_view(), name=
'truck_create'),
path('data/trucks/update//',views.TruckUpdateView.as_view(), name=
'truck_update'),
path('data/trucks/delete//',views.TruckDeleteView.as_view(), name=
'truck_delete'),

# Urls for container forms & actions
path('data/containers/list/',views.ContainersListView.as_view(), name=
'containers_list'),
path('data/containers/create/',views.ContainersCreateView.as_view(), 
name='containers_create'),
path('data/containers/update//',views.ContainersUpdateView.as_view
(), name='containers_update'),
path('data/containers/delete//',views.ContainersDeleteView.as_view
(), name='containers_delete'),

# Urls for destination forms & actions
# ... guess what will come here ...

]

>From views.py

# Create views
class TruckCreateView(CreateView):
model = Truck
fields = ['label', 'description', 'max_speed', 'max_weight', 
'max_volume' ]

def get_success_url(self):
return reverse("truck_list")

class ContainerCreateView(CreateView):
model = Container
fields = ['label', 'description', 'max_weight', 'max_volume' ]

def get_success_url(self):
return reverse("container_list")

# ... drum-whirl ... what is next? ... 


I suppose my task at hand may be a bit unusual, but I aIso think I can't be 
the first facing this problem.
Basically, I want to do more or less the same with all my models (maybe in 
2 or 3 variations). So, 

1) did someone perhaps already make a nice package of Class Based Views 
which can take an Model name as argument, with the model capable of 
providing the necessary data, e.g. field list?
2) How advisable / possible would it be to take the object name from the 
url and pass that on to the generic class based view?
3) Did I miss something very obvious? :)


Thanks for your help, Mikkel

-- 
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/80559ac3-bb8b-429b-9395-7bd09870e636%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Advice needed: One big model or many apps with highly interlinked data tables?

2018-04-23 Thread Mikkel Kromann
Thank you to all three of you. 
This was exactly the advice I've been looking for, and increased my 
understanding of Django as well as of my own app.
I will go carefully through the relations between my different models, and 
split them up between several model files, and cross-import as needed.

cheers, Mikkel

lørdag den 14. april 2018 kl. 16.10.27 UTC+2 skrev Mikkel Kromann:
>
> Hi.
>
> I'm new to Django, and I'm working my way into Django by going through the 
> nice Djangoproject.com turorial. 
> I'm trying to find out whether Django is the right tool for my task, which 
> is maybe a bit unusual for Django.
>
> My task is to build a web interface to a database for an calculation tool 
> made in Python. 
> The database will contain maybe up to 100.000 pieces of data (mostly 
> decimal fields), and the tool will import this data, do some calculations 
> and write some results back to the database.
>
> My Django web interface should allow the user to view, add, delete and 
> edit the data in the database, and view the results with tables and charts.
> The data is organised in various chunks:
>
> - "Sets" which lend themselves very nicely to Django models, i.e. 
> HouseholdType, Item, City, Month, Year
> - "Maps", which are user defined ManyToOne or ManyToMany relations between 
> the various sets (can probably be worked into the "sets" models)
> - "Data Tables", which contains the main load of data, having the "sets" 
> as foreign keys (e.g. "Demand" for each HouseholdType, Item, City, Month 
> and year)
> - "Results tables", calculated by the tool but in structure quite similar 
> to the "Data tables"
>
> I will have roughly 10 sets, 10 maps. 20-30 data tables and 10-20 result 
> tables.
> I understand that putting all these into a one app will create biiig 
> models.py and views.py files, which is probably a bad idea.
>
> On the other hand, splitting the sets, maps and tables into several apps 
> does not seem to be an ideal solution either.
> All the tables and the maps will be models that have foreign keys to the 
> "sets" models.
> My understanding so far is, that it is also bad to have a lot of 
> interlinkage between the various apps.
>
> An intermediate solution might be, that if I make a "Sets" app containing 
> all the models that are going to be primary key in the other apps, then the 
> interlinkages between the apps is somewhat simplified.
>
> Any thoughts or advice?
>
>
> cheers, Mikkel 
>
>
>

-- 
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/1bb4ab4f-7e47-4d06-aacf-5c2c0f0606f7%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Advice needed: One big model or many apps with highly interlinked data tables?

2018-04-14 Thread Mikkel Kromann
Hi.

I'm new to Django, and I'm working my way into Django by going through the 
nice Djangoproject.com turorial. 
I'm trying to find out whether Django is the right tool for my task, which 
is maybe a bit unusual for Django.

My task is to build a web interface to a database for an calculation tool 
made in Python. 
The database will contain maybe up to 100.000 pieces of data (mostly 
decimal fields), and the tool will import this data, do some calculations 
and write some results back to the database.

My Django web interface should allow the user to view, add, delete and edit 
the data in the database, and view the results with tables and charts.
The data is organised in various chunks:

- "Sets" which lend themselves very nicely to Django models, i.e. 
HouseholdType, Item, City, Month, Year
- "Maps", which are user defined ManyToOne or ManyToMany relations between 
the various sets (can probably be worked into the "sets" models)
- "Data Tables", which contains the main load of data, having the "sets" as 
foreign keys (e.g. "Demand" for each HouseholdType, Item, City, Month and 
year)
- "Results tables", calculated by the tool but in structure quite similar 
to the "Data tables"

I will have roughly 10 sets, 10 maps. 20-30 data tables and 10-20 result 
tables.
I understand that putting all these into a one app will create biiig 
models.py and views.py files, which is probably a bad idea.

On the other hand, splitting the sets, maps and tables into several apps 
does not seem to be an ideal solution either.
All the tables and the maps will be models that have foreign keys to the 
"sets" models.
My understanding so far is, that it is also bad to have a lot of 
interlinkage between the various apps.

An intermediate solution might be, that if I make a "Sets" app containing 
all the models that are going to be primary key in the other apps, then the 
interlinkages between the apps is somewhat simplified.

Any thoughts or advice?


cheers, Mikkel 


-- 
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/7b0f436c-4bef-4c1f-b513-e18b820fb570%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.