Controlling access at table row level

2015-11-05 Thread Steve West
Hi all

I'm implementing a Django project in which individual table rows are marked 
as either private or public. I need to be able to filter accesses to the 
tables in such a way that logged-in users can see everything, but other 
users only get visibility of the 'public' rows. My initial thoughts were 
that I could apply a check on whether the user is logged in in any of three 
places: at the model level, in views or in templates. It seemed to me that 
the most elegant and robust option would be to do so at the model level, by 
writing custom managers for my models. Within the custom managers, I could 
check if the user is logged in and filter all queries accordingly.

I did an initial implementation of the above approach, but quickly found 
problems. Whenever I span foreign key relationships in my views, the 
default model manager is invoked, so i have had to add in further tests for 
whether the user is logged in at the view level. I've also got some cases 
where foreign keys are spanned at the template level and have had to add 
further login tests there, too.

All-in-all, I don't think I am going about this in the right way!  In the 
Django documentation, it seems to be mostly expected that one will use 
authentication to control access to individual views or model operations, 
rather than controlling finer-grained access to individual rows, so I 
haven't found anything that really helps.

Can anyone please offer any advice or suggest what would be the best way of 
solving the problem or point my at any documentation that might help.

Many thanks

Steve

-- 
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/002471e1-8a64-4637-9d00-ae774924fd84%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


ANN: django-admin-tools 0.7.0 released

2015-11-05 Thread David Jean Louis

Hello,

We are happy to announce the availability of the version 0.7.0 of 
django-admin-tools:

https://pypi.python.org/pypi/django-admin-tools/0.7.0

Django-admin-tools is a collection of extensions/tools for the default 
django administration interface, it includes:

 * a full featured and customizable dashboard,
 * a customizable menu bar,
 * tools to make admin theming easier.

This version fixes some issues and adds support for Django 1.9 and the 
new admin flat theme.


Thanks to all the people who contributed to this release.

The project is hosted on Github:
https://github.com/django-admin-tools/django-admin-tools

Django-admin-tools is generously documented, you can browse the 
documentation online here:

https://django-admin-tools.readthedocs.org/

Regards,

--
The django-admin-tools team
https://github.com/django-admin-tools/

--
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/563B3183.6030106%40gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Controlling access at table row level

2015-11-05 Thread Mike Dewhirst

On 5/11/2015 9:35 PM, Steve West wrote:

Hi all

I'm implementing a Django project in which individual table rows are 
marked as either private or public.


Have you looked at https://github.com/django-guardian/django-guardian

I need to be able to filter accesses to the tables in such a way that 
logged-in users can see everything, but other users only get 
visibility of the 'public' rows. My initial thoughts were that I could 
apply a check on whether the user is logged in in any of three places: 
at the model level, in views or in templates. It seemed to me that the 
most elegant and robust option would be to do so at the model level, 
by writing custom managers for my models. Within the custom managers, 
I could check if the user is logged in and filter all queries accordingly.


I did an initial implementation of the above approach, but quickly 
found problems. Whenever I span foreign key relationships in my views, 
the default model manager is invoked, so i have had to add in further 
tests for whether the user is logged in at the view level. I've also 
got some cases where foreign keys are spanned at the template level 
and have had to add further login tests there, too.


All-in-all, I don't think I am going about this in the right way!  In 
the Django documentation, it seems to be mostly expected that one will 
use authentication to control access to individual views or model 
operations, rather than controlling finer-grained access to individual 
rows, so I haven't found anything that really helps.


Can anyone please offer any advice or suggest what would be the best 
way of solving the problem or point my at any documentation that might 
help.


Many thanks

Steve
--
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/002471e1-8a64-4637-9d00-ae774924fd84%40googlegroups.com 
.

For more options, visit https://groups.google.com/d/optout.


--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/563B3B51.9060302%40dewhirst.com.au.
For more options, visit https://groups.google.com/d/optout.


Re: Controlling access at table row level

2015-11-05 Thread Jani Tiainen

Django has foundation for object level (row level) perms:

https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#handling-object-permissions

So basically you just check:

current_user.has_perm('permname', obj)

For a full list of methods you can check:
https://docs.djangoproject.com/en/1.8/ref/contrib/auth/#methods

On 05.11.2015 12:35, Steve West wrote:

Hi all

I'm implementing a Django project in which individual table rows are 
marked as either private or public. I need to be able to filter 
accesses to the tables in such a way that logged-in users can see 
everything, but other users only get visibility of the 'public' rows. 
My initial thoughts were that I could apply a check on whether the 
user is logged in in any of three places: at the model level, in views 
or in templates. It seemed to me that the most elegant and robust 
option would be to do so at the model level, by writing custom 
managers for my models. Within the custom managers, I could check if 
the user is logged in and filter all queries accordingly.


I did an initial implementation of the above approach, but quickly 
found problems. Whenever I span foreign key relationships in my views, 
the default model manager is invoked, so i have had to add in further 
tests for whether the user is logged in at the view level. I've also 
got some cases where foreign keys are spanned at the template level 
and have had to add further login tests there, too.


All-in-all, I don't think I am going about this in the right way!  In 
the Django documentation, it seems to be mostly expected that one will 
use authentication to control access to individual views or model 
operations, rather than controlling finer-grained access to individual 
rows, so I haven't found anything that really helps.


Can anyone please offer any advice or suggest what would be the best 
way of solving the problem or point my at any documentation that might 
help.


Many thanks

Steve
--
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/002471e1-8a64-4637-9d00-ae774924fd84%40googlegroups.com 
.

For more options, visit https://groups.google.com/d/optout.


--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/563B414A.70404%40gmail.com.
For more options, visit https://groups.google.com/d/optout.


Prefetch object with to_attr set to the same name as the field triggers rows deletions

2015-11-05 Thread mccc
I'm using a Prefetch object to follow some GenericRelation, and I was 
playing around with the to_attr parameter;
I had the DB debug turned on, as I was checking whether it was making any 
difference, and I started noticing some DELETE statements on the remote 
table, so I started investigating.
It looks like those deletions are triggered within the prefetch process 
when the to_attr is set to the same name as the field; also, it does not 
seem to happen if the relationship is not a generic one.
While this usage is presumably wrong, it is not mentioned anywhere in the 
docs; also, I think that deleting rows from the database is a somewhat 
extreme way to educate users :)
Can someone enlighten me on what's going on here?

Thank you very much.

-- 
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/c1680410-8bb7-4358-a3ee-44f65cdc7c70%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How do I relate two tables using field name instead of id?

2015-11-05 Thread frocco
The two models from msaccess are linked by name field, not id.
Can I like by name field in django and not use id?

There was no id in the table

On Wednesday, November 4, 2015 at 12:35:49 PM UTC-5, Dheerendra Rathor 
wrote:
>
> In your model use define __str__ method to name1. Then django admin will 
> use name1 in dropdown box. 
>
> On Wed, 4 Nov 2015 at 21:50 frocco > wrote:
>
>> Hello,
>>
>> I have two existing tables 
>> table1 has name1
>>
>> table2 has name2
>>
>> when I edit table2 in admin, I want a dropdownbox that shows values from 
>> table1 using name1
>> both fields are character
>>
>> I cannot change the design, porting from msaccess
>>
>> thanks
>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to django-users...@googlegroups.com .
>> To post to this group, send email to django...@googlegroups.com 
>> .
>> Visit this group at http://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/756fc995-1c2c-4aee-a074-0a327dbc84e0%40googlegroups.com
>>  
>> 
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/b76f6937-5be1-4025-8fe0-093f4542a527%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How do I relate two tables using field name instead of id?

2015-11-05 Thread Gergely Polonkai
It is possible, but in an SQL database it may become ineffective. For this,
you will have to make the name field unique, and put an index on it
(uniqueness also creates an index, by the way).

