Re: Django Dashboard

2013-07-30 Thread Simon Charette
I'd suggest you take a look at django-admin-tools . Le mardi 30 juillet 2013 14:09:00 UTC-4, Martin Marrese a écrit : > > Hi, > > I'm looking for a Django Dashboard to implement on an existing app. A > colleague recommended Dashing (1), bu

Re: Ordering a queryset on a reverse foreign key's attribute

2013-08-01 Thread Simon Charette
>From a quick look I'd also expect `order_by('-children__date')` to work. Can you provide the generated SQL query and some results? Le jeudi 1 août 2013 09:58:25 UTC-4, Daniele Procida a écrit : > > I have an Event model: > > class Event(Model): > parent = models.ForeignKey('self',

Re: Dynamic increasing choices object

2013-08-21 Thread Simon Charette
Not really Django related but you can achieve it by doing the following: WEIGHTS = tuple( (weight, "%dkg" % weight) for weight in range(40, 251) ) Le mercredi 21 août 2013 18:16:59 UTC-4, Gerd Koetje a écrit : > > > How do i automatic increase this from 40 tot 250kg > its a choices field insi

Re: Django ORM: default value from sql query

2013-08-21 Thread Simon Charette
You can achieve this by setting a callable default value [1] on you field: class MyModel(models.Model): count = models.PositiveIntegerField(default=lambda:MyModel.objects.count()) [1] https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.default Le mercredi 21 août

Re: How to handle exceptions in middleware?

2013-08-22 Thread Simon Charette
`Middleware.process_view ` can either return `None` or an `HttpResponse object [1] thus you could wrap your `AuthManager.ValidateToken(Token)` call into a try/catch block and return a response early if the service is unavailable. [1] https://docs.djangoproject.com/en/dev/topics/http/middleware

Re: Remove validation on a field if its empty

2013-09-05 Thread Simon Charette
Set `required=False`on your `password` field`. If you want to make sure it's only non-mandatory when the user exists override your `UserForm.__init__` this way: class UserForm(forms.ModelForm): password =

Re: Aggregation and count - only counting certain related models? (i.e. adding a filter on the count)

2013-09-24 Thread Simon Charette
Unfortunately the Django ORM's doesn't support conditionnal aggregates . Le mardi 24 septembre 2013 16:50:51 UTC-4, Victor Hooi a écrit : > > Hi, > > I'm trying to use aggregation to count the number of "likes" on an item. > > The likes for an item are

Re: Aggregation and count - only counting certain related models? (i.e. adding a filter on the count)

2013-09-24 Thread Simon Charette
Unfortunately the Django ORM's doesn't support conditionnal aggregates . Le mardi 24 septembre 2013 16:50:51 UTC-4, Victor Hooi a écrit : > > Hi, > > I'm trying to use aggregation to count the number of "likes" on an item. > > The likes for an item are

Re: Restrict access to user-uploaded files to authorized users

2013-09-24 Thread Simon Charette
I'm not aware of any solution except serving from Django if you can't install Apache plugins. If you're really stuck with serving large files from Django I'd recommend you streamthe content of the fi

Re: Aggregation and count - only counting certain related models? (i.e. adding a filter on the count)

2013-09-25 Thread Simon Charette
013 04:41:37 UTC-4, Daniel Roseman a écrit : > > On Tuesday, 24 September 2013 21:58:44 UTC+1, Simon Charette wrote: > >> Unfortunately the Django ORM's doesn't support conditionnal >> aggregates<https://code.djangoproject.com/ticket/11305> >> . >>

Re: What's the difference between assertIn and assertContains?

2013-10-28 Thread Simon Charette
assertContains performs additional assertion such as the status code of the request and provides a way to perform comparison based on HTML semantic instead of character-by-character equality. Under the hood it also handles streaming and deferred response gracefully. I suggest you take a look at th

Re: multiple databases and syncdb problem

2013-10-29 Thread Simon Charette
syncdb defaults to syncing the 'default' database when no --database is specified . Try specifying which database to synchronize, with the --database=inserv flag in your case. Le mardi 29 octobre 2013 16:52:

Re: handling field DoesNotExist error within a model class

2013-11-01 Thread Simon Charette
Use the `DateTypeModelClass.DoesNotExist` exception. By the way, make sure you use `select_related()` if you want to use `__unicode__` on those instances or it will results in 1 + N * 6 queries where N = `Channel.objects.count()`. Le vendredi 1 novembre 2013 12:46:21 UTC-4, Rick Shory a écrit :