For the admin site to display names, though, you still have to define the
__str__() method that does only something like "return self.name".

However, based on what I said above, if I were you, I would convert the
access database so the tables use integer IDs for foreign keys. The admin
site will need to fetch data from the other table in both cases, but it can
speed up indexing and usage on the long run.

2015-11-05 15:08 GMT+01:00 frocco :

> The two models from msaccess are linked by name field, not id.
> Can I like by name field in django and not use id?
>
> There was no id in the table
>
> On Wednesday, November 4, 2015 at 12:35:49 PM UTC-5, Dheerendra Rathor
> wrote:
>>
>> In your model use define __str__ method to name1. Then django admin will
>> use name1 in dropdown box.
>>
>> On Wed, 4 Nov 2015 at 21:50 frocco  wrote:
>>
>>> Hello,
>>>
>>> I have two existing tables
>>> table1 has name1
>>>
>>> table2 has name2
>>>
>>> when I edit table2 in admin, I want a dropdownbox that shows values from
>>> table1 using name1
>>> both fields are character
>>>
>>> I cannot change the design, porting from msaccess
>>>
>>> thanks
>>>
>>> --
>>> You received this message because you are subscribed to the Google
>>> Groups "Django users" group.
>>> To unsubscribe from this group and stop receiving emails from it, send
>>> an email to django-users...@googlegroups.com.
>>> To post to this group, send email to django...@googlegroups.com.
>>> Visit this group at http://groups.google.com/group/django-users.
>>> To view this discussion on the web visit
>>> https://groups.google.com/d/msgid/django-users/756fc995-1c2c-4aee-a074-0a327dbc84e0%40googlegroups.com
>>> 
>>> .
>>> For more options, visit https://groups.google.com/d/optout.
>>>
>> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/b76f6937-5be1-4025-8fe0-093f4542a527%40googlegroups.com
> 
> .
>
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CACczBUJHosmjBKanE_0x95412YGjOQ9%3DTkD%3DkdTHwXZuhsB%3DtQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: How do I relate two tables using field name instead of id?

2015-11-05 Thread frocco
Thanks, I will look into adding id

If I just do this, clinician = models.ForeignKey(Clinician)
I get clinician_id does not exist

In my related table I have

def __unicode__(self):
return self.clinicianname


On Wednesday, November 4, 2015 at 11:19:40 AM UTC-5, frocco wrote:
>
> Hello,
>
> I have two existing tables 
> table1 has name1
>
> table2 has name2
>
> when I edit table2 in admin, I want a dropdownbox that shows values from 
> table1 using name1
> both fields are character
>
> I cannot change the design, porting from msaccess
>
> thanks
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/44660e3a-cd6c-4858-8b29-d1dc4ceeced0%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Custom QuerySet and __date field lookup

2015-11-05 Thread Simon Charette
Hi Adam,

I couldn't reproduce your issue with Django 1.9.b1 with the following model 
definition:

from __future__ import unicode_literals

import datetime

from django.db import models


class EntryQuerySet(models.QuerySet):
def today(self):
today = datetime.date.today()
return self.filter(start__date=today)

class Entry(models.Model):
start = models.DateTimeField()

objects = EntryQuerySet.as_manager()

Are you sure you are actually using Django 1.9?

Simon

Le mercredi 4 novembre 2015 14:45:33 UTC+1, aprzy...@gmail.com a écrit :
>
> Hello,
>
> I'm playing around with the 1.9 beta release. The __date field lookup 
> (casts DateTimeField to a date) is a very useful new addition. However, it 
> doesn't seem to work in a custom QuerySet.
>
> models.py
>
> class EntryQuerySet(models.QuerySet):
> def today(self):
>  today = now().date()
>  return self.filter(start__date=today) [start is a DateTimeField]
>
> In Django shell:
>
> >>> WorkSession.objects.today()
>
> ...
>
> django.core.exceptions.FieldError: Unsupported lookup 'date' for 
> DateTimeField or join on the field not permitted.
>
> Changing "__date=today" to "__year=2015" produces the expected results. If 
> this is a bug, I'll attach the full traceback and models.py.
>
> Adam
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/41c9befb-3446-4944-a56b-f8c74122848a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Prefetch object with to_attr set to the same name as the field triggers rows deletions

2015-11-05 Thread Simon Charette
Hi mccc,

Would it be possible to provide an example of the models and actions 
required to trigger the deletion.

I suppose the deletion is triggered by the many to many relationship 
assignment logic and we should simply raise a ValueError if `to_attr` is 
set the same name as the referred relationship.

Thanks,
Simon

Le jeudi 5 novembre 2015 15:04:31 UTC+1, mccc a écrit :
>
> I'm using a Prefetch object to follow some GenericRelation, and I was 
> playing around with the to_attr parameter;
> I had the DB debug turned on, as I was checking whether it was making any 
> difference, and I started noticing some DELETE statements on the remote 
> table, so I started investigating.
> It looks like those deletions are triggered within the prefetch process 
> when the to_attr is set to the same name as the field; also, it does not 
> seem to happen if the relationship is not a generic one.
> While this usage is presumably wrong, it is not mentioned anywhere in the 
> docs; also, I think that deleting rows from the database is a somewhat 
> extreme way to educate users :)
> Can someone enlighten me on what's going on here?
>
> Thank you very much.
>

-- 
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/3a9eae38-e532-4c28-be04-61b5b62ed030%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Safe tag is working differently for different view.

2015-11-05 Thread Collin Anderson
Hello,

Are you sure they're using the same template? (If you change something does 
it actually affect both views?)

Is one of the views using mark_safe?

Collin

On Tuesday, October 27, 2015 at 9:29:02 PM UTC+1, sonu kumar wrote:
>
> I am having two views both are extending from same base.html and both of 
> them have loaded same template tags, but one is escaping string using safe 
> and other is not what could be 
> Code 
>
> view 1
>
> {% extends 'base.html' %}
> {% load inplace_edit mezzanine_tags rating_tags keyword_tags comment_tags 
> nano_tags staticfiles %}
>
> ...
>
> {% comments_for object %}
>
> ...
>
> view 2
>
> {% extends "base.html" %}
>
> {% load inplace_edit mezzanine_tags comment_tags keyword_tags nano_tags i18n 
> future staticfiles %}
>
> ...
>
> {% comments_for blog_post %}
>
> ...
>
>
> view3 (comment.html)
>
> {% load i18n mezzanine_tags comment_tags  nano_tags future %}
>
> ...
>
> {{ comment.comment|safe  }}
>
> ...
>
>
> As we can see both view 1 and 2 are using same function so it would be using 
> same template but in view2 safe is working and in view1 it's not working.
>
>
> What could be the reason for this ?
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/ba60efb5-36be-492a-b9f0-e1007de500f3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Standalone Project using django ORM

2015-11-05 Thread Collin Anderson
Hi,

It looks like you stack trace is somehow getting cut off.

My guess is it's trying to import something that either doesn't exist or 
has a syntax error.

Collin

On Wednesday, October 28, 2015 at 12:39:06 AM UTC+1, ADEWALE ADISA wrote:
>
> The screen shot is attached. There is no error message but the trace. But 
> the program seem stop at django.setup(). Though it ran smoothly in django 
> 1.50
> On Oct 28, 2015 12:27 AM, "Dheerendra Rathor"  > wrote:
>
>> Is this the full stacktrace? Looks like error message is missing in 
>> stacktrace. 
>>
>> On Wed, 28 Oct 2015 at 04:05 ADEWALE ADISA > > wrote:
>>
>>> Hello;
>>> I have being having issues trying to use django orm in my application. 
>>> This issues occur when using django 1.85. The application run perfectly 
>>> well on django 1.50. Bellow are the snippet :
>>>
>>> Model.py:
>>> from django.db import models
>>>
>>> class Person(models.Model):
>>> name = models.CharField(max_length=100)
>>> email = models.CharField(max_length=100)
>>> birthdate = models.DateField()
>>> class Meta:
>>> app_label = 'runnable'
>>> 
>>> def __unicode__(self):
>>> return u'%d: %s' % (self.id, self.name)
>>>
>>> app.py:
>>>
>>> import sys
>>> from os import path
>>> import collections
>>> import datetime
>>> sys.path.insert(0, path.abspath(path.join(path.dirname(__file__), '..'
>>> )))
>>>
>>> from django.core.management import call_command
>>> from django.conf import settings
>>>
>>> #print(sys.path)
>>> if not settings.configured:
>>> settings.configure(
>>>DEBUG=True,
>>> DATABASES={
>>> 'default': {
>>> # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 
>>> 'oracle'.
>>> 'ENGINE': 'django.db.backends.sqlite3',
>>> # Or path to database file if using sqlite3.
>>> 'NAME': ':memory:',
>>> }
>>> },
>>> INSTALLED_APPS=("runnable", )
>>> 
>>> )
>>>
>>> import django
>>> django.setup()
>>> #call_command('syncdb')
>>> call_command('makemigrations')
>>> call_command('migrate')
>>> call_command('inspectdb')
>>> from models import Person
>>> print("PERSON: "+ Person)
>>>
>>> Console msg:
>>> p.py", line 28, in 
>>> django.setup()
>>>   File 
>>> "/data/data/com.hipipal.qpy3/files/lib/python3.2/site-packages/django/__init__.py",
>>>  
>>> line 18, in setup
>>> apps.populate(settings.INSTALLED_APPS)
>>>   File 
>>> "/data/data/com.hipipal.qpy3/files/lib/python3.2/site-packages/django/apps/registry.py",
>>>  
>>> line 108, in populate
>>> app_config.import_models(all_models)
>>>   File 
>>> "/data/data/com.hipipal.qpy3/files/lib/python3.2/site-packages/django/apps/config.py",
>>>  
>>> line 198, in import_models
>>> self.models_module = import_module(models_module_name)
>>>   File 
>>> "/data/data/com.hipipal.qpy3/files/lib/python3.2/python32.zip/importlib/__init__.py",
>>>  
>>> line 124, in import_module
>>>
>>> Note:
>>> The application run successfully with django 1.50  by uncomment syncdb 
>>> and comment out migration, make migrations.
>>>
>>> Thanks.
>>>
>>> -- 
>>> You received this message because you are subscribed to the Google 
>>> Groups "Django users" group.
>>> To unsubscribe from this group and stop receiving emails from it, send 
>>> an email to django-users...@googlegroups.com .
>>> To post to this group, send email to django...@googlegroups.com 
>>> .
>>> Visit this group at http://groups.google.com/group/django-users.
>>> To view this discussion on the web visit 
>>> https://groups.google.com/d/msgid/django-users/CAMGzuy9BSMrgqw8uMgp3kd9eBu5fTdF4DCB9%3Di-8r6EmZmN-WA%40mail.gmail.com
>>>  
>>> 
>>> .
>>> For more options, visit https://groups.google.com/d/optout.
>>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> 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 http://groups.google.com/group/django-users.
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/CAByqUgjWYn%3DtfSeA-EBrzeur2_jodiPysZUS%3Dor%2BFeCFpKhbwg%40mail.gmail.com
>>  
>> 
>> .
>> For more options, visit https://groups.google.com/d/optout.
>>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
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@googlegro

Re: [django_tables2] Expected table or queryset, not 'str'.

2015-11-05 Thread Collin Anderson
Hi,

Do you to post your traceback if you're still getting this error?

Thanks,
Collin

On Wednesday, October 28, 2015 at 2:17:28 PM UTC+1, Leutrim Osmani wrote:
>
> Can you please tell me how did you fixed this error ?
>
> On Monday, April 29, 2013 at 9:21:29 AM UTC+2, binith a k wrote:
>>
>> You were correct, it was indeed a version problem.
>> I was using latest django-tables2 in my new python virtual env and I had 
>> an older version (of django-tables2) installed as default, and the 
>> PYTHONPATH environment variable was pointing to the older version.
>>
>> Problem solved, thanks for the time
>>
>> thanks
>> -binith
>>
>> On Friday, 26 April 2013 07:25:35 UTC-7, Binith Babu wrote:
>>>
>>> I am sorry I coud not find a solution in this thread
>>>
>>> Did you mean I am using an older version of django tables2 ?
>>> In that case I am not, I am using the latest version installed with pip.
>>> May be its my mistake, I am still trying to figure whether I am doing 
>>> something wrong.
>>> WIll post back if I find something.
>>>
>>> Thanks
>>> binith
>>>
>>>
>>>
>>> On Friday, 26 April 2013 06:53:06 UTC-7, Tom Evans wrote:

 On Fri, Apr 26, 2013 at 2:30 PM, Binith Babu  wrote: 
 > 
 > I got the same error today, anybody know a solution? 
 > 

 Apart from the solution I already posted to the list in this thread? 

 Cheers 

 Tom 

>>>

-- 
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/3f6afa29-5c9e-4dac-ad5d-a4c29824676a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Locking / serializing access to one element in database

2015-11-05 Thread Collin Anderson
Hi Carsten,

If you're just updating one field, this _might_ work for you:

try:
TestMonthModel.objects.create(jahr=Jahr, monat=Monat)  # create() uses 
force_insert.
except IntegrityError:
pass # It already exists. No Problem.
# ... calculate some things.
TestMonthModel.objects.filter(jahr=Jahr, monat=Monat).update(value=new_value
)

Collin

On Wednesday, October 28, 2015 at 8:50:09 PM UTC+1, Carsten Fuchs wrote:
>
> Hi Collin, hi all, 
>
> Am 27.10.2015 um 19:56 schrieb Collin Anderson: 
> > Yes, an exception will be raised. 
>
> Thinking further about this, all we need is a method that gives us an 
> exception if we 
> accidentally create a second object when in fact only one is wanted. Your 
> suggestion 
> with manually dealing with the PKs and using .save(force_insert=True) is 
> one method to 
> achieve that, another one that works well for me is using an 
> (application-specific) 
>
>  unique_together = (year, month) 
>
> constraint, which achieves the desired result (guarantee uniqueness where 
> required, 
> raise an exception otherwise) without having to manually deal with PKs. 
>
> Alas, I wonder how to proceed to complete the solution. As I find it 
> simpler to deal 
> with the above mentioned unique_together rather than with coming up with a 
> PK based 
> solution, I refer to my original code from [1], which was: 
>
>
>  try: 
>  mm = TestMonthModel.objects.select_for_update().get(jahr=Jahr, 
> monat=Monat) 
>  except TestMonthModel.DoesNotExist: 
>  mm = TestMonthModel(jahr=Jahr, monat=Monat) 
>
>  # A *long* computation, eventually setting fields in mm and save: 
>
>  mm.value = 123 
>  mm.save() 
>
>
> Combining everything from this thread, this could be changed into this 
> code 
> (pseudo-code, not tested): 
>
>
>  while True: 
>  try: 
>  mm = 
> TestMonthModel.objects.select_for_update().get(jahr=Jahr, monat=Monat) 
>  break   # Got what we wanted! 
>  except TestMonthModel.DoesNotExist: 
>  try: 
> # Create the expected but missing instance. 
>  # No matter if the following succeeds normally or throws 
>  # an Integrity error, thereafter just restart the loop. 
>  TestMonthModel(jahr=Jahr, monat=Monat).save() 
>  except IntegrityError: 
>  pass 
>
>  # A *long* computation, eventually setting fields in mm and save: 
>
>  mm.value = 123 
>  mm.save() 
>
>
> Afaics, this solves the problem, but it also feels quite awkward and I 
> wonder if there 
> is a more elegant solution. 
>
> Comments? Does this sound reasonable at all? 
>
> Best regards, 
> Carsten 
>
> [1] https://groups.google.com/forum/#!topic/django-users/SOX5Vjedy_s 
>
>