Re: Django not installed, but clearly installed ??

2013-11-14 Thread Simon Charette
It looks like pip failed to install django. Look into pip.log for more details. Le jeudi 14 novembre 2013 23:28:51 UTC-5, icevermin a écrit : > > Hello, > > I installed Django using pip. It seems as if it was installed just fine. > However... > > cmd --> python --> import django I get an error !

Re: override_settings decoration of non-test class function

2013-11-18 Thread Simon Charette
Hi Daniel! Prior to Django 1.6 (552a90b444) override_settings couldn't be safely nested . Could you try running your example against this version and report back her

Re: Prefetching a single item

2015-03-02 Thread Simon Charette
Can your seats be part of multiple trains? Is there a reason you defined a ManyToMany from Train to Seat instead of a ForeignKey from Seat to Train? If your schema was defined as the latter the following could probably work (given you only want the first Seat of each Train object): trains = T

Re: Using proxy kind of Table in Admin Interface

2015-03-02 Thread Simon Charette
Hi Rootz, Unfortunately there's a long standing ticket to solve inconsistency with permissions for proxy models so your chosen approach won't work until this is fixed. Simon Le lundi 2 mars 2015 11:16:36 UTC-5, Rootz a écrit : > > Question. > How w

Re: Query optimization - From 3 queries to 2

2015-03-02 Thread Simon Charette
Hi Humberto, The following should do: Provider.objects.prefetch_related( Prefetch('service_types', ServiceType.objects.select_related('service_type_category')) ) P.S. Next time you post a question try to remove data unrelated to your issue from your example (e.g `countries` and `user` refe

Re: Can the new `Prefetch` solve my problem?

2015-03-02 Thread Simon Charette
Hi cool-RR, The following should do: filtered_chairs = Chair.objects.filter(some_other_lookup=whatever) desks = Desk.objects.prefetch_related( PrefetchRelated('chairs', filtered_chairs, to_attr='filered_chairs'), PrefetchRelated('nearby_chairs', filtered_chairs, to_attr='filtered_nearby_

Re: Custom lookup field for text comparison in Django 1.6

2015-03-04 Thread Simon Charette
Hi Jorgue, As you already know there's no officially supported API to create custom lookups in Django < 1.7 However it's possible to get something working by monkey patching WhereNode.make_atom. Here's an example GIST that expose a dec

Re: Prefetching a single item

2015-03-04 Thread Simon Charette
which has its own issues. (And can't be > used for any number of items other than 1 in this case.) > > On Tue, Mar 3, 2015 at 7:15 AM, Simon Charette > wrote: > >> Can your seats be part of multiple trains? >> >> Is there a reason you defined a ManyToMany from Tr

Re: Sharing templates across multiple projects

2015-03-06 Thread Simon Charette
Hi John, I suggest you put the templates you want to share in a location accessible by your multiple projects and add this directory to your TEMPLATE_DIRS setting. Make sure you have 'django.template.loaders.filesy

Re: Django 1.8 ImportError: No module named formtools

2015-03-10 Thread Simon Charette
Hi Neto, Here's an excerpt from the Django 1.8 release note : The formtools contrib app has been moved into a separate package. > *django.contrib.formtools* itself has been removed. The docs provide > mig

Re: Django 1.8 post_save without recursion

2015-03-13 Thread Simon Charette
I don't think there's best a way of doing it but in your specific case the following should do: @receiver(post_save, sender=Person) def do(instance, update_fields, *args, **kwargs): if update_fields == {'ok'}: return instance.ok = True instance.save(update_fields={'ok'}) Simo

Re: Need your advices to optimize when annotate foreign key

2015-03-16 Thread Simon Charette
Hi Sardor, Are you using PostgreSQL? Simon Le lundi 16 mars 2015 05:19:38 UTC-4, Sardor Muminov a écrit : > > > > Hello there, > > > I am trying to perform aggregation from all objects which have one foreign > key. > > > These are my models: > > ... > > class Post(models.Model): > id = mode

Re: Need your advices to optimize when annotate foreign key

2015-03-16 Thread Simon Charette
to mention it. I am using PostgreSQL 9.3.6 > > Now I am implementing Chenxiong Qi's suggestion. > > Do you have any idea? > > > On Tuesday, March 17, 2015 at 12:25:00 AM UTC+9, Simon Charette wrote: >> >> Hi Sardor, >> >> Are you using PostgreSQL? &g

Re: Django ReverseSingleRelatedObjectDescriptor.__set__ ValueError

2015-03-18 Thread Simon Charette
Hi Bradford, You must retrieve the ContentType model from the `apps` instead of importing it just like the other models you're using in your forwards function. ContentType = apps.get_model("contenttypes", "ContentType") The reason why you're getting such a strange exception is because you're

Re: Django project for multiple clients

2015-03-26 Thread Simon Charette
This concept is called multi-tenancy. I suggest you have a look at the django-tenant-schema application which isolate each tenant in it's own PostgreSQL schema. You could also build you own solution using a middleware and a database rout

Re: QueryDict and its .dict() method - why does it do that?

2015-03-27 Thread Simon Charette
Hi Gabriel, One thing I dislike about how PHP/Rail deal with this is the fact they expose an easy way to shoot yourself in the foot. e.g. PHP Your code expects $_GET['foo'] to be an array() but the querystring is missing the trailing "[]" (?foo=bar) and crash. This also open a door for subtle

Re: Jinja2 with Django 1.8c1 & cannot import name 'Environment'

2015-03-28 Thread Simon Charette
Hi Rolf, Since your `jinja2.py` file sits before your installed `jinja2` package directory in your PYTHONPATH you end up trying to import `Environement` from your the module you're defining and not the installed `jinja2` module. Rename your jinja2.py file something else and things should be wor

Re: Jinja2 with Django 1.8c1 & cannot import name 'Environment'

2015-03-29 Thread Simon Charette
Hi Rolf, Did you install jinja2 in your python environment (I assumed /www/pbs-venv was a virtualenv)? What does /www/pbs-venv/bin/pip --freeze outputs? Simon Le dimanche 29 mars 2015 14:53:49 UTC-4, Rolf Brudeseth a écrit : > > >> Rename your jinja2

Re: Jinja2 with Django 1.8c1 & cannot import name 'Environment'

2015-03-29 Thread Simon Charette
Hi Rolf, Django 1.8+ adds built-in support but doesn't ship with Jinja2, the same way it has built-in support for PostgreSQL but doesn't ship the psycopg2 package. You must install it in your environment just like you did with the Django package. Simon Le dimanche 29 mars 2015 16:40:33 UTC-

Re: Jinja2 with Django 1.8c1 & cannot import name 'Environment'

2015-03-30 Thread Simon Charette
You're welcome Rolf. Your question lead an initiative by Tim to clarify Jinja2 needs to be installed . Cheers, Simon Le lundi 30 mars 2015 19:47:46 UTC-4, Rolf Brudeseth a écrit : > > >> >> Django 1.8+ adds built-in support but doesn't ship with Jinja

Re: Accessing to my user

2015-04-02 Thread Simon Charette
Hi! Personna.objects.get(user__username='foo') should do. Simon Le jeudi 2 avril 2015 11:24:48 UTC-4, somen...@gmail.com a écrit : > > I have this > class Persona(models.Model):7 > >"""Person class:8 >

Re: "The outermost 'atomic' block cannot use savepoint = False when autocommit is off." error after upgrading to Django 1.8

2015-04-02 Thread Simon Charette
Hi Matt, I think it would be preferable to use atomic() here. >From reading the documentation it looks like you might already be in a transaction when calling `set_autocommit` but it's hard to tell without the full traceback. Wha

Re: Context manager to pick which database to use?

2015-04-28 Thread Simon Charette
Hi Peter, I think you could use database routers to declare the default behavior and rely on the using() queryset method for the exceptional case? I'm afraid the introduction of a context manag

Re: Django model inheritance: create sub-instance of existing instance (downcast)?

2015-05-13 Thread Simon Charette
Hi Guettli, This isn't part of the public API but you could rely on how Django loads fixture internally . parent = Restaurant.objects.get(name__iexact="Bob's Place").parent

Re: Improve Performance in Admin ManyToMany

2015-05-14 Thread Simon Charette
It's a bit hard to tell without your model definition and the executed queries but is it possible that the string representation method (__str__, __unicode__) of one the models referenced by a M2M access another related model during construction? e.g. from django.db import models class Foo(mo

Re: Improve Performance in Admin ManyToMany

2015-05-14 Thread Simon Charette
I meant if db_field.name == 'bars': Sorry for noise... Le jeudi 14 mai 2015 11:15:49 UTC-4, Simon Charette a écrit : > > The last example should read: > > if db_field.name == 'baz': > > > > Le jeudi 14 mai 2015 11:14:24 UTC-4, Simon Charette a écrit

Re: Improve Performance in Admin ManyToMany

2015-05-14 Thread Simon Charette
The last example should read: if db_field.name == 'baz': Le jeudi 14 mai 2015 11:14:24 UTC-4, Simon Charette a écrit : > > It's a bit hard to tell without your model definition and the executed > queries but is it possible that the string representation method (__str__

Re: select_related() / prefetch_related() and sharding

2015-05-21 Thread Simon Charette
Small correction, prefetch_related doesn't issue any JOIN unless a is query with a select_related is specified with a Prefetch object. Simon Le jeudi 21 mai 2015 17:53:30 UTC-4, Ash Christopher a écrit : > > Hi David, > > *select_related* does a JOIN under the hood, and you can't do > cross-dat

Re: Reduce number of calls to database

2015-06-02 Thread Simon Charette
Hi Cherie, A `id__in` queryset lookup should issue a single query. levels = Level.objects.filter(id__in=level_ids) Cheers, Simon Le mardi 2 juin 2015 11:42:19 UTC-4, Cherie Pun a écrit : > > Hi, > > I am new to Django and I am performing some iteration on a queryset. When > I use django_debug_

Re: Core error in showing records?

2015-06-16 Thread Simon Charette
Hi MikeKJ, I suppose the ModelAdmin subclass in use here has a list_display method marked as boolean that return an unexpected value

Re: custom model fields with to_python()/from_db_value() for different django version...

2015-06-17 Thread Simon Charette
Hi Jens, I haven't tested your alternative but it looks like it would work. I prefer the explicit check against django.VERSION since it makes it easy to search for dead code branch when dropping support a version of Django. Simon Le mercredi 17 juin 2015 10:59:27 UTC-4, Jens Diemer a écrit : >

Re: Get the name of the method in QuerySetAPI

2015-06-17 Thread Simon Charette
Hi Utkarsh, I guess you could define a __getattribute__[1] method on your manager? from django.db import models class MyManager(models.Manager): def __getattribute__(self, name): print(name) return super(models.Manager, self).__getattribute__(name) Simon [1] https://docs.p

Re: Django ORM generate inefficient SQL

2014-08-26 Thread Simon Charette
This is already tracked in #19259 . Le jeudi 21 août 2014 06:49:41 UTC-4, Alex Lebedev a écrit : > > Hi, guys! > > I have encountered a problem. When I use the following code in django > shell: > > from django.contrib.auth.models import Group >

Re: Django ORM generate inefficient SQL

2014-08-28 Thread Simon Charette
ase backend (I tested it on PostgreSQL and MySQL) > > среда, 27 августа 2014 г., 12:37:00 UTC+6 пользователь Simon Charette > написал: >> >> This is already tracked in #19259 >> <https://code.djangoproject.com/ticket/19259>. >> >> Le jeudi 21 août 2

Re: Django ORM generate inefficient SQL

2014-08-28 Thread Simon Charette
statement, or would you like to do it yourself? > > четверг, 28 августа 2014 г., 20:36:19 UTC+6 пользователь Simon Charette > написал: >> >> The issue on MySQL should be tracked in another ticket I guess -- you're >> right that it should be able to GROUP only b

Re: related_query_name - what is it?

2014-08-29 Thread Simon Charette
The documentation is wrong, it should be: # That's now the name of the reverse filter Article.objects.*filter*(tag__name="important") I'll commit a documentation admonition and give you credit. Thanks for spotting this! Le vendredi 29 août 2014 22:27:38 UTC-4, Petr Glotov a écrit : > > Correcti

Re: Best way to batch select unique ids out of pool for sequences

2014-09-04 Thread Simon Charette
The following should do: Item.objects.bulk_create([ Item(pool_cd=pool_cd.unique_code) for pool_cd in pool_cds ]) Le jeudi 4 septembre 2014 12:44:08 UTC-4, James P a écrit : > > I forgot to include the code where I set the pool codes to NOTFREE, here > is the whole snippet. > > code_count

Re: Preventing race conditions when submitting forms

2014-11-25 Thread Simon Charette
Hi Paul, You might want to take a look at the third party packages listed under the *concurrency* category . I've used django-concurrency in the past and it worked well for me. Simon Le ma

Re: Foreign Key Deletion Problem

2014-11-25 Thread Simon Charette
Hi Jann, I think you'll need to write a custom deletion handler for this. The following should work: from django.db import models class SetNull(object): """Deletion handler that behaves like `SET_NULL` but also takes a list of extra fields to NULLify.""" def __init__(self, *fields

Re: Preventing race conditions when submitting forms

2014-11-25 Thread Simon Charette
I can't think of a generic way of solving conflict resolution. I'd say it's highly application specific. Le mardi 25 novembre 2014 15:06:53 UTC-5, Paul Johnston a écrit : > > Tim, Simon, > > Thanks for the responses. Looks like django-concurrency is a good fit, and > it works the way Tim suggest

Re: ModelAdmin.has_change_permission gives 403

2014-11-26 Thread Simon Charette
In order to make a model admin read only I suggest you make sure ` get_readonly_fields() ` return all of them. from django.contrib.admin.utils import flatten_fieldsets def get_readonl

Re: Query set append

2014-12-01 Thread Simon Charette
Try using a subquery for this: tableC_QuerySet = models.TableC.objects.filter( tableC_id__in=models.TableB.objects.filter(table_ID = ).values() ) Le lundi 1 décembre 2014 14:07:59 UTC-5, check@gmail.com a écrit : > > Hello > > I am very new to python and Django . I have a basic question

Re: How to get the class name of a ContentType in django

2013-11-29 Thread Simon Charette
Do you want to retrieve the class name of the model class associated with a content type? Le jeudi 28 novembre 2013 12:04:34 UTC-5, Aamu Padi a écrit : > > How do I get the class name in string of a ContentType? I tried it this > way, but it didn't worked out: > > class StreamItem(models.Model):

Re: View decorators before CSRF verification?

2013-12-15 Thread Simon Charette
Hi Dalton, > Is this something to be bothered about? This is a request for advice and discussion rather than debugging a particular problem. I think I would prefer if there were a way for Django to check for view decorator compliance first because I think a 405 response is more descriptive and

Re: Honest feedback

2014-01-31 Thread Simon Charette
Just wanted to add/correct two points. > That also means some of the warts are still there like the difficulty in > writing reusable apps, file based settings, multiple user profiles, that 30 > char username length on the contrib.auth.User model. > Django 1.5 ships with a configurable user

Re: Model validation across relationships

2014-03-23 Thread Simon Charette
I'd say that's exactly what you should use `Model.clean()` for. In this case you're *doing validation that requires access to more than a single field.* What sounds vague to you in the documentation? Le vendredi 21 mars 2014 19:43:07 UTC-4, Joshua Pokotilow a écrit : > > Given these models, wou

Re: Missing ORDER BY in subselect?

2014-04-16 Thread Simon Charette
I pretty sure this is related to #22434 . There's a patch on Github I'm actually reviewing and it's looking pretty good. If all goes well it should make it to Django 1.7. Le mercredi 16 avril 2014 15:16:0

Re: How to create Union in Django queryset

2014-04-17 Thread Simon Charette
I'm not sure this will work but you could try creating a VIEW on the database side that does the union there and access it through an un-managed model. CREATE VIEW *view_name* AS SELECT id, name FROM *a* UNION SELECT id, name FROM *b*; class C(models.Model): name = models.CharField()

Re: 3 table many to many relationship

2014-04-23 Thread Simon Charette
Django allows you to explicitly specify an intermediary model for many-to-many relationships with the `through` option. class A(models.Model): b_set = models.ManyToMany('B', related_name='a_

Re: Django explicit `order_by` by ForeignKey field

2014-04-25 Thread Simon Charette
The issue was referenced in #19195and it was suggested we add the ability to order by field name and not only by attribute name. I suggest you open a ticket for this and add a reference to it in #19195 .

Re: Django explicit `order_by` by ForeignKey field

2014-04-25 Thread Simon Charette
Actually the FieldError is not raised anymore in Django 1.7 (and master) and issuing a .order_by('group_id') is the equivalent of .order_by('group') which respect related model ordering if defined. I would argue we should seize the opportunity to provide a way of opting out of this default beha

Re: migrate command fails with foreign key to user model

2014-04-28 Thread Simon Charette
This is a release blocker for Django 1.7 which is being tracked in #22485 . Le lundi 28 avril 2014 04:54:32 UTC-4, Ryan a écrit : > > I have used django in the past, but not for some time. So the changes > surrounding the user models are new to me.

Re: Is it a django's bug or something mistaken,when I can't encode chinese characters in django environment?

2014-04-28 Thread Simon Charette
Maybe those API's expect you to pass them bytes and not text. Did you try encoding your subject and your body as 'utf-8' bytes (using .encode('utf-8'))? Simon Le lundi 28 avril 2014 23:00:03 UTC-4, jie.l...@gmail.com a écrit : > > > My environment is python3.3.4 django1.6.2,when I work on a dja

Re: django-mutant

2014-04-30 Thread Simon Charette
Hi Eddilbert, I'm the author of django-mutant. May I ask you what exactly you're trying to achieve with this application? Creating new field should be as simple as importing a field definition subclass from a contrib.* application. e.g. from mutant.contrib.text import CharFieldDefinition Cha

Re: Creating an object using Foreign Key for Users but filtered by group

2014-05-05 Thread Simon Charette
You could use the `ForeignKey.limit_choices_to` option : class Message(models.Model): moderator = models.ForeignKey(User, limit_choices_to={'groups__name': 'Moderator'}) user= models.

Re: Using IN clause with parameterized raw queries

2014-05-29 Thread Simon Charette
Did you try: cursor.execute("SELECT username FROM users WHERE username NOT IN (%s, %s, %s)", ['user_a', 'user_b', 'user_c']) Le jeudi 29 mai 2014 18:10:04 UTC-4, J Y a écrit : > > Let say I have this query I would like to execute: > > SELECT username FROM users WHERE username NOT IN ('user_a', '

Re: Strange query when using annotate and count

2017-11-23 Thread Simon Charette
Hello Cristiano, I understand your frustration but please avoid using the developer mailing list as a second tier support channel. I suggest you try the IRC #django channel if you need to want to get faster support. What's happening here is that annotate() really means "select this field" whil

Re: Strange query when using annotate and count

2017-11-23 Thread Simon Charette
that > wouldn't work since paginators accept only one query set for example and > internall uses it for both count and results. > > > > El viernes, 24 de noviembre de 2017, 0:05:29 (UTC-3), Simon Charette > escribió: >> >> Hello Cristiano, >> >>

Re: Strange query when using annotate and count

2017-11-24 Thread Simon Charette
gt; Even with these cases, if the annotated value is used later with a filter > query I can't really simply removed, but the sub queries and extra function > calls really doesn't make sense to be there when doing a count, so it seems > that all the options are quite bad and h

Re: Error on execute migration (create index) when set db_name with quoted string

2017-11-27 Thread Simon Charette
Hey Carlos, I believe the trailing quote truncation issue might be solved in the yet to be released 1.11.8[0][1] version. Could you confirm whether or not it's the case? You'll have to regenerate your migration. Best, Simon [0] https://github.com/django/django/commit/a35ab95ed4eec5c62fa19bdc

Re: Error on execute migration (create index) when set db_name with quoted string

2017-11-28 Thread Simon Charette
15, in migrate > state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, > fake_initial=fake_initial) > File > "/Users/cadu/Envs/dj28792/src/django/django/db/migrations/executor.py", > line 145, in _migrate_all_forwards > state = self.apply_migration(state, migration, fake=f

Re: Django 2.0 released

2017-12-03 Thread Simon Charette
> My mistake? My "requirements.txt" file did not mention package versions. You should definitely make sure to lock/freeze your requirements to prevent your application's behavior from changing under your feet. Best, Simon Le samedi 2 décembre 2017 15:02:55 UTC-5, Adler Neves a écrit : > > I gues

Re: RenameField with django 2.0: AttributeError: 'ManyToManyRel' object has no attribute 'field_name'

2017-12-04 Thread Simon Charette
Hello there, This looks like a regression in Django 2.0 caused by 095c1aaa[0]. Please file a new ticket mentioning it's a regression in Django 2.0 and mark it as a release blocker. [1] Thanks, Simon [0] https://github.com/django/django/commit/095c1aaa898bed40568009db836aa8434f1b983d [1] https:

Re: PRIMARY KEY in view PostgreSQL

2017-12-11 Thread Simon Charette
Hello Matthew, This should be fixed in Django 2.0 by daf2bd3efe53cbfc1c9fd00222b8315708023792[0]. I'd appreciate if you could chime in the related django-developer thread[1] to mention you were using an unmanaged model to query views as there was no consensus regarding whether or not the patch

Re: Many to Many fields and through table

2017-12-19 Thread Simon Charette
Hello Mark, The only downside I can think of is that you won't be able to create relationships from the m2m managers, you'll have to create the relationship directly instead. This isn't such a big issue if you plan on adding fields later to the intermediary model later on anyway. You can read mo

Re: ChoiceField avec valeur cochée par défaut

2018-03-01 Thread Simon Charette
Bonsoir Niche, Tu devrais être en mesure d'y arriver en t'assurant que le formulaire (Form) comprenant ce champ ait ta valeur ta valeur par défaut comme initial data. exemple class MyForm(forms.Form): field = ChoiceField(widget=widgets.RadioSelect, choices=['un', 'deux', 'trois']) form =

Re: how to do inner join using 3 tables

2018-03-08 Thread Simon Charette
Hello Angel, Did you try the following transaction = Transaction.objects.filter( user=user, status=F('detail__status'), ).first() Best, Simon Le jeudi 8 mars 2018 09:52:44 UTC-5, Angel Rojas a écrit : > > Hello friends, I have a little problem with a relationship with 3 tables > > table

Re: How to add an OR criterion to an existing QuerySet?

2018-03-14 Thread Simon Charette
Hello Bern, You're actually pretty close to the solution. You should be able to OR an existing querysets filters by using the "|" operator between querysets of the same model. That would be the following: qs |= Model.objects.filter(Q(...)) Simon Le mercredi 14 mars 2018 23:45:41 UTC-4, Bernd

Re: How to add an OR criterion to an existing QuerySet?

2018-03-15 Thread Simon Charette
o the other and was happy > ... > > Regards, > > Bernd. > > Simon Charette wrote: > > Hello Bern, > > You're actually pretty close to the solution. > > You should be able to OR an existing querysets filters by using the "|" > operator >

Re: IntegrityError: FOREIGN KEY constraint failed: Django 2.0.3

2018-03-21 Thread Simon Charette
Hello Anon, Django doesn't use database level ON DELETE constraints and emulates them in Python to dispatch pre_delete/post_delete signals. As long as you're using the ORM to perform the deletion you shouldn't encounter constraint violations. There's a ticket to add support for database level o

Re: A django bug on Queryset.delete

2018-03-28 Thread Simon Charette
Hello Yue, You probably have a model with a ForeignKey where you set on_delete=True. Best, Simon Le mercredi 28 mars 2018 07:11:04 UTC-4, yue lan a écrit : > > Hi, > I think I found a bug of django. My python version is 3.6.3 and Django is > 2.0.3. And the bug is showed below: > > File "E:\pr

Re: How to formulate a query over two models?

2018-04-11 Thread Simon Charette
Hello there, If you are using PostgreSQL you can achieve it using ArrayAgg[0] queryset = MetaData.objects.annotate(values=ArrayAgg('metadatavalue__value')) map = dict(queryset.values_list('name', 'values')) Cheers, Simon [0] https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/aggregates

Re: looking for the right way to work with JSONField - behavior inconsistent between strings and integers

2018-04-24 Thread Simon Charette
Hello Olivier, Since JSON objects can only have string keys[0] I'd suggest you always use strings as dict keys on the Python side to avoid having to deal with both cases. Another solution would to subclass JSONField to override the from_db_value method to turn keys into integer when retrieved f

Re: Django ORM - better handling of connections

2018-05-14 Thread Simon Charette
Hello André, > Is there a way to force Django to close the DB connection after each operation (unless we're in an atomic block)? The only way I can think of achieving that is by bundling your own database backend subclass and override execute() and the cursor subclass to close the connection wh

Re: Chinese humanize number conversion

2016-05-03 Thread Simon Charette
Hi Malte, The conversion takes place in the intword template filter[1]. The Chinese translation of the intword_converters can be found in the locale directory of the humanize application[2]. These translations are handled over Transifex[3]. Cheers, Simon [1] https://github.com/django/django/b

Re: Customised handling for wrong passwords entered in Login page in Django.

2016-05-03 Thread Simon Charette
Hi Arun, If you only want to log failed login attempts I suggest you connect a receiver to the user_login_failed signal[1] instead. Cheers, Simon [1] https://docs.djangoproject.com/en/1.9/ref/contrib/auth/#django.contrib.auth.signals.user_login_failed Le mardi 3 mai 2016 06:01:59 UTC-4, Arun

Re: How to atomically create and lock an object?

2016-05-11 Thread Simon Charette
Hi Carsten, Did you try using select_for_update() with get_or_create()[1] in an atomic()[2] context? @transation.atomic def demonstrate_the_problem(): d = date.today() t = TestModel.objects.select_for_update().get_or_create( jahr=d.year, monat=d.month ) # ... long `some_v

Re: How to atomically create and lock an object?

2016-05-12 Thread Simon Charette
already started by the demonstrate_the_problem() atomic wrapper. Else the connection is left in an unusable state by the integrity error. Cheers, Simon Le jeudi 12 mai 2016 10:48:30 UTC-4, Carsten Fuchs a écrit : > > Hi Simon, > > many thanks for your reply! > Please see below fo

Re: Getting unexpected results when using multiple aggregates

2016-05-13 Thread Simon Charette
This is a know limitation. Please see "Combining multiple aggregations"[1] in the documentation. Cheers, Simon [1] https://docs.djangoproject.com/en/1.9/topics/db/aggregation/#combining-multiple-aggregations Le vendredi 13 mai 2016 14:56:05 UTC-4, da...@joustco.com a écrit : > > I'm using an a

Re: How made worked models.Sum() together with models.Count in Django annotations?

2016-05-15 Thread Simon Charette
Hi Seti, As documented this will yield the wrong results in most cases until subqueries are used instead of JOINs[1]. Cheers, Simon [1] https://docs.djangoproject.com/en/1.9/topics/db/aggregation/#combining-multiple-aggregations Le dimanche 15 mai 2016 12:42:44 UTC-4, Seti Volkylany a écrit :

Re: Working with HstoreField in django tests

2016-05-15 Thread Simon Charette
Hi Denis, >From the exception it looks like the issue is not related to a missing extension but from an attempt of using and integer as a key. e.g. instance.hstore_field = {1: 'foo'} instead of instance.hstore_field = {'1': 'foo'} Cheers, Simon Le dimanche 15 mai 2016 21:11:33 UTC-4, Denis

Re: timezone application aware

2016-05-17 Thread Simon Charette
Hi Noumia, > Whatever operations they do within the database, all dates will be saved with > timezone, right? Django stores datetimes using the UTC timezone on all database backends. > But how do you identify the timezone of a user? is that something that I > should ask the user for and save i

Re: Aggregation / annotation over results of a subquery

2016-05-20 Thread Simon Charette
Hi Malcom, I suggest you look into the conditionnal aggregation documentation[1]. from django.db.models import Case, Count, When Contact.objects.annotate( messages_count=Count( Case(When( messages__recipient=recipient, messages__status=Message.STATUS_UNREAD,

Re: How to implement a ManyToManyField with a View

2016-05-26 Thread Simon Charette
Hi Bruce, I think you want to call get_object_or_404 with the Contact model in your contact_detail() view. Cheers, Simon Le jeudi 26 mai 2016 13:43:00 UTC-4, Bruce Whealton a écrit : > > Hello all, > I started a similar thread but couldn't find it. > I was creating a Personal Information Ma

Re: How to set default ordering to Lower case?

2016-06-06 Thread Simon Charette
Hi Neto, Ordering by expression (order_by(Lower('name')) is not supported yet but it's tracked as a feature request[1]. If we manage to allow transforms in `order_by()`[2] in the future you should be able to define a ['name__lower'] ordering in the future but until then you have to use a combin

Re: Possible bug with UploadedFile and form validation?

2016-06-13 Thread Simon Charette
Hi Nick, `io.TextIOWrapper` objects close their wrapped file when they are garbage collected (e.g. `__del__()`). This is similar to how `File` objects close their underlying file descriptor when collected. In the case of your `clean()` method the `file` object can be garbaged collected as soon

Re: Date() in Django query

2016-06-14 Thread Simon Charette
Hi Galil, In the next version of Django (1.10) you'll be able to use the TruncDate expression[1] for this exact purpose: MyModel.objects.annotate(join_date=TruncDate('join_time')).values_list('join_date', flat=True) In the mean time you can simply use a Func expression[2]: MyModel.objects.an

  1   2   3   >