-- 
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/9351c121-9e4a-428d-8d70-e0563af99d97%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: mssql databASE CONNECTION to Django

2015-11-05 Thread Collin Anderson
Hello,

I'd recommend using django 1.7 until mssql gets compatible with django 1.8.

Thanks,
Collin

On Friday, October 30, 2015 at 3:31:35 PM UTC+1, Sid wrote:
>
> sorry tim I know I am asking a dumb question...can you please tell me what 
> is the best way to make it work please if possibe...because I am struck 
> form last 2 days
>

-- 
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/111d7267-3597-4bdb-8bb9-20e3eb13879c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Django bootstrap3_datetime widget in admin site doesn't pass form data

2015-11-05 Thread Collin Anderson
Hi Ilia,

The default admin widget looks for id_0 and id_1, but if you use a custom 
widget, that is responsible for looking for its own value (like 
publish_time_1). You could check out DateTimePicker's source code to see 
what it's actually doing.

Thanks,
Collin

On Sunday, November 1, 2015 at 3:04:28 PM UTC+1, Ilia wrote:
>
> I'm trying to replace the standard AdminSplitDateTime widget in my admin 
> site for better functionality (basically I want to display only 'available' 
> dates in my calender which I couldn't find how to do with the default 
> picker). I decided to use the bootstrap3_datetime widget.
>
> After overriding my field to use the new widget, it doesn't seem to be 
> transferred into the 'clean' method (isn't in self.cleaned_data) for 
> validation.
>
> *models.py*
>
> publish_time = models.DateTimeField('Date to publish')
>
> *admin.py*
>
> class MyForm(forms.ModelForm):
>
> def __init__(self, *args, **kwargs):
> super(MyForm, self).__init__(*args, **kwargs)
> bad_dates = []
> #populating bad_dates with application logic
>
> def clean(self):
>
> # This will always return None when using the new widget.
> # When working with the default widget, I have the correct value.
> publish_time = self.cleaned_data.get('publish_time', None)
>
>
> publish_time = forms.DateTimeField(widget=DateTimePicker(options=
> {"format": "DD-MM- HH:mm",
>  "startDate": timezone.now().strftime('%Y-%m-%d'),
>  "disabledDates": bad_dates,
>  })
>
> class MyModelAdmin(admin.ModelAdmin):
> form = MyForm
>
> admin.site.register(MyModel, MyModelAdmin)
>
> HTML-wise, the widget works well and the text field is populated with the 
> correct date (and with the 'bad_dates' disabled). The problem is that it 
> seems it isn't saved on the form.
>
> I also tried initializing the widget in the init method by doing:
>
> self.fields['publish_time'].widget = DateTimePicker(options=...)
>
> But the result was the same.
>
> I've analysed the POST request that is sent using each of the widgets. In 
> the default admin widget, I see that it generates two fields: 
> "publish_time_0" (for date) and "publish_time_1" (for time). In the 
> bootstrap3 widget, only a single "publish_time" field is sent.
>
> I'm assuming that the admin site understands that the field is a 
> DateTimeField (from models), looks for id_0 and id_1 and that's why it 
> fails. Does that make sense? Is there anyway around it?
>
> Thanks a lot!
> Ilia
>

-- 
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/60cd4c0a-3220-46f7-8527-2230f291432c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: jquery and django template

2015-11-05 Thread Collin Anderson
Hi,

Are you trying to show the user what filters are being applied to the data, 
or are you trying to filter the data based on a user selection?

Collin

On Monday, November 2, 2015 at 2:51:36 AM UTC+1, varun naganathan wrote:
>
> I basically have the database entries in the namespace of my template.I 
> basically need to get the filter i want to apply on the databse entry using 
> data available from user selection(using jquery).Any suggestions on how i 
> can achieve this?
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/37a720f5-020b-49ec-8119-120da188ca5a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: How do I relate two tables using field name instead of id?

2015-11-05 Thread Gergely Polonkai
If you go with the current solution, you will have to add the to_field
keyword argument to ForeignKey:

clinician = models.ForeignKey(Clinician, to_field='name')

Best,
Gergely

2015-11-05 15:47 GMT+01:00 frocco :

> Thanks, I will look into adding id
>
> If I just do this, clinician = models.ForeignKey(Clinician)
> I get clinician_id does not exist
>
> In my related table I have
>
> def __unicode__(self):
> return self.clinicianname
>
>
> On Wednesday, November 4, 2015 at 11:19:40 AM UTC-5, frocco wrote:
>>
>> Hello,
>>
>> I have two existing tables
>> table1 has name1
>>
>> table2 has name2
>>
>> when I edit table2 in admin, I want a dropdownbox that shows values from
>> table1 using name1
>> both fields are character
>>
>> I cannot change the design, porting from msaccess
>>
>> thanks
>>
>> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/44660e3a-cd6c-4858-8b29-d1dc4ceeced0%40googlegroups.com
> 
> .
>
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CACczBULUX9nMhjMFgM54ZQ3CZiNNZPLTjBeidO9-f%2BVzR30zGw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: How do I relate two tables using field name instead of id?

2015-11-05 Thread frocco
Thank you

On Wednesday, November 4, 2015 at 11:19:40 AM UTC-5, frocco wrote:
>
> Hello,
>
> I have two existing tables 
> table1 has name1
>
> table2 has name2
>
> when I edit table2 in admin, I want a dropdownbox that shows values from 
> table1 using name1
> both fields are character
>
> I cannot change the design, porting from msaccess
>
> thanks
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/f42b087f-dffe-42df-994b-22e9028dd4c7%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Prefetch object with to_attr set to the same name as the field triggers rows deletions

2015-11-05 Thread Michele Ciccozzi
Hello Simon,

I'm going to paste a trimmed-down version of the involved classes:

class CeleryTask(models.Model):
celery_task_id = models.CharField(max_length=50, primary_key=True)
task_type = models.ForeignKey(ContentType)
task_id = models.PositiveIntegerField()
task = GenericForeignKey('task_type', 'task_id')

class AccountManagementTask(models.Model):
account = models.ForeignKey(Account, null=True, editable=False)
task_content_type = models.ForeignKey(ContentType)
task_content_id = models.PositiveIntegerField()
task_content = GenericForeignKey('task_content_type', 'task_content_id')
celery_task = GenericRelation(CeleryTask,
content_type_field='task_type', object_id_field='task_id',

related_query_name='account_management_tasks')

(the task_content thing is involved in a follow-up question that will be
asked in a short while)

This is the code triggering the weirdness:

previous_tasks =
AccountManagementTask.objects.filter(account=account)\
.prefetch_related(
Prefetch('celery_task',
 to_attr='celery_task'))\
.prefetch_related(
Prefetch('task_content',
 to_attr='task_content'))\
.annotate(created_on=F('celery_task__created_on'))\

Immediately after that, the QuerySet is sent off to a simple DRF serializer
- which doesn't even touch the issue since the relevant piece of
information is annotated:

class AccountManagementTaskSerializer(serializers.ModelSerializer):
def to_representation(self, instance):
return {'id': instance.pk,
'created_on': instance.created_on,
'date_from': instance.task_content.date_from,
'date_to': instance.task_content.date_to}

class Meta:
model = AccountManagementTask


Now the follow-up, that you might already have guessed: if I *do* use the
same name for following the GenericForeignKey relation (task_content), the
content of the relationship does not get deleted(no surprise there..?) and
I can go with my naïve serialization over there, while if I specify a
different to_attr name I get back a list and I have to deal differently
with that.
How do these prefetch_related / Prefetch to_attr / Generic* things really
work?

Merci beaucoup,
Michele

On Thu, Nov 5, 2015 at 4:14 PM, Simon Charette  wrote:

> Hi mccc,
>
> Would it be possible to provide an example of the models and actions
> required to trigger the deletion.
>
> I suppose the deletion is triggered by the many to many relationship
> assignment logic and we should simply raise a ValueError if `to_attr` is
> set the same name as the referred relationship.
>
> Thanks,
> Simon
>
> Le jeudi 5 novembre 2015 15:04:31 UTC+1, mccc a écrit :
>>
>> I'm using a Prefetch object to follow some GenericRelation, and I was
>> playing around with the to_attr parameter;
>> I had the DB debug turned on, as I was checking whether it was making any
>> difference, and I started noticing some DELETE statements on the remote
>> table, so I started investigating.
>> It looks like those deletions are triggered within the prefetch process
>> when the to_attr is set to the same name as the field; also, it does not
>> seem to happen if the relationship is not a generic one.
>> While this usage is presumably wrong, it is not mentioned anywhere in the
>> docs; also, I think that deleting rows from the database is a somewhat
>> extreme way to educate users :)
>> Can someone enlighten me on what's going on here?
>>
>> Thank you very much.
>>
> --
> You received this message because you are subscribed to a topic in the
> Google Groups "Django users" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/django-users/CDe4McxxCsI/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to
> django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/3a9eae38-e532-4c28-be04-61b5b62ed030%40googlegroups.com
> 
> .
>
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAP1Jri%2BmP7OCeK2fSKepEDAWvJ8U8C1ATZdv2RCTs48WBgk3OA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/o

Re: return values from static files to django admin

2015-11-05 Thread Collin Anderson
Hi,

You may need to also calculate the possible options in python. Some hacky 
code that might help:

class AdminRoutingInlineForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(AdminRoutingInlineForm, self).__init__(*args, **kwargs)
field1 = self.data.get('field1', '')
CHOICES = [('a', '%s any' % field1),('b', '%s blah' % field1),] 
self.fields['choice_text'].choices = CHOICES

Collin

On Monday, November 2, 2015 at 9:32:58 PM UTC+1, dc wrote:
>
> I tried that. But in that case I need to declare choices in models.py for 
> that field (so that the field is displayed as a dropdown in admin) and then 
> django doesn't accept any string that's not part of the choices list. I am 
> pretty sure I am missing something here.
>
> On Mon, Nov 2, 2015 at 2:55 PM, Andreas Kuhne  > wrote:
>
>> Hi,
>>
>> Yes you could just populate the dropdown list with javascript. 
>>
>> Regards,
>>
>> Andréas
>>
>> 2015-11-02 17:27 GMT+01:00 dc >:
>>
>>> Thanks a lot. Let me look into it.
>>>
>>> Is there any other way I can populate my choice list with user input?
>>>
>>> On Monday, November 2, 2015 at 10:19:22 AM UTC-5, Andréas Kühne wrote:

 Hi,

 What you are suggesting doesn't work. You can't communicate with the 
 django backend via javascript if you don't use a lot of ajax requests. I 
 would check django-smart-selects and see if you could use that?

 Regards,

 Andréas

 2015-11-02 15:57 GMT+01:00 dc :

> Any lead will be extremely helpful. I am still stuck. :(
>
> On Thursday, October 29, 2015 at 11:40:32 PM UTC-4, dc wrote:
>>
>> I have declared a charfield 'choice_text' in one of my models. I want 
>> to convert it to a dropdown box in django admin. The choices in the 
>> dropdown list depend on user input to a textbox defined in another 
>> model class. I have a javascript (declared  as Media class inside a 
>> ModelAdmin class) that reads user input in the textbox. But I am unable 
>> to 
>> this choice list back from .js file to django admin. How do I do that? 
>> Thanks in advance.
>>
>> I have tried this.
>>
>> *models.py*
>> class Routing(models.Model):
>> choice_text = models.CharField(_('Choices'), max_length=100, 
>> default="(any)", null=False)
>>
>> *admin.py*
>> class AdminRoutingInlineForm(forms.ModelForm):
>> def __init__(self, *args, **kwargs):
>> super(AdminRoutingInlineForm, self).__init__(*args, **kwargs)
>> CHOICES = [('a', 'any'),('b', 'blah'),] * // override 
>> this with choices from populate_dropdown.js (code below)*
>> self.fields['choice_text'].choices = CHOICES
>>
>> class RoutingInlineAdmin(StackedInline):
>> form = AdminRoutingInlineForm
>> fields = (('choice_text', 'next'),)
>> model = Routing
>>
>>
>> class FormModelAdmin(ModelAdmin):
>> inlines = [RoutingInlineAdmin]
>>
>> class Media:
>> js= ("sforms/admin/populate_dropdown.js",)
>>
>>
>> *populate_dropdown.js*
>> (function($) {
>> $(document).ready(function() {
>>
>> $("[id^=id_fields-][id$=_options_0]").each(function(){ *  
>> // user input from this field will be used as choices*
>> choices = '(any),' + $(this).val().split("\n");
>> alert(choices);
>> 
>> *// send this choices back to admin.py and override CHOICES 
>> in AdminRoutingInlineForm class*
>> });  
>> });
>>  
>>
>>
>> -- 
> 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 http://groups.google.com/group/django-users.
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/django-users/6ef56f22-dce0-4a85-b348-381b3a93e88f%40googlegroups.com
>  
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>

 -- 
>>> You received this message because you are subscribed to the Google 
>>> Groups "Django users" group.
>>> To unsubscribe from this group and stop receiving emails from it, send 
>>> an email to django-users...@googlegroups.com .
>>> To post to this group, send email to django...@googlegroups.com 
>>> .
>>> Visit this group at http://groups.google.com/group/django-users.
>>> To view this discussion on the web visit 
>>> https://groups.google.com/d/msgid/django-users/24ac486e-08fa-42cd-a426-bda97246693c%40googlegroups.com
>>>  

Why my aggregate is not working?

2015-11-05 Thread Fellipe Henrique
Hi, I have these model:

class ProductClicks(models.Model):
product = models.ForeignKey(Product)
dthr = models.DateTimeField(_('Date/Time Click'), auto_now_add=True)
ip = models.CharField(_('IP'), max_length=20, blank=True, null=True)


And this view:

current_month = datetime.now().month

list_prod = ProductClicks.objects.filter(dthr__month=current_month)\
.aggregate(total=Count('product'))


But in my template doesn't show my aggregate list.

My goal is: show a list of all product with the Count, like in SQL when we
use Group By...

What's my error?

T.·.F.·.A.·. S+F
*Fellipe Henrique P. Soares*

e-mail: > echo "lkrrovknFmsgor4ius" | perl -pe \ 's/(.)/chr(ord($1)-2*3)/ge'
*Fedora Ambassador: https://fedoraproject.org/wiki/User:Fellipeh
*
*Blog: *http:www.fellipeh.eti.br
*GitHub: https://github.com/fellipeh *
*Twitter: @fh_bash*

-- 
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAF1jwZGhgy-daV0v70OTTR46%3Diq4TVZhGfXO1DEiyGmivxKVtg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


update_or_create() always creates (or recreates)

2015-11-05 Thread Yunti
I have tried to use the update_or_create() method assuming that it would 
either, create a new entry in the db if it found none or update an existing 
one if it found one and had differences to the defaults passed in  - or 
wouldn't update if there was no difference.  However it just seemed to 
recreate entries each time even if there were no changes.

I think the issue was that I wanted to:
1)  get an entry if all fields were the same,
2) or create a new entry if it didn't find an existing entry with the 
unique_id
3) or if there was an entry with the same unique_id, update that entry with 
remaining fields. 

The update_or_create() method doesn't seem to work as I had hoped using how 
I have called it below - it just always seems to do an update if it finds a 
match on the given kwargs. 

Or if I tried passing in all That would 
would have to be passing in all the fields as keyword args to check that 
nothing had changed but then that would miss option 3) finding an existing 
entry that 






supplier, created = 
Supplier.objects.update_or_create(unique_id=product_detail['supplierId'],
   defaults={
   'name': 
product_detail['supplierName'],
   'entity_name_1': 
entity_name_1,
   'entity_name_2': 
entity_name_1,
   'rating': 
product_detail['supplierRating']})





class Supplier(models.Model):
unique_id = models.IntegerField(unique=True)
name = models.CharField(max_length=255, unique=True)
entity_name_1 = models.CharField(max_length=255, blank=True)
entity_name_2 = models.CharField(max_length=255, blank=True)
rating = models.CharField(max_length=255)

last_updated = models.DateTimeField(auto_now=True)


def __str__(self):
return self.name


Not being convinced that update_or_create() would give me what I needed I made 
the below function:


def create_or_update_if_diff(defaults, model):
try:
instance = model.objects.get(**defaults)
# if no exception, the product doesn't need to be updated
except model.DoesNotExist:
# the product needs to be created or updated
try:
model.objects.get(unique_id=defaults['unique_id'])
except model.DoesNotExist:
# needs to be created
instance = model.objects.create(**defaults)
# model(**defaults).save()
sys.stdout.write('New {} created: {}\n'.format(model, 
instance.name)) 
return instance, True
else:
# needs to be updated
instance = model.objects.update(**defaults)
sys.stdout.write('{}:'
 ' {} updated \n'.format(model, 
instance.unique_id)) 
return instance, True
return instance, False


However I can't get it to be quite right.  I key a key error on update possibly 
because the defaults passed in now include unique_id. Should the unique_id be 
separated and both passed into the function to fix this?  (And should I have 
created a function to achieve this - or would have update_or_create() have been 
able to do this.?)



supplier_defaults={
   'unique_id': 
product_detail['supplierId'],
   'name': 
product_detail['supplierName'],
   'entity_name_1': 
entity_name_1,
   'entity_name_2': 
entity_name_2,
   'rating': 
product_detail['supplierRating']}



-- 
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/a0b6e1dd-d583-480e-9c6e-540c1ad4511a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Why my aggregate is not working?

2015-11-05 Thread Dheerendra Rathor
Are you sure you want to use aggregate? Aggregate will return you a
dictionary like {'total': 10}. Probably you want to use annotate which will
return you a queryset.

On Thu, 5 Nov 2015 at 22:09 Fellipe Henrique  wrote:

> Hi, I have these model:
>
> class ProductClicks(models.Model):
> product = models.ForeignKey(Product)
> dthr = models.DateTimeField(_('Date/Time Click'), auto_now_add=True)
> ip = models.CharField(_('IP'), max_length=20, blank=True, null=True)
>
>
> And this view:
>
> current_month = datetime.now().month
>
> list_prod = ProductClicks.objects.filter(dthr__month=current_month)\
> .aggregate(total=Count('product'))
>
>
> But in my template doesn't show my aggregate list.
>
> My goal is: show a list of all product with the Count, like in SQL when we
> use Group By...
>
> What's my error?
>
> T.·.F.·.A.·. S+F
> *Fellipe Henrique P. Soares*
>
> e-mail: > echo "lkrrovknFmsgor4ius" | perl -pe \
> 's/(.)/chr(ord($1)-2*3)/ge'
> *Fedora Ambassador: https://fedoraproject.org/wiki/User:Fellipeh
> *
> *Blog: *http:www.fellipeh.eti.br
> *GitHub: https://github.com/fellipeh *
> *Twitter: @fh_bash*
>
> --
> 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 http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/CAF1jwZGhgy-daV0v70OTTR46%3Diq4TVZhGfXO1DEiyGmivxKVtg%40mail.gmail.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAByqUgj1pJ-Z5fyR2GF%2BM1UsHfVQv0W1EyB%3Dkv6-oxVb2qwHeg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Form to login

2015-11-05 Thread Dariusz Mysior
Thank's I have it!

W dniu środa, 4 listopada 2015 06:51:02 UTC+1 użytkownik Dariusz Mysior 
napisał:
>
> I try do login view and I find it on 
>
> https://docs.djangoproject.com/en/1.8/topics/auth/default/
>
> from django.contrib.auth import authenticate, login
>
> def my_view(request):
> username = request.POST['username']
> password = request.POST['password']
> user = authenticate(username=username, password=password)
> if user is not None:
> if user.is_active:
> login(request, user)
> # Redirect to a success page.
> else:
> # Return a 'disabled account' error message
> ...
> else:
> # Return an 'invalid login' error message.
> ...
>
>
>
> to give request.POST username and password and username I must create my 
> own form or maybe Django have that form ready? I use Django 1.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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/e8038d21-9ad5-4e52-b5af-c9fa78f44681%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: update_or_create() always creates (or recreates)

2015-11-05 Thread Carsten Fuchs

Hi Yunti,

Am 05.11.2015 um 18:19 schrieb Yunti:

I have tried to use the update_or_create() method assuming that it would 
either, create
a new entry in the db if it found none or update an existing one if it found 
one and had
differences to the defaults passed in  - or wouldn't update if there was no 
difference.


A note about the last statement: If a Supplier object has the same unique_id, and all 
other fields (in `defaults`) are the same as well, logically there is no difference 
between updating and not updating – the result is the same.



  However it just seemed to recreate entries each time even if there were no 
changes.


Have you checked? How?
In your create_or_update_if_diff() you seem to try to re-invent update_or_create(), but 
have you actually examined the results of the


supplier, created = Supplier.objects.update_or_create(...)

call?


I think the issue was that I wanted to:
1)  get an entry if all fields were the same,


update_or_create() updates an object with the given kwargs, the match is not made 
against *all* fields (i.e. for the match the fields in `defaults` are not accounted for).



2) or create a new entry if it didn't find an existing entry with the unique_id
3) or if there was an entry with the same unique_id, update that entry with 
remaining
fields.


update_or_create() should achieve this. It's hard to tell more without additional 
information, but 
https://docs.djangoproject.com/en/1.8/ref/models/querysets/#update-or-create explains 
the function well, including how it works. If you work through this in small steps, 
check examples and their (intermediate) results, you should be able to find what the 
original problem was.


Best regards,
Carsten

--
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/563BB657.7050209%40cafu.de.
For more options, visit https://groups.google.com/d/optout.


Re: How do I relate two tables using field name instead of id?

2015-11-05 Thread Jani Tiainen
You need to set few additional attributes in your foreign key.

First you have to use db_column='', and to_field=''

db_column value would be column name in your table that holds foreign key.
I guess this would be 'name2' in your model that reflects table2

to_field would be reference in field in a model that reflects table1 db
column name1

So as a simplified example:

class MyModel1(models.Model):
name1 = model.CharField(max_length=123)

class Meta:
db_table = 'table1'

class MyModel2(models.Model):
name2 = model.ForeignKey('myapp.MyModel1', db_column='name2',
to_field='name1')

class Meta:
db_table = 'table1'

Hope that helps.


On Thu, Nov 5, 2015 at 6:12 PM, frocco  wrote:

> Thank you
>
> On Wednesday, November 4, 2015 at 11:19:40 AM UTC-5, frocco wrote:
>>
>> Hello,
>>
>> I have two existing tables
>> table1 has name1
>>
>> table2 has name2
>>
>> when I edit table2 in admin, I want a dropdownbox that shows values from
>> table1 using name1
>> both fields are character
>>
>> I cannot change the design, porting from msaccess
>>
>> thanks
>>
>> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/f42b087f-dffe-42df-994b-22e9028dd4c7%40googlegroups.com
> 
> .
>
> For more options, visit https://groups.google.com/d/optout.
>



-- 
Jani Tiainen

- Well planned is half done, and a half done has been sufficient before...

-- 
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAHn91ofvaaSWR-VPd9%3Dppc%3DOuM4Huo38Hf4zfb%2B-LmDcX0biYQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Locking / serializing access to one element in database

2015-11-05 Thread Carsten Fuchs

Hi Collin,

Am 05.11.2015 um 16:36 schrieb Collin Anderson:

If you're just updating one field, this _might_ work for you:


Why just one?



|
try:
TestMonthModel.objects.create(jahr=Jahr,monat=Monat)# create() uses 
force_insert.
exceptIntegrityError:
pass  # It already exists. No Problem.
# ... calculate some things.
TestMonthModel.objects.filter(jahr=Jahr,monat=Monat).update(value=new_value)
|


It's a nice idea, and I'll have to think more about it, but I guess that while this 
forces two parallel accesses to work with the same single instance, they can still both 
enter the calculation step, whose side effects may be hard to foresee in this context. 
Both will eventually also update the instance at the end, possibly with different 
results…  I'll have to think more about this.  ;-)


Best regards,
Carsten

--
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/563BBF7A.50506%40cafu.de.
For more options, visit https://groups.google.com/d/optout.


Re: can I write Django a client consuming RESTfull api from elsewhere

2015-11-05 Thread Jani Tiainen
Well your workflow would be following steps roughly:

1) End user requests URL from your Django site
2) Django router URL to a view
3) View code opens remote connection to RESTful service somewhere on the web
4) View code receive response from service
5) Data is processed
6) Data is rendered to end user

Now there is problem in step 3 and 4. That part may take long time
(minutes), what happens if service is down? Request will fail. Now what
happens at end user part? Browser will be waiting for response. Which in
turn connects to a frontend webserver which actually blocks either thread
or process. Now you hit second problem, what if you run for example 20
threads/processes in total. What happens when 21st request is coming in?
Well end user can't access your site at all because it's waiting for 20
older responses to come up.

That's why other people are suggesting that you don't request restful
service (unless you really can guarantee that it's fast) from view code but
do processing outside your web app. Like using background task to retrieve
data in timely manner and store it locally, or actually read that data
directly from the restful service without involving a django view.


If you could describe more of your use case, what data, what nature, why
you want to access it from a view we could give you a more specific help.


On Thu, Nov 5, 2015 at 3:31 AM, kk  wrote:

>
>
>
> On Wednesday 04 November 2015 10:43 PM, Avraham Serour wrote:
>
>> the question is why, why would you want to store a global connection for
>> a REST server?
>> keep in mind that you would be making HTTP requests, meaning even that
>> you had a global variable holding the connection it would just open and
>> close each tie you make a request.
>>
>
> No, I am not talking about the REST server.
> The REST server is a totally different service and I am just consuming it
> through Django views.
> So I have to use a client connection object such as Python request
> So I want to keep it as global, so that all views can access it from a
> single location, instead of creating a client request instance for every
> view on every call.
>
>
> Happy hacking.
> Krishnakant.
>
> --
> 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 http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/563AB16E.9060604%40gmail.com
> .
>
> For more options, visit https://groups.google.com/d/optout.
>



-- 
Jani Tiainen

- Well planned is half done, and a half done has been sufficient before...

-- 
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAHn91ocG3m3VaMKEE2ycamiFX4H6E%2BpiphXgegJyR63qneW12A%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Prefetch object with to_attr set to the same name as the field triggers rows deletions

2015-11-05 Thread Simon Charette
Bonsoir Michele,

I'll try to explain what happens here with a simplified model definition 
assuming you are using Django 1.8. I used a GenericRelation like your 
provided example but this issue can be triggered for about any M2M 
relationship.

Given the following models:

from django.db import models
from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation
)
from django.contrib.contenttypes.models import ContentType

class TaggedItem(models.Model):
tag = models.SlugField()
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')

class Bookmark(models.Model):
url = models.URLField()
tags = GenericRelation(TaggedItem)

Assigning directly to a Bookmark instance tags attribute (a 
ReverseGenericRelatedObjectsDescriptor 
instance) will result in a delete query followed by multiple insert or 
update queries 

 
depending on whether they exist or not. For example:

>>> b = Bookmark.objects.create(url='www.djangoproject.com')
>>> # The following line will result in the following queries:
>>> # 1) DELETE FROM bookmark WHERE id = b.id;
>>> # 2) INSERT INTO taggeditem ...;
>>> # 3) INSERT INTO taggeditem ...;
>>> b.tags = [TaggedItem(tag='Python'), TaggedItem(tag='Web')]

Note that the DELETE query is not run as of 1.9 since Django now performs 
updates in 'bulk' instead (that is comparing the existing relationship with 
this specified value and only perform the required insert/update).

Now, as documented, when you specify a `to_attr` Django simply uses 
`setattr()` onder de motorkap and ends up triggering the code path 
described above if the specified attribute happens to be a reverse 
relationship descriptor. Note that is behavior will be deprecated in Django 
1.10 and removed in Django 2.0. 


I have to say I'm unsure how we should proceed here. I guess I would favor 
raising a ValueError if the model the list of prefetched objects will be 
attached to has a reverse descriptor for the specified `to_attr` at least 
until this behavior is deprecated since it looks like a major footgun to me.

I guess we should move the discussion to the development mailing list 
 to gather 
feedback.

Au plaisir,
Simon

Le jeudi 5 novembre 2015 17:17:04 UTC+1, mccc a écrit :
>
> Hello Simon,
>
> I'm going to paste a trimmed-down version of the involved classes:
>
> class CeleryTask(models.Model):
> celery_task_id = models.CharField(max_length=50, primary_key=True)
> task_type = models.ForeignKey(ContentType)
> task_id = models.PositiveIntegerField()
> task = GenericForeignKey('task_type', 'task_id')
>
> class AccountManagementTask(models.Model):
> account = models.ForeignKey(Account, null=True, editable=False)
> task_content_type = models.ForeignKey(ContentType)
> task_content_id = models.PositiveIntegerField()
> task_content = GenericForeignKey('task_content_type', 
> 'task_content_id')
> celery_task = GenericRelation(CeleryTask, 
> content_type_field='task_type', object_id_field='task_id',
>   
> related_query_name='account_management_tasks')
>
> (the task_content thing is involved in a follow-up question that will be 
> asked in a short while)
>
> This is the code triggering the weirdness:
>
> previous_tasks = 
> AccountManagementTask.objects.filter(account=account)\
> .prefetch_related(
> Prefetch('celery_task',
>  to_attr='celery_task'))\
> .prefetch_related(
> Prefetch('task_content',
>  to_attr='task_content'))\
> .annotate(created_on=F('celery_task__created_on'))\
>
> Immediately after that, the QuerySet is sent off to a simple DRF 
> serializer - which doesn't even touch the issue since the relevant piece of 
> information is annotated:
>
> class AccountManagementTaskSerializer(serializers.ModelSerializer):
> def to_representation(self, instance):
> return {'id': instance.pk,
> 'created_on': instance.created_on,
> 'date_from': instance.task_content.date_from,
> 'date_to': instance.task_content.date_to}
>
> class Meta:
> model = AccountManagementTask
>
>
> Now the follow-up, that you might already have guessed: if I *do* use the 
> same name for following the GenericForeignKey relation (task_content), the 
> content of the relationship does not get deleted(no surprise there..?) and 
> I can go with my naïve serialization over there, while if I specify a 
> different to_attr name I get back a list and I have to deal differently 
> with that.
> How do 

django admin - You don't have permission to edit anything

2015-11-05 Thread Benjamin Smith
I followed the django doc

on creating a custom user model while extending the model itself with my
own fields. So it became like this:

class MyUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=255, unique=True)
first_name = models.CharField(max_length=35)
last_name = models.CharField(max_length=35)
username = models.CharField(max_length=70, unique=True)
date_of_birth = models.DateField()
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)

@property
def is_staff(self):
return self.is_admin

def get_full_name(self):
return ('%s %s') % (self.first_name, self.last_name)

def get_short_name(self):
return self.username

objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name', 'username',
'date_of_birth']

And its manager to be:

class MyUserManager(BaseUserManager):
def create_user(self, email, first_name, last_name, username,
date_of_birth, password=None):
if not email:
raise ValueError('User must have an email address')

user = self.model(
email=self.normalize_email(email),
first_name=first_name,
last_name=last_name,
username=username,
date_of_birth=date_of_birth,
)

user.set_password(password)
user.save(using=self._db)
return user

def create_superuser(self, email, first_name, last_name, username,
date_of_birth, password):
user = self.create_user(
email,
first_name=first_name,
last_name=last_name,
username=username,
date_of_birth=date_of_birth,
password=password
)
user.is_admin = True
user.save(using=self._db)
return user

However, after I created the superuser while syncdb, when I login to the
admin panel, there is nothing to do. It displays:

* You don't have permission to edit anything.*

I saw some other post with the same problem and most of them suggested to
add *admin.autodiscover()* in the urls.py. But even this didn't help me.

This is the admin.py:

class MyUserAdmin(UserAdmin):
form = UserChangeForm
add_form = UserCreationForm

list_display = ('email', 'first_name', 'last_name', 'username',
'date_of_birth', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': (('first_name', 'last_name'),
'username', 'date_of_birth')}),
('Permissions', {'fields': ('is_admin',)}),
)

add_fieldsets = (
(None, {
'classes': ('Wide',),
'fields': ('email', 'first_name', 'last_name', 'username',
'date_of_birth')
}),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()


admin.site.register(MyUser, MyUserAdmin)

What am I doing wrong here? Please help me how to solve this problem. Thank
you.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAM4YLW%2B3cBT8bLQL%2Bo1%3Dy6ZJ_7R8xUHvMd8AwfP_mxn%3DPRN6BA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: Best practices for writing functional tests to exercise forms?

2015-11-05 Thread Carl Meyer
Hi Tim,

On 11/04/2015 05:36 PM, Tim Chase wrote:
> Beginning a new project, I'd like to include functional testing in
> addition to my unit tests.  What are recommended best practices for
> exercising form-classes?  I was hoping to do something like
> 
>   c = django.test.Client()
>   results = c.get(page_url)
>   frm = SomeForm()
>   # pseudo-code for desired functional testing follows
>   self.assertFormIn(frm, results) # check the form is used
>   frm["name"] = "Pat Smith"
>   frm["email"] = "psm...@example.com"
>   results = c.post(page_url, frm) # submit the filled-out form
>   # check results for error messages and/or success here
> 
> Is there some piece of Django that I've missed that would facilitate
> higher-level tests like this?

I recommend the WebTest package [1], along with django-webtest [2] to
adapt it for use with Django.

It would replace your use of the Django test client (which isn't a
problem; it's a replacement with more features); you'd create and use a
WebTest client instead. It will parse the HTML of a response and pull
out any forms, allowing you to programmatically "fill out" the form
fields present in the markup and submit them. This allows for
integration tests that will catch errors like forgetting to include a
formset's management form in your template.

I use WebTest rather than the Django test client for all my
request/response integration tests.

Carl

[1] https://pypi.python.org/pypi/WebTest
[2] https://pypi.python.org/pypi/django-webtest

-- 
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/563BEFC5.4050508%40oddbird.net.
For more options, visit https://groups.google.com/d/optout.


signature.asc
Description: OpenPGP digital signature


Re: django admin - You don't have permission to edit anything

2015-11-05 Thread Andreas Kuhne
Hi,

You don't have permissions to edit anything, because you haven't created a
superuser.

The superuser in django has a property that is called "is_superuser" and
should be set to True. If you don't have that property (and your
createsuperuser sets some other property), you will have the same rights as
everyone else, which is nothing to begin with. You can add rights to the
user be adding the permissions you want, or by setting the is_superuser
property to True.

Check the documentation for the django admin site here:
https://docs.djangoproject.com/en/1.8/ref/contrib/admin/

Regards,

Andréas

2015-11-06 0:15 GMT+01:00 Benjamin Smith :

> I followed the django doc
> 
> on creating a custom user model while extending the model itself with my
> own fields. So it became like this:
>
> class MyUser(AbstractBaseUser, PermissionsMixin):
> email = models.EmailField(max_length=255, unique=True)
> first_name = models.CharField(max_length=35)
> last_name = models.CharField(max_length=35)
> username = models.CharField(max_length=70, unique=True)
> date_of_birth = models.DateField()
> is_active = models.BooleanField(default=True)
> is_admin = models.BooleanField(default=False)
>
> @property
> def is_staff(self):
> return self.is_admin
>
> def get_full_name(self):
> return ('%s %s') % (self.first_name, self.last_name)
>
> def get_short_name(self):
> return self.username
>
> objects = MyUserManager()
> USERNAME_FIELD = 'email'
> REQUIRED_FIELDS = ['first_name', 'last_name', 'username',
> 'date_of_birth']
>
> And its manager to be:
>
> class MyUserManager(BaseUserManager):
> def create_user(self, email, first_name, last_name, username,
> date_of_birth, password=None):
> if not email:
> raise ValueError('User must have an email address')
>
> user = self.model(
> email=self.normalize_email(email),
> first_name=first_name,
> last_name=last_name,
> username=username,
> date_of_birth=date_of_birth,
> )
>
> user.set_password(password)
> user.save(using=self._db)
> return user
>
> def create_superuser(self, email, first_name, last_name, username,
> date_of_birth, password):
> user = self.create_user(
> email,
> first_name=first_name,
> last_name=last_name,
> username=username,
> date_of_birth=date_of_birth,
> password=password
> )
> user.is_admin = True
> user.save(using=self._db)
> return user
>
> However, after I created the superuser while syncdb, when I login to the
> admin panel, there is nothing to do. It displays:
>
> * You don't have permission to edit anything.*
>
> I saw some other post with the same problem and most of them suggested to
> add *admin.autodiscover()* in the urls.py. But even this didn't help me.
>
> This is the admin.py:
>
> class MyUserAdmin(UserAdmin):
> form = UserChangeForm
> add_form = UserCreationForm
>
> list_display = ('email', 'first_name', 'last_name', 'username',
> 'date_of_birth', 'is_admin')
> list_filter = ('is_admin',)
> fieldsets = (
> (None, {'fields': ('email', 'password')}),
> ('Personal info', {'fields': (('first_name', 'last_name'),
> 'username', 'date_of_birth')}),
> ('Permissions', {'fields': ('is_admin',)}),
> )
>
> add_fieldsets = (
> (None, {
> 'classes': ('Wide',),
> 'fields': ('email', 'first_name', 'last_name', 'username',
> 'date_of_birth')
> }),
> )
> search_fields = ('email',)
> ordering = ('email',)
> filter_horizontal = ()
>
>
> admin.site.register(MyUser, MyUserAdmin)
>
> What am I doing wrong here? Please help me how to solve this problem.
> Thank you.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/CAM4YLW%2B3cBT8bLQL%2Bo1%3Dy6ZJ_7R8xUHvMd8AwfP_mxn%3DPRN6BA%40mail.gmail.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>

-- 

Re: Custom QuerySet and __date field lookup

2015-11-05 Thread aprzywecki
You were right. Wrong virtualenv...*facepalm*

-- 
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 http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/30aff294-aebf-46e9-a231-f7e902af%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.