Re: problems with get_or_create
On Thu, 2010-03-25 at 15:58 +, Tom Evans wrote: [...] > > He is describing this situation: > > >>> User.objects.get(username='tevans...@googlemail.com') > > >>> User.objects.get_or_create(username='tevans...@googlemail.com') > (, False) > >>> User.objects.get(username='tevans...@googlemail.com').first_name > u'Tom' > >>> User.objects.get(username='tevans...@googlemail.com', first_name='Thomas') > Traceback (most recent call last): > File "", line 1, in > File "site-packages/django/db/models/manager.py", line 119, in get > return self.get_query_set().get(*args, **kwargs) > File "django/db/models/query.py", line 305, in get > % self.model._meta.object_name) > DoesNotExist: User matching query does not exist. > >>> User.objects.get_or_create(username='tevans...@googlemail.com', > >>> first_name='Thomas') > Traceback (most recent call last): > File "", line 1, in > File "site-packages/django/db/models/manager.py", line 122, in > get_or_create > return self.get_query_set().get_or_create(**kwargs) > File "site-packages/django/db/models/query.py", line 343, in > get_or_create > raise e > IntegrityError: (1062, "Duplicate entry '' for key 2") No, he's not, because Kenneth said that the instance exists. In your example, the instance doesn't exist and thus a new object is attempted to be created. The restrictions at that point are the same as when creating a new object from scratch, as noted in my reply. The caller of get_or_create() will always know what the various constraints are on the model and must allow for that in their code. Regards, Malcolm -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: problems with get_or_create
On Thu, 2010-03-25 at 11:22 +0530, Kenneth Gonsalves wrote: > hi, > > I have a model like this: > > name - unique > slno - not null > mode - not null > > If the instance does not exist and I give all three values to get_or_create, > it works > > if the instance exists, and I give values for slno and mode which are > different > from the existing ones - I get a programming error as get_or_create tries to > create a new instance and falls foul of the unique constraint on name. It > works if I only give the value for name - it gets the instance and then I can > add the new values and save I don't understand what you are saying here. If the instance exists (as in, the filter parameters passed to get would return a single item), that instance is returned and the default parameters are never considered. So the values you pass for slno and mode are irrelevant. If the equivalent get() call would not return anything, then the instance does not exist and it's clear that the default parameter must contain correct data that can be used to create a new object -- including not violating any unique constraints. Perhaps you could show the code call you are making, rather than writing it out as a sentence. In short: get_or_create() first runs the get(). If that returns something, it is what is returned. If the get() fails with no object being present, then the instance DOES NOT exist and a new one is created, with all the same requirements as if you'd created a new object from scratch (e.g. no unique constraint violations). Malcolm -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
Re: Need for an internationalization/translation system not request-based
On Thu, 2009-08-13 at 10:11 +0200, Jarek Zgoda wrote: > Wiadomość napisana w dniu 2009-08-13, o godz. 09:38, przez Enrico > Sartorello: > > > Nice information, so we can go ahead working with activate() :-) > > > > Let me ask you one more question: in your code, i see you're using > > django.util.translation.get_language(), it's not a documented > > function and according to django policies it can be changed or > > removed in any new release. > > Perhaps it's better using request.LANGUAGE_CODE? > > > This function looks like part of public interface and the page > http://docs.djangoproject.com/en/dev/misc/api-stability/ > lists the whole internationalization subsystem as stable API so I'd > not worry. Well, it says that anything documented in the internationalization subsystem is stable API. So the original poster still has a point. But let's not worry about semantics too much here. I am quite willing to say that get_language() is stable API (I'm kind of the de-factor i18n sub-system maintainer, so I doubt I'll get any real arguments there). It hasn't changed in years and it does what is advertised. It's also needed, for exactly the reasons Jarek points out. Let's just document it and help people out. Generally, we haven't documented a lot of the internals of the i18n stuff for low-level customisation. Ramiro Morales has been doing some good work over the past few months helping sort out the documentation there -- splitting up some confusing single file i18n stuff into i18n and l10n and template versus backend. We're now in a position to start filling in some of the gaps. In short: feel free to use get_language() and unless some amazingly hidden bug or security hole is found in it, the API will not change. I'm happy to take a documentation patch that documents what it does (Jarek's code example is a good place to start -- that's the sort of thing I would include in the docs). Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: new session ID is created for every request from IE 7
On Wed, 2009-08-12 at 19:21 -0700, humble wrote: > Hi, > > I am writing a web application that involves session management with > the corporate backend module. I wrote my own authentication backend > plugin to satisfy the corporate requirement, not the default > authentication backend. I use file based session engine to avoid > sqlite crap. Everything works fine in firefox and chrome. But it seems > to be a problem with IE: response includes a new session ID (actually > a test cookie) for each request from IE. It seems IE never sends back > the previous cookie given by the server in subsequent request. Check > in /tmp/ (where I store all session files), I see the previous session > file is replaced with a new empty session file. > > Looking in to contrib.session.middleware.py confirms > "request.session.session_key" is different for each request. However, > this only happens when I use IE. I configured IE 7 to allow cookies, > so it does not reject cookies from django. What might be the problem? > Has any one seen this issue before? I've seen it before when the domain being used for the cookie wasn't a valid domain name. Browsers have blacklists of sets of domains that they won't accept/send cookies for and they typically won't allow you to set a cookie for .com, say. That might be the problem in this case. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: problem with openid
On Thu, 2009-08-13 at 07:22 +0530, Kenneth Gonsalves wrote: > hi, > > was trying out django_openidconsumer and get this error: > > complete() takes exactly 3 arguments (2 given) - I cannot figure it out as > this > is the definition of complete: > > def complete(request, on_success=None, on_failure=None): That's certainly one complete() function. But it's not the one in the traceback. :-) [...] > Traceback: > File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py" in > get_response > 92. response = callback(request, *callback_args, > **callback_kwargs) > File "/usr/lib/python2.6/site-packages/django_openidconsumer/views.py" in > complete > 111. openid_response = consumer.complete(dict(request.GET.items())) This is calling the complete() method on the "consumer" instance (consumer.complete(), not complete()). So find what type of object "consumer" is and look at the methods on that object. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: AutoRefresh model field (filled in by a trigger)
On Wed, 2009-08-12 at 04:55 -0700, Evgeny wrote: > Hi, > I have some fields in a model which are filled in by before_insert > trigger. > Is there any right way to autorefresh them after the object is > inserted, besides requesting a new instance of the object by > model.objects.get() method? You have one perfectly good method and you want another one instead? :-) Seriously, use get(pk=my_obj.pk). It's designed to retrieve single instances from the database. You could do filter(id=my_obj.pk).values("field_1", "field_2", ...) but it's not going to be significantly faster unless your model has massive fields (leading to other problems) and it reads a bit less comprehensibly in the code. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Need for an internationalization/translation system not request-based
On Wed, 2009-08-12 at 15:48 +0200, Jarek Zgoda wrote: [...] > As translation.activate() is process-wide, this approach is not > safe in multithreaded environment if using static translation (not > request-based). This is not correct. The translation.activate() call is thread-specific and definitely thread-safe. Otherwise Django's entire translation infrastructure wouldn't work. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Inheritance at runtime (per model instance)
On Wed, 2009-08-12 at 14:24 +0200, Thomas Guettler wrote: > Hi Malcolm and others, > > Malcolm Tredinnick schrieb: [...] > > You already have the content type table for referring to other model > > objects. Why not use that so that you can maintain some referential > > integrity? > > Content Types use serial keys. Take something like a ticket system: > Serial keys are good for the tickets. But if you have something like a > TicketTypeModel it is not a good solution. The customer uses the live > system and can create new TicketTypes. But during the same time, > I might create new TicketTypes in my development system. The serial IDs clash. Ah, ok. So you'll end up with something like your own version of the content type system. Makes sense. Providing your model names are going to be different from your customer's developed versions, your plan makes sense. > And the TicketTypes or (Workflow-Models) need to be installable for several > customers. This is the only reason I would be tempted not to just use the import path. You really want to namespace the identifiers and model names might clash if they're common enough. I would be very tempted to prefix some identifier with a customer-specific identifier (as a development recommendation, not enforced in the code). So you identifiers would be "tg_" and your customer 1 might use "aa_", etc. The prefix used to generate the ids could even be a setting if you could auto-create the ids from the model name/import path. But I might be over-engineering this. You understand your target audience -- particularly the number and habits of the target audience -- better than me. So this is just me thinking out loud. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Inheritance at runtime (per model instance)
On Wed, 2009-08-12 at 11:39 +0200, Thomas Guettler wrote: > Hi, > > I am writing a workflow engine. The base workflow is stored in the DB. > But some code needs to written for most workflows. > > This means I need code for a model instance (an not code per mode class). > > To make this most pythonic, how could this be done? > > My idea: since I want the workflow to be portable to several installations, I > don't use > serial IDs for primary keys, but slug-fields. The slug-field could be a > importable > classname like 'foo.workflow.MyClass'. You already have the content type table for referring to other model objects. Why not use that so that you can maintain some referential integrity. I suspect, simply because you've been using Django forever and know what's going on, that there is something subtle here I don't understand, so feel free to tell me why I'm an idiot and this won't work. > > Now I want that the Workflow model instance inherits from MyClass. This must > be done at runtime. I think this could be done with a custom manager. This is where I become Old Conservative Malcolm and say that you might want to consider NOT abusing model inheritance! :) I have reasons, though, so let me explain... I try to always relate this back to Python and what you can do in Python with normal classes (Django's ORM just provides a way to store parts of classes on disk). You can do what you want in Python, using the type() command where you can create whatever base classes you like. Sadly, it's harder than that when we introduce the persistence part -- storing in the DB. Since inheritance is implemented via relations that are constraints at the DB level, allowing arbitrary tables is not going to be possible. Although I've tried to implement model inheritance so that it works as transparently as possible, there are limits and this is one of them -- it's a genuine leaky abstraction, because the database requirement influences the functionality regardless of what implementation I use. A Django relation that points to any type of model already exists, however: GenericForeignKey. Since you can ignore model inheritance in Django and use a OneToOneField to link the models, you can do the same thing with GenericForeignKey in the place of OneToOneField. So you end up storing the "type" of the remote model and the pk of the instance you are pointing to. No referential integrity at the database level there (although we do enforce that the type is an existing content type). Based on your brief description, I would use GenericForeignKeys here, I think. But please elaborate if there's a reason that won't work for you. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Ajax in Django
On Wed, 2009-08-12 at 11:47 +0300, Jani Tiainen wrote: > HB kirjoitti: > > Hey, > > Why Django doesn't provide integration with Ajax out of the box (like > > Rails and Wicket)? > > It all depends what you mean by "integration"? > > You can use (model)forms with Ajax, or use any other means if you wish. > > Only thing that django doesn't provide is Ajax form rendering - I mean > that you can't just say {{ form }} and magically get ajaxafied form. I'll reply here, rather than against the original post, since you're hit the nail on the head, but I want to expand somewhat... We have always encouraged people to come up with a good set of template tags to do this sort of stuff. Right now, there doesn't appear to be anything that looks very Django-like. If you look at the Ajax helpers in Rails, for example, it's like writing Ruby in the templates. Since Django deliberately strives to have very simple templates, without programming in the templates, the challenge is greater for "generic" template tags. This doesn't mean it's harder to use Ajax, it just means that people are more likely to write custom template tags that insert the precise Ajax bits they're after. Including Ajax or other Javascript bits in Django templates isn't hard and writing custom tags is very easy, so it seems that the middle ground we've arrived at is reasonably acceptable to our core audience (experienced Python developers and web designers). It also doesn't mean that people shouldn't continue to try and create the perfect set of Ajax tags. When that happens, it will attract attention, fame, fortune, etc, and after suitable shaking out, we would look at whether it's worthwhile including in contrib. But in the 4+ years that Django has been open sourced, nobody has yet done that, which shows where the balance between need and pragmatism lies. > And there is good reason - what would be javascript framework to use > then? MooTools? jQuery? Prototype? ExtJS? Or my favourite Dojotoolkit (I > bet there is dozen of others that I don't remember or are aware of) That is also definitely a consideration. Along those lines, there are some library specific helpers that have been created. Search for dojango, for example, a set of Dojo-based Django template tags. I'm not sure if they're particularly good or not, as I haven't used them much at all, but they exist, which is definitely a good thing. There's also YUI-based incremental loading via Django template tags out there, too, which was even featured on the YUI developers blog (as an example of YUI-in-action) at one point. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: dates with a different format in the db
On Wed, 2009-08-12 at 00:24 -0700, Vokial wrote: > You've been very helpful, thanks. > The problem here is that i have to use these fields as proper > DateFields because i have to do some operations with these dates, like > making monthly/daily reports, searching entries in a specific period > of time and so on... > I guess i have to convert these strings to datetime objects in each > and every view but it's so annoying.. that's why i'm looking for a way > to make django use these strings as dates.. You could write a custom field subclass then, which converts the string it reads from the database to a DateTime value. Have a look at http://docs.djangoproject.com/en/dev/howto/custom-model-fields/ That documentation addresses a fairly complicated example of mapping database data to a Python class, not something like a datetime object, but it's basically the same thing. So read the whole document before leaping into code. At some point, I'll rewrite it to order things a bit differently (from memory, I wrote the initial version of that at about 1:30 one morning and it's never really had a major rewrite, but all the information is correct). Also, searching for dates in a range is still possible with your current data: MyModel.objects.filter(date_string__gte="20090101, date_string__lte="20090131") will return all the January, 2009 data, for example. You might be able to go a long way with just string stuff if you want to do direct database filtering. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: unique_together with None
On Tue, 2009-08-11 at 23:36 -0700, gentlestone wrote: > Thank you for the explanation. Seems to be the correct solution of the > problem (NULL, v1) != (NULL, v1) is overwrite the save method and > check for existence of (NULL, v1) before saving a new instance of > (NULL, v1). What I don't understand, why are the well-known databases > so stupid and why they can't do this job. Um .. the well-known databases are doing exactly the right thing. The behavior of NULL is well-defined to be not equal to itself (Oracle's incorrect behavior here is for historical reasons and they won't change it to avoid backwards-incompatibilities for their existing long-time users). Using nullable columns in unique constraints carries this risk-tradeoff with it, if you are going to be inserting NULL-able items. If you want to add that check to your save() method, then you can override it yourself, but the database behavior is a matter of least obstruction for users, since two entries of (NULL, "xyz") *are* different at that level. You don't want that behaviour, but that doesn't mean it's incorrect for all situations. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: problem with django_openid
On Wed, 2009-08-12 at 07:10 +0530, Kenneth Gonsalves wrote: > hi > was trying to install django_openid on latest svn head. I am getting this > error - do not know whether it is mine or openid's The main error I see here is a complete failure to use cut-and-paste view from the debug screen when pasting a traceback. Come on, Kenneth! You've been using Django and getting help from this list for far too long not to know that pasting a concise representation of the problem helps us to help you. Also the error is line 42 of the output you did paste. It says template syntax error, so that's definitely the first place to start looking and searching for the string reported in the template shows up the problem fairly quickly. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: syncdb with ForeignKey to_field outputs statements in wrong order
On Tue, 2009-08-11 at 12:00 -0700, physicsnick wrote: > Actually they don't need to be unique (and I don't want them to be > unique). MySQL does not require that foreign keys be unique; only that > they be indexed. > > I am actually using this for a temporal database. There are many > instances of an Author with the same code (an instance for each time > it was changed). In relation to the above example I am having the > Author's default manager filter for live instances of the object, and > making it be used to resolve foreign keys via "use_for_related_fields > = True". This means the reverse relationship (book.author) gives one > object: the live version of the author with the referenced code. While > the foreign key itself is a many-to-many relation at the database > level, Django's ForeignKey field is many-to-one. The fact that it happens not to raise an error when you twist it slightly in the way you're doing doesn't mean it's expected to work. I'm not convinced there is a bug involved here, since you're not using the ForeignKey class correctly. As far as I can work out, when ForeignKey is used correctly, we always are going to be generating the correct SQL. I thought Django's "validate" management command raised an error when to_field was used to target a non-unique field, but apparently I'm hallucinating. That's probably an oversight in the implementation. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: How to get this auto-field id value
On Tue, 2009-08-11 at 17:27 -0700, David wrote: > Any tips/suggestions are highly appreciated... One tip is to wait more than eight hours before posting "please help me" yet again. > > > > On Aug 11, 9:26 am, David wrote: > > Just a little more information. The autoField id is in the model > > class. Model_Form is a form based on this model class. > > > > On Aug 11, 9:20 am, David wrote: > > > > > > > > > Hello, > > > > > I am trying to retrieve an autoField id value in my following code > > > when I update records. > > > > > def update_record(request): > > > if request.POST: > > > form = Model_Form(request.POST) > > > if form.is_valid(): > > > form.save(pk=form.id, force_update=True) > > > > > I got an error that "Model_Form" object has no attribute 'id'. > > > > > Model_Form is a model-based form class that has an autoField id that > > > increases one by one. When I update a record, I need to give this > > > value. > > > > > I even tried "pk=form.pk", however it did not work either. ModelForm subclasses don't include any AutoField values. By definition, they are *automatically* assigned by the database. If you're using an AutoField, you don't set it yourself. If you want to manage the primary key value yourself, don't make it an AutoField. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: dates with a different format in the db
On Tue, 2009-08-11 at 08:58 -0700, Vokial wrote: > Hi! > In a db i have, already filled up with data, i have a varchar field > which contains dates formatted like "mmdd". Is there a way to make > Django recognise that field as a proper DateField even if the > formatting is different than the usual "-mm-dd" ? Django wouldn't recognise a character field that stored the dates in -mm-dd format as a DateField, either. > Because i can't alter the data in that db and i have to order the > entries by date... One of the reasons mmdd is quite a decent storage format is that normal string sorting puts the dates in order. So why can't you just order on that column as it already stands? You won't be able to do anything like filter using the __month lookup type, because it isn't a date field at the database level. But ordering shouldn't be a problem. > ...maybe by defining a function that automatically decodes the string > into a datetime python object like strptime? You can certainly convert the string values to datetime.date objects easily enough, but that doesn't help with ordering in querysets, for example, since that ordering happens at the database level. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Standalone script with django's ORM and multiprocessing
On Tue, 2009-08-11 at 03:12 -0700, prabhu S wrote: [...] > Why do you close the connection in > every process? Can you not just close once in parent? That would also work. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Standalone script with django's ORM and multiprocessing
On Tue, 2009-08-11 at 11:06 +0200, Spajderix wrote: > Hi! > > I've written a standalone script, which looks throught a table in db for > tasks to perform. It then starts subprocesses for each task it founds > using multiprocessing.Process class from python. Everything's fine when > there is one task, but when i try to start more subprocesses at once i get: > > OperationalError: (2013, 'Lost connection to MySQL server during query') > raise errorclass, errorvalue > OperationalError: (2006, 'MySQL server has gone away') > > I guess that this happens because all subprocesses share one connection, > and when one of them closes this connection, rest of subprocesses raises > an error. That certainly sounds believable. We call close() explicitly, too, so that is why ongoing operations are interrupted in the middle. > Do you know a way to go round this problem? If you close the database connection, Django will open a new one the next time it needs it. So I suspect you can work around this by explicitly closing the connection immediately after you start a new process (in the new process). Then the process will get its own connection when you try to do something. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Bad DateTime for LANGUAGE_CODE = 'sk'
On Tue, 2009-08-11 at 02:03 -0700, gentlestone wrote: > also local flavors SKRegionSelect and SKDistrictSelect do not work, > I'm afraid Please file tickets for these items (one issue per ticket) if they don't already exist. There is a localflavor component in Trac that is worth scanning the titles for to see if an issue has been reported. What we will need to fix things is what you are doing to exhibit the problem (a short series of steps) and what the result should be. For bonus points, a patch to both the code and the tests, but at least a problem report so that we can replicate the issue. Then it will be fixed. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: looping over forms in a formset
On Tue, 2009-08-11 at 01:12 -0700, bnl wrote: [...] > Apologies that I'm not asking my questions in the way you'd like, > but believe me, I am cutting it down a lot ... and I appreciate that > it's still not obvious where the errors are (I would have found > them otherwise). In this case, I had cut it down to just field, and > it > exhibited the problem ... I shouldn't have included the extra line > which was just to show why I wanted to do it ... Trimming a problem report to the minimum required and no further is part science and part black art, so there are going to be times when you just get unlucky. In this case, however, the problem is you aren't including details so that I or anybody else can actually reproduce the problem. So you end up in a position where you have to hope the particular error message triggers a "we've seen that before" thought in somebody's head. A good problem report or request for help contains enough information to repeat the problem. Which means, in this case, the form class containing the field. > > It would seem that the advice to loop over hidden fields in the > template could be promoted to the documentation. Well, we already document, in the main formset documentation, including the management form if you're doing manual template layout (http://docs.djangoproject.com/en/dev/topics/forms/formsets/#using-a-formset-in-views-and-templates ) and we document including hidden fields if you're doing iteration over form fields, in the main forms documentation, (http://docs.djangoproject.com/en/dev/topics/forms/#looping-over-hidden-and-visible-fields ) so this isn't undocumented territory. However, if you feel there's a clearer way to do this without giving it undue prominence -- bearing in mind it's an edge case, so shouldn't obscure the more regular usage cases or weigh those sections down with heavy details -- then please do create a patch and attach it to a ticket. Many of our documentation improvements are generated by people trying to make something clearer. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Sort by output of arbitrary method
On Tue, 2009-08-11 at 00:29 -0700, Harish wrote: > Hi Friends, > > According to the django tutorial: > "You can click on the column headers to sort by those values -- except > in the case of the was_published_today header, because sorting by the > output of an arbitrary method is not supported. " > > > Is there any work around for this? Sorting is done at the database level. You can't pass arbitrary Python code through to the database layer, which is why that restriction is in place. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Project Organization
On Mon, 2009-08-10 at 20:51 -0700, MattR wrote: > Are there any best practices documents to organizing large Django > projects? > > Should the view code be in a file called views.py? It seems like this > file could get rather large and hard to manage, is there some > suggested way to break it up? View functions are just Python functions that are called with particular parameters (request + any arguments from the URL pattern). So you can put them literally anywhere that is on your Python path. They don't even have to reside in applications, although it's not a bad idea to do so. You definitely don't have to call the module views.py and it's not uncommon to break it up into, say, a views/ directory containing a bunch of files with related views in each file. > > Should the files with views even be called views.py, or should the > filename indicate the functionality of the view? I tend to go for separate filenames for separate functionality. I'll often have views that change data in one file, views that are for read-only things in another file and forms in other files, again, maybe grouped by functional groups. Also remember to look at how you split things into applications. A Django "project" is really just a settings file and a root URL Conf file. The settings file contains a list of applications that are used and finding a nice separation of your functionality into applications is a really good idea and pays off in spades down the road. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Timezones in Django
On Tue, 2009-08-11 at 00:08 -0400, Vitaly Babiy wrote: > Hey guys, > I am working on an application that needs to be timezone aware. Is > there support for this with in django I can't seem to find anything > except for a few third party packages. i am trying to find something > that is in django core. No. Django encourages the use of third-party applications. The problem in this area is MySQL. They apparently haven't discovered that the world has timezones yet and that any datetime without a timezone is broken, so they don't have a timezone-aware datetime field. Since MySQL is a fully supported database in Django, it makes having a timezone-aware field in core quite a tricky proposition. Not that that will prevent us eventually adding one, but it's not amazingly high priority as writing custom fields is pretty easy these days. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: adding a model to show up in admin
On Mon, 2009-08-10 at 20:43 -0700, zignorp wrote: > Hello, > I just added a model to models.py, > > class Topic (models.Model): > topic = models.CharField(max_length=180, blank=True, null=True) > > def __unicode__(self): > return self.topic > > I can see it in the model that's calling it: > class Film(models.Model): > topic = models.ManyToManyField(Topic, blank=True) > > but I can't see it in the admin. Did you add a call in your admins.py file to register Topic with the admin? Like you will have done for the Film model? Models don't automatically show up in the admin interface. The admin app needs to be told they exist. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: imitating a spreadsheet (kind of) with formsets
On Mon, 2009-08-10 at 19:07 -0700, Chris Curvey wrote: > What I want to do is have a series of forms, all next to each other in > table format, like this: > > Car Honda Toyota Chevy > Price $12,000$14,000 $10,000 > MPG 30 2826 > Color Blue Red Yellow > > (I'm sure that's going to look like crap in a proportional font.) But > the point is that Car, Price, MPG and Color are all labels, and > everything else (Honda, $12,000, 30, Blue, etc) is a form field. > > I can create the formset and use as_table() to get the forms > generated, but I seem to either get the label repeated for every form, > or not at all. Can someone point me in a direction to get the form > labels listed only once? At some point, when you're doing highly customised form layout, you have to switch from using the convenience methods for the simple cases and attend to all the little details yourself. This means laying out each form element appropriately. Maybe you write a template tag to do that, or maybe you can do it with some for-loops in the form. But as_table() and friends aren't designed for this kind of thing. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Dumping Large Databases
On Mon, 2009-08-10 at 17:02 -0700, Chris wrote: > I'm trying to dump a 3GB MySQL database using manage.py dumpdata, but > it's getting killed after 2 hours. Is there any way to get it to use > less memory/cpu so it doesn't get killed and completes the dump? Is there some particular reason you need to use dumpdata for this? At some point, using the database's native tools is going to be a lot more efficient and robust. Dumpdata is great for the sweet spot, but it isn't designed to completely replace all existing database tools. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Multiple application instances?
On Mon, 2009-08-10 at 12:20 -0700, Andrin Riiet wrote: > In the django documentation -> URL dispatcher -> Defining URL > namespaces it reads "When you need to deploy multiple instances of a > single application, it can be helpful to be able to differentiate > between instances" > > I am unable to find any kind of documentation on how to "deploy > multiple instances of a single application". > > So how can I have multiple instances of one application? Have a look at how the admin application works. It isn't trivial to create an application that can be deployed multiple times, but fortunately, it's also not required very often. The admin is an example and I can think of a few other situations it might be required for, but generally you'll find that the same application instance can be used to handle things. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Passing optional URL params to reverse() function
On Mon, 2009-08-10 at 11:28 -0700, nabucosound wrote: > Hi all: > > I have a URLconf url entry like this: > > > url( > regex=r'^(?P\w+)/(?P[-\w]+)/$', > view='show_post', > name='show_post', > kwargs={'msg': None}, > ), > > > and I want to call it with HttpResponseRedirect and reverse(): > > > filters = {'category': post.category.name, 'slug': post.slug} > return HttpResponseRedirect(reverse('show_post', kwargs=filters)) > > > but I am getting this error: > > > NoReverseMatch at /commentposted/first-post/ > > Reverse for 'show_post' with arguments '()' and keyword arguments > '{'category': u'django', 'msg': 'Your comment has been posted', > 'slug': u'first-post'}' not found. > [...] > Is there any way to pass th reverse() function extra optional > parameters that the url define? Or am I crazy? No, you can't do that. By the way, the extra arguments you are passing in aren't *optional* -- they are simply not required. There is not situation in which they will be used to construct the URL. You can only pass in parameters that are present in the URL pattern. There are a bunch of technical reasons for this (including handling optional arguments and precise error reporting), so it's not an arbitrary decision. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: looping over forms in a formset
On Mon, 2009-08-10 at 08:59 -0700, bnl wrote: > hi folks > > I have a formset, which I want to display using a customised template > for the forms. > > This works: > > {{formset.mangement_form}} > {% for form in formset.forms %} > {{form}} > {% endfor %} > > The following displays ok, let's me edit one form, but then I can't > update it or add another, failling with a muMultiValueDictKeyError > at > "Key 'form-0-id' not found in 1.0 blew up with a keyerror). > > {{formset.management_forms}} > {% for form in formset.forms %} > {{form.title.errors}}{{form.title}} > etc looping over the fields in a nice way ... > {% endfor %} > > Looking at the posted form in an editor, I see the following (with > django 1.0) in the form that works: > > and > > in the one that doesn't. Since the one that doesn't work doesn't have any value associated with it, it won't be submitted as a form element (which is why you are not seeing it as a key in the form data). In other words, it's being rendered incorrectly. So it's working fine, given what is being rendered. > > Any idea what I'm doing wrong? need to do? The details are hidden in the line you have written as "looping over the fields in a nice way". Construct a small self-contained example of a form and formset class and show exactly how you are attempting to display the form fields and we might have some chance of spotting the problem. Work hard on removing every detail that isn't necessary -- removing form elements and formset details as much as possible until the error disappears. Ideally, you'll end up with a form with only one field and it will become apparent what the problem is. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: select_related(field) doesn't use the default manager of the field
On Sat, 2009-08-08 at 22:00 -0700, Gleber wrote: [...] > When I override the get_query_set() adding extra fields, these fields > aren't available if I execute: > ModelB.objects.all().select_related('ref') This is true. > This is a bug? Not necessarily. It's intentional behaviour at the moment and it's fairly tricky to make things work the way you want. *Particularly* because you're using extra(). All bets are off once you start introducing extra() into things, because that introduces opaque SQL strings, so the necessary alias relabelling and the like that has to go on to move query parts around isn't going to be able to work with that. Worthwhile opening a ticket for this enhancement request. Don't be too surprised if it's ultimately closed as wontfix, but I'd like to have a think about it for a bit and see if the passing of a few months brings up new ways to do this that I didn't think of the first couple of times I worked on this problem. > If not, how can I get the extra fields from ModelA > through ModelB with only one query? It might not be possible. > I need this cause I have to display a list of 50+ ModelBs and i can't > execute 50+ queries only for that.. Which you don't have to do. You can use normal select_related() behaviour and then do an extra query to retrieve the necessary extra fields and iterate through the queryset attaching the extra attributes to the models. So it's one extra query. You could even do this as a subclass of QuerySet as a specially named method if you were doing it often enough that you wanted it wrapped up neatly. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: override save()
On Sun, 2009-08-09 at 13:35 -0700, Léon Dignòn wrote: > Hi, > > I have a ModelForm of my UserProfile model with two additional fields. > I need to override save(), to save the additional fields to the > django.contrib.auth.model.User model. > I tried to do that with a subclass of my UserProfile model class to > have the code separated. But I get a NameError: name > 'ProfileFormExtended' is not defined. > > from django.contrib.auth.models import User > from django.db import models > from django.forms.models import ModelForm > from django import forms > from myproject.myapp.models import UserProfile > > class ProfileForm(ModelForm): > first_name = forms.CharField(max_length=30) > last_name = forms.CharField(max_length=30) > > class Meta: > model = ProfileFormExtended At the time this line of code is executed, this class doesn't exist yet (you don't define it until later in the file). The error message is telling you the right thing. Reorder the code in the file. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Continuing problems running Django when not site Root.
On Sat, 2009-08-08 at 13:41 -0700, Streamweaver wrote: > Let me clarify. This method handles the RequestContext obviously since > it's a login but what I mean is the SCRIPT_NAME variable isn't set for > the template and can't be read as far as I can tell. Nothing is automatically set for a template. If you want access to a particular quantity in a template, pass it in. You could even create a context processor if you want it every time. Typically, SCRIPT_NAME is *not* required in templates, since things like the url template tag already handle it automatically and constructing the correct URL for many things is more complex than just crashing together a few strings, so it tends to be done via template tags or in views. Thus, SCRIPT_NAME isn't a likely candidate for something that would be passed in all the time. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Bug with model get_*_display() methods?
On Sat, 2009-08-08 at 12:09 -0700, Margie wrote: [...] > Question: If want to use a special widget for a ChoiceField, is it > true that I need to instantiate the ChoiceField (or TypedChoiceField), > rather than just setting the .widget attribute on the one that is by > default created for me (due to it being a modelForm)? > > I find that if I just do this: > > self.fields["status"].widget = StatusWidget(task=instance) Grep'ing for "choices" in django/forms/*.py would reveal the answer to this. Have a look at how the Select widget handles choices, since that is what you're subclassing. The "choices" attribute of all the classes in widgets.py is set in the __init__() method of each widget. In fields.py, have a look at ChoiceField and you'll see that when you set choices on a field, they are also set on the associated widget (there's a _set_choices() method that is part of the "choices" property on ChoiceField). What you're doing in your above code is not setting any choices at all. You need to tell the widget which choices it can use. [...] > However, I see when debugging that IntegerField.to_python is an > unbound method: > > (Pdb) self.coerce > > > What is the right thing to set coerce to if I just want it to do > whatever it would "normally" do for the corresponding model field if I > wasn't trying to override the widget? In my case I have verified that > if I set coerce=int that does work, but that doesn't seem very > general. I'd much rather use whatever the standard coerce method > would have been if I hadn't overridden the widget. I'm not completely convinced this is a great plan, since if you are only overriding the widget in __init__, then the coerce function will already have been set up when the TypedChoiceField was created (it's a feature of the forms.Field subclass, not the widget). If you are overriding the form field entirely then you know better than Django what the correct type to use is, so it's actually easier and arguably clearer to just put in the right thing. However, you also have access to the model, so just use the model._meta.fields[...] entry for the field and use the to_python() method on that instance. Look at things like django.db.models.options.Options.get_field_by_name(). Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: generate sql query from ORM
On Sat, 2009-08-08 at 07:26 -0700, Lokesh wrote: > Hi, > > Need help in generating the sql query i.e generated by django at > runtime from ORM > > from django.contrib.auth.models import User > class UserBasicDetails(models.Model): > user_id = models.OneToOneField(User, primary_key=True, > to_field='username') > name = models.CharField(null=False, blank=False, max_length=30) > > qs = UserBasicDetails.objects.get > (user_id__email__exact='exam...@djano.com') > > > I got the below search result qs.query.as_sql() > but, this will generate sql for only for result sets (filter) and not > for a single record/value (get) (UserBasicDetails.objects.filter > (user_id__email__exact='exam...@djano.com')) A get() call is a filter() call with only the first element extracted (if more than one element is returned, it's an error). So just look at the SQL for the equivalent filter() call. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Django documentation site is SLOW
On Sat, 2009-08-08 at 00:14 -0700, Thierry wrote: > Hi, > > Just wanted to add my own testimony: I too, noticed serious > performance issues with Firefox when consulting Django documentation. "Performance issues" could many a myriad of things. Is it slow to render, or slow to load the data? Or slow to update as you scroll through the page? Can you give an example of a page that behaves poorly in your case and describe how it behaves poorly? Does it behave in the same fashion when you're viewing a local copy of the docs (served via a local webserver versus just loaded as files is a difference to test, too), or just when you're viewing them on djangoproject.com? Django's docs pages are generally very lightweight HTML and total content is fairly well set up for taking advantage of caching. There are a few CSS rules that could be written differently to give greater performance, but none of them are particularly tragic, given the lack of reflows that go on in the page (they are static pages, by and large). We're certainly better in this respect than a vast majority of websites out there. If we have a situation that is a genuine example of Firefox regression, it would be good to know so it can be reported to the Firefox team or fixed on our side if it's a legitimate problem. Right now, the problem reports from this thread are a little light on those things we like to call "specific details". For the record, I'm using Firefox 3.5.2 on Fedora 11 and don't notice any problems reading the docs (although I don't have Adblock installed). Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Bug with model get_*_display() methods?
Hi Margie, On Fri, 2009-08-07 at 23:17 -0700, Margie wrote: > > Hmmm, ok, after digging around I realize that full_clean was not > setting cleaned_data for the status field to an integer value; > cleaned_data['status'] was just getting set to something like u'1'. > > I am in fact using sqllite, and yes, my status fields are just > integers: > > OPEN_STATUS = 1 > CLOSED_STATUS = 2 > STALLED_STATUS = 3 > > I think the problem has to do with the way I created the status field, > which is like this: > > self.fields["status"] = forms.ChoiceField > (choices=Task.STATUS_CHOICES, widget=StatusWidget(task=instance), > required=False) Right, that won't do what you want. ChoiceField normalizes to a unicode object. > > I tried moving to TypedChoiceField(), but that didn't help. I > debugged into it in the case where I used TypedChoiceField() and I can > see that when coerce is called it isn't doing anything, it is just > returning the unicode value. > > I find that if I do this instead, that it does do the coerce > correctly: > > self.fields["status"].widget = StatusWidget(task=instance) > > > In looking at the doc it looks like the purpose of TypedChoiceField() > is to allow me to create my own coerce function, is that right? Correct. > And > of course I wasn't doing that so it was behaving the same as > ChoiceField, and it looks like the default there is to just return the > unicode. Also correct. The documentation says "Defaults to an identity function" and all the data coming from a form submission are strings (Python unicode objects), so if you don't supply the coerce parameter, it does nothing. It's probably a slight API wart that TypedChoiceField doesn't just raise an exception if you don't supply coerce(). The default is slightly dangerous, as it almost always means you're misusing the field. Not a fatal flaw in the design, however. > > When I don't declare the status field at all (ie, just let django do > it's default thing), my guess is that it is choosing a coerce function > based on the integer type of my choices, is that true? Yes. The django.db.models.fields.Field.formfield() method detects if you have specified "choices" in the field and uses the Field subclass's to_python() function as the coerce method. > I have never > used anything but sqlite3 so far, so I guess that was masking the > error and I would have run into this in a more serious way when I > moved to a different db? Actually, my SQLite observation was entirely bogus. I suspect what you're seeing is the difference between these two lines: t1 = Task.objects.create(status=u'3') t2 = Task.objects.get(id=t1.id) In this case, t1.status will be a unicode string, but t2.status will always be an integer, no matter what DB backend is involved. So you are seemingly stumbling over a case like the t1 situation -- where you're using the object after it has been populated and saved, but still using the raw data. I've long argued that allowing the wrong types to be assigned to attributes in Django models is a flaw (Python got rid of automatic type coercion for operator arguments years ago for the same reason), but it's been there forever in Django-years, so isn't going to go away now. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Continuing problems running Django when not site Root.
On Fri, 2009-08-07 at 14:44 -0700, Streamweaver wrote: [...] > Is there anyway around this? Anyone know if fixing this on the Django > roadmap? It was fixed over a year ago (before Django 1.0 came out). If you are using anything later than that, you don't have to do *anything* to worry about SCRIPT_NAME, although the variable is set in the request.META dictionary so you can use it to construct URLs if you want to do that manually. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Bug with model get_*_display() methods?
On Fri, 2009-08-07 at 11:40 -0700, Margie wrote: > I see inconsistencies in how get_*_display() works based on whether > the object is a recently saved object. Probably an example describes > this best: > > My model contains this: > > class Task(models.Model): > > STATUS_CHOICES = ( > (OPEN_STATUS, 'Open'), > (CLOSED_STATUS, 'Closed'), > (STALLED_STATUS, 'Stalled'),) > > status = models.IntegerField(choices=STATUS_CHOICES, blank=True, > null=True) I'm assuming OPEN_STATUS and friends are integers here (and not '1' or other strings that contain integers). [...] > However, if I have recently saved a modelForm associated with my Task > model and now have a handle to the object that that save() returned, > the status is in unicode, and get_status_display() doesn't return a > useful string: > > (Pdb) type(self) > > (Pdb) self.status > u'3' > (Pdb) self.get_status_display() > u'3' If I create a standard ModelForm subclass for your task model and then submit some data to it (just using {"status": "1"} as the POST data dictionary), I cannot replicate your problem. The devil is in the details here. What does your ModelForm look like? The results you are seeing are consistent with the form somehow saving a string value for the "status" field. Which means (a) you're using SQLite, since other databases will complain about the type mismatch, and (b) something is going funky in your particular ModelForm. The get_FOO_display() method requires an exact match the choice value and the value of the field, otherwise it just returns the field value. Since 3 != u'3' in Python, it is returning the correct result, given the value of the status field. The question is how did you manage to get a string into the status field. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Date-based generic view not working
On Fri, 2009-08-07 at 13:36 -0700, Thomas Jaggi wrote: > Well, after setting 'allow_future' to true everything works fine. > Since the entries were created today I don't really get this. I'm > using the 'pub_date' as 'date_field' and it's definitely NOT in the > future... Did you set the timezone correctly in your settings file? If you forget to specify anything, it sadly defaults to Chicago's timezone (when we all know the correct answer is Australia/Sydney), which means "now" is in the past for most of us. Secondly, if you make a typo in the timezone setting or specify one that isn't know to your system, it will end up appearing to be UTC, which is also in the past for more the majority of the planet's population. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: very interesting query... i need some help
On Fri, 2009-08-07 at 06:15 -0700, talpay...@gmail.com wrote: > i have come up with one of the most interesting query i have ever > seen. > > I want to do this : > > products = products.filter(productdetail__detail_value__gte = > first_value) > products = products.filter(productdetail__detail_value__lte = > second_value) > > where first_value and second_value are integers and > "productdetail__detail_value" are stored as a char. > > it is a very simple sql query but how can i do this using django > queryset. the problem is that i need the products to stay as a > queryset... because i need to filter it again if that is the case. So what is the problem you are seeing? At the end of the above two statements, "product" is a queryset, so that part of your problem is solved. > > taking the easy way out and changing the way the table is constructed > is not an option. i have to store any kind of data in "detail_value" > and filter the information. it's a generic filter and this is the only > problem i don't have a solution to. please help. You have a modelling problem, in that you're using "<=" on a character field, which doesn't make sense for generic data. That's not something Django can help you with out of the box. You say you can't change the field type to something numeric type because have to store "anything" in that field, but what do you expect to happen in the filter if detail_value is "elephant", say? It is neither less than, nor greater than, nor equal to a number. It's incomparable. So you're asking Django to read your mind a bit there. Since you're wanting to do something that is highly SQL specific here, you'll want to first work out what the query will look like in raw SQL. I suspect there's going to be either a nested query to only extract numeric values or maybe a coallesce statement or maybe something else. I can't visualise how you might do this, since it's very data dependent. Work out the SQL query directly, perhaps on a simplified model and then let us know what that might be and then we might be able to help convert it into something you can use in the ORM. Or maybe not -- there are (intentionally) limits on what you can do directly in the ORM and the answer for edge-cases is often to write the query directly in SQL. Which means you cannot use it further as a queryset (you could create something that could be used to extra results, easily enough, but further filter() calls, etc, are much harder to inject correctly). Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: user.objects.create is not checking for duplicate emails
On Fri, 2009-08-07 at 17:02 +0300, Mirat Bayrak wrote: > no i am talking about User model in django! The Django user model does not enforce unique email addresses, since email addresses aren't necessarily one-to-one with real-world people: there are various legitimate situations where different users of your site will have the same email address. If you want email addresses to be unique, you should make that check a part of the form validation in the form you're using to create users, as indicated earlier in the thread. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Model field option "max_length" is not respected (Sqlite backend)?
On Fri, 2009-08-07 at 01:24 -0700, Thierry wrote: > Hi, > > I have a model roughly defined as such (FK fields do not appear for > simplicity): > > class FieldChange(models.Model): > old_value = models.CharField(max_length=50) > new_value = models.CharField(max_length=50) > > Using SQLite, the table definition roughly translates to: > > CREATE TABLE "fieldchange" ( > "id" integer NOT NULL PRIMARY KEY, > "old_value" varchar(50) NOT NULL, > "new_value" varchar(50) NOT NULL, > ) > > However, it seems that the "max_length" condition is not respected, > neither at Django level (when saving) Django does not currently do model-level validation. > nor at database level: SQLite respects SQL syntax, in that it accepts it without error, but it's internal storage format doesn't enforce that. You can put a string into a numeric field in SQLite and it won't complain. That's part of the reason for its code simplicity: you have to behave nicely when giving it data, because it isn't standing in the living room with a big stick enforcing much. > For instance, I managed to create a model instance with fields longer > than 50 characters and save it. > Worse, I managed to retrieve that instance with fields unchanged, i.e > their size still exceeding 50 characters (in a separate "django shell" > session). > > I expected the operation to fail at validation or DB backend level, or > at least that the fields would be truncated to comply with condition > "max_length=50". The latter behaviour would be very bad, since it would quietly lose data (the fact that MySQL does it and only raises a warning and not an error is, in my book, a design bug in MySQL). > Is there some kind of bad magic here? Or only related > to SQLite? No and yes, in that order. > Now what had me spot the error is that I wanted to manually truncate > 'old_value' and 'new_value' fields when data exceeds the 50 characters > limit (adding trailing '...' characters when necessary). Where is the > best location to do that? The model 'save()' method, I suppose? Yes. That's the ideal place for any cleanups of this variety. Honza Kral is working on model validation as part of his Django summer of code project and that contains normalisation passes as well, so this will be something that will be easier in a future version of Django (1.2, all things going well). For now, the save() method is an ideal place for any automatic translations. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: multi-table inheritance and modification of OneToOneField options
On Fri, 2009-08-07 at 00:30 -0700, Jan Ostrochovsky wrote: > Thank you, Malcolm. > > In fact, our current design was, as you recommended: > > Subject ---one-to-one-null-false--- Address ---one-to-one-null-true--- > Payment (Invoice) > > I want to use generic views and to join Subject+Address in the same > form, and model inheritance seemed to me as most straightforward > solution for this need, but as you do not recommend it, Bear in mind that there might be somebody who gives stricter recommendations on not abusing model inheritance around here, but I'm not sure who they would be. I very much view it as a Python equivalent (with some abstraction leakage from DB -> Python), but my view isn't universally held. In this case, though, what you're asking for isn't possible in the way the code is implemented, so it's not just a matter of preference. > I will look > for another solution... e.g. form inheritance, as I found it here > http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#form-inheritance > or here http://www.djangosnippets.org/snippets/703/. Hmm ... if you're doing this for the form result and you aren't intermixing the fields from Subject and Address (or even if you are), you might be better served by still making each on its own ModelForm and just passing both into the template. Then layout both Django forms inside a single HTML form element. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: DateInput widget, format attr & ugettext
On Fri, 2009-08-07 at 11:56 +1000, Malcolm Tredinnick wrote: > On Thu, 2009-08-06 at 08:06 -0700, cArkraus wrote: > > Hey all, > > > > I cant seem to get my (non-model-)forms datefield localized. > > > > Here's my first attempt: > > some_date = fields.DateField(widget=widgets.DateInput(format=ugettext > > ('%d.%m.%Y'))) > > This would do the translation when the file is imported, which won't > reflect the user's current locale. The working rule is that you don't > use ugettext() outside of a view function (or something called directly > by a view). > > > That's working fine, until the user switches his sessions language. > > Then, the date is still shown in the format(ie. '%d.%m.%Y') and not > > the correctly localized one(ie. '%Y-%m-%d'). > > > > Now, if I change to ugettext_lazy() like this: > > > > some_date = fields.DateField(widget=widgets.DateInput > > (format=ugettext_lazy('%d.%m.%Y'))) > > > > I get a TemplateSyntaxError 'strftime() argument 1 must be string or > > read-only buffer, not __proxy__' > > That's a bug in Django and Python (both sides share some blame: Python's > string handling is retarded in cases like this and Django doesn't work > around it correctly here). It's not particularly easy to work around it, > either. This came about ambiguously: without hunting down the offending place right at the moment, I'm still fairly certain it's easy to fix this in Django's core. I can't think of an easy way to work around it in Django apps, however (that might be because I'm not imaginative enough). Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: DateInput widget, format attr & ugettext
On Thu, 2009-08-06 at 08:06 -0700, cArkraus wrote: > Hey all, > > I cant seem to get my (non-model-)forms datefield localized. > > Here's my first attempt: > some_date = fields.DateField(widget=widgets.DateInput(format=ugettext > ('%d.%m.%Y'))) This would do the translation when the file is imported, which won't reflect the user's current locale. The working rule is that you don't use ugettext() outside of a view function (or something called directly by a view). > That's working fine, until the user switches his sessions language. > Then, the date is still shown in the format(ie. '%d.%m.%Y') and not > the correctly localized one(ie. '%Y-%m-%d'). > > Now, if I change to ugettext_lazy() like this: > > some_date = fields.DateField(widget=widgets.DateInput > (format=ugettext_lazy('%d.%m.%Y'))) > > I get a TemplateSyntaxError 'strftime() argument 1 must be string or > read-only buffer, not __proxy__' That's a bug in Django and Python (both sides share some blame: Python's string handling is retarded in cases like this and Django doesn't work around it correctly here). It's not particularly easy to work around it, either. Please open a ticket with this short example (only the ugettext_lazy() case). Although you might also check that the i18n component in Trac doesn't have a ticket open like this. I'm a little surprised it hasn't been noticed before. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: How-to use SelectMultiple widget with CommaSeparatedIntegerField ?
On Thu, 2009-08-06 at 07:35 -0700, nono wrote: > I was reading my post and though it was not very clear > > My model uses CommaSeparatedIntegerField to store some integer values. > I want my users to use SelectMultiple widget to create/update those > integer so I put a ChoiceField with widget=SelectMultiple in my form. > My problem is that all I can get from this is a list of values (for > example [u'2', u'3']) where I expect comma separated values ("2, 3"). > > I hope this is a better explanation and somebody could help me If you want to normalise the values that are submitted to something other than what happens automatically, write a clean_() method for that form field. Have a look at http://docs.djangoproject.com/en/dev/ref/forms/validation/ for details. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: multi-table inheritance and modification of OneToOneField options
On Thu, 2009-08-06 at 07:15 -0700, Jan Ostrochovsky wrote: > Hello, > > http://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance > says: > The inheritance relationship introduces links between the child model > and each of its parents (via an automatically-created OneToOneField). > > http://docs.djangoproject.com/en/dev/ref/models/fields/#onetoonefield > says: Multi-table inheritance is implemented by adding an implicit one- > to-one relation from the child model to the parent model... > > The question is: how can I set options of that implicit OneToOneField? > Most interesting is null=True / null=False. You don't. Model inheritance is a Python-level thing and things like "optional" inheritance doesn't existence for Python inheritance. It's a shortcut for emulating Python class inheritance as much as possible. If you want this level of control, model the relations explicitly and set the options on the OneToOneField to whatever you like. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Get current user outside a view / without an request object
On Thu, 2009-08-06 at 03:33 -0700, krylatij wrote: > Why do you think so? It's bad encapsulation practice, for a start. It breaks Python's namespacing habits. In this particular case, however, go back and read the original poster's message. Having the user in threadlocals doesn't solve any problem, since he's trying to create a form class based on information in the request and that only happens at import time, not every time something in the file is looked at. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: django queryset based on when data created
On Wed, 2009-08-05 at 21:41 -0700, Joru wrote: > Everytime I edit some data, the data order in queryset changed into > the newest edited > Is it posible to get queryset that ordered based when the data created > without having to add creation date for sorting purpose The order results are returned in SQL when you don't supply explicit ordering is completely undefined. It can even change without the data changing (if the database tables are vacuumed to better utilise space, for example). Unless you specify an ordering, there are no guarantees in this area. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Admin site images not coming up in 1.1
On Wed, 2009-08-05 at 21:09 -0700, emy_66 wrote: > Hi, > > Just migrating my application to 1.1. Everything works fine except the > images inside the admin site are not showing up. Any ideas why this > may be? Everything worked with 1.0.1 and 1.0.2 I think. Remember that the admin images and CSS files are static data, so you will have some extra configuration in place to serve those files (what and where will depend on your particular server choices). Have you changed things to point to the Django 1.1 admin media files instead of the 1.0 versions? Not sure if that will fix your problem or not. I haven't had any particular problems moving projects to the new code, so I haven't seen what you are seeing. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: multiple projects shared database
On Wed, 2009-08-05 at 17:59 +0100, Robin Becker wrote: > My boss wants to have two different django controlled websites with a common > database. Is there a way to do this? > > We are already running multiple websites into a single django project and > because they have a disambiguating term in the urls eg each url has > /lang/brand/path we can map the URLs pretty well. > > With the multiple django projects & 1 database I am worried there are some > hidden problems waiting to come out and play. The only potential problem is the content types. There are entries in the content types table for each model and it needs to contain information about all the models. So be careful when you're running syncdb. What you're trying to do here is not dissimilar to just using different settings files for the same database, as in this tip: http://www.pointy-stick.com/blog/2009/03/26/django-tip-controlling-admin-or-other-access/ On the other hand, if the two websites are entirely independent, putting them into a single database is simply poor design. It's trivial to create a separate database and why not use the tools that are available instead of adding extra complexity?! Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: apache ok (mod_wsgi) bue some issue with admin backend
On Wed, 2009-08-05 at 11:50 +0200, Salvatore Leone wrote: > Hello again... > > > I have my site working with mod_wsgi, but I still have some problem > using the admin interface and managing uploaded files. > > On the admin side all static files aren't loaded. So there is no css and > you can imagine the way I see the admin pages... Have you read the information about serving static admin files? It's linked from a couple of places in the docs (particularly from the admin documentation), but unfortunately the mod_wsgi documentation is still missing a few of those bits, so the link from there is missing. In any case, make sure you've read this: http://docs.djangoproject.com/en/dev/howto/deployment/modpython/#serving-media-files > > I also have some problem serving uploaded file which are in the MEDIA > directory. I have see the problem is in the link for downloading the > file. It points to 'http://localhost:8000/path/to/file' I think the > problem is in the ":8000". Sounds like your MEDIA_URL setting isn't correct, since that is what is used to derive the initial portion of the hostname for media links, unless you've done something really customised in your model's file fields. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Unit test failing with 302 instead of 200, using Django's TestCase class
On Wed, 2009-08-05 at 10:45 +0100, Paulo Almeida wrote: > Ok, so with APPEND_SLASH = False , I get a 404 (so no > response['location']) , but the response.context still has all the > variables like MEDIA_URL, LANGUAGES, LANGUAGE_BIDI, and not the ones > it should have. It still has also: > > {'request_path': u'/myflow/experiment/1'} > > I also tested another view, with URL: > > response = self.client.get('/myflow/experiments') > > This one works, and it has a list of experiments which links to the > view that isn't working. The link in response.content is: > > a href="/myflow/experiment/1" > > as it should be, and as it works outside tests. Also, from > that /myflow/experiments response.content I can tell that the fixtures > are being loaded, so it should not be a problem of experiment 1 not > existing. > > If you can suggest anything else I may try, please do. It's time to use the scientific method. Make the smallest self-contained example possible that exhibits the problem. A single test case in a file that uses Django.TestCase. A single view that does nothing but returns a constant string. A single URL pattern, etc. Remove everything that you possibly can. If you find you cannot remove a particular chunk of functionality (a URL pattern or a view or a template or whatever), then you know where to look for the problem. You have a lot of things in flight here all at once. Throw as many overboard as you and eliminate the moving parts. What's left is the problem you're trying to solve. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: overwrite User model
On Wed, 2009-08-05 at 01:43 -0700, Shuge Lee wrote: > django.contrib.auth.models.User > > I don't like models.User, but I like Admin view, and I will keep admin > view in my application. > > How to overwirte models.User You can't. Django relies on the existing User model. There are *plenty* of threads on this list that discuss how to use email addresses for login for user-exposed forms. One that was active less than 24 hours ago, even. Perhaps you might want to have a browse of those to find alternate solutions to your problem. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: HttpResponseRedirect and encoding
On Wed, 2009-08-05 at 01:32 -0700, alecs wrote: > Sorry :( > > return HttpResponseRedirect(path) brings Internal Server Error: > > > cat /var/log/apache2/error.log [... snip ...] I can't immediately see why Python's urljoin() function is trying to do encoding/decoding at the point this explodes, but clearly it isn't happy with non-ASCII str objects. We might have to work around that in Django. It seems it should be possible to reduce this to a fairly simple test case of just returning an HttpRedirect with a UTF-8 encoded string, although I don't have time to sit down and work out the details right at the moment and my trivial attempt worked without error, so there's something special going on. I'm prepared to say this might be a Django bug (it's a mini-bug that we're not working around Python being slightly awkward). Probably worth opening a ticket, if there isn't already one in this area. If you can find a simple case that reliably demonstrates the problem, that would be useful, too. I might have just made a silly error when trying to create a standalone just now, but I can't stop to spend any more time on it. > if I set return HttpResponseRedirect(path.encode('utf8')) then I'm > getting: [...] > > Traceback: > File "/usr/share/python-support/python-django/django/core/handlers/ > base.py" in get_response > 91. response = callback(request, *callback_args, > **callback_kwargs) > File "/usr/share/python-support/python-django/django/contrib/auth/ > decorators.py" in __call__ > 78. return self.view_func(request, *args, **kwargs) > File "/var/www/filez/filezupload/views.py" in send_file > 256. return HttpResponseRedirect(path.encode('utf8')) > > Exception Type: UnicodeDecodeError at /file/ > f5c27ee3982ebf701793038d22c72980d64793f566cb0ac10269ee0b > Exception Value: ('ascii', '/var/upload/alecs/\xd0\xa6\xd0\xb5\xd0\xbb > \xd0\xb5\xd0\xb2\xd1\x8b\xd0\xb5 \xd0\xbf\xd0\xbe\xd0\xba > \xd0\xb0\xd0\xb7\xd0\xb0\xd1\x82\xd0\xb5\xd0\xbb\xd0\xb8 > \xd0\xb4\xd0\xb5\xd1\x8f\xd1\x82\xd0\xb5\xd0\xbb\xd1\x8c\xd0\xbd > \xd0\xbe\xd1\x81\xd1\x82\xd0\xb8 \xd0\xbd\xd0\xb0 2008 \xd0\xb3\xd0\xbe > \xd0\xb4.jpg', 18, 19, 'ordinal not in range(128)') That suggests to me that "path" isn't a unicode string in the first place. You see that sort of error if you try to encode data that is in a str object -- i.e. it is already UTF-8 encoded. I would suggest trying passing in path.decode('utf-8') -- converting the string back into unicode. It's possible I missed an edge-case when fixing bug #10267, since the tests included there only check for unicode strings being used in the Location header (for the non-ASCII case). Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Select_related and foreign keys
On Wed, 2009-08-05 at 18:27 +1000, Brian May wrote: > On Wed, Aug 05, 2009 at 04:34:49PM +1000, Malcolm Tredinnick wrote: > > since it returns a *new* queryset that you cannot save to anything in > > the template. > > errr... What about: > > {% with object.object_set.select_related as set %} > ... > {% endwith %} Hence why I said it wasn't particularly useful. I didn't say it was entirely useless. Note, in passing, that the above will retrieve more data than you want, since it will follow the forwards relation back to the very object you started from (unless it's a nullable ForeignKey). If you need to precise control that select_related() offers, using it in the view is better practice. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: HttpResponseRedirect and encoding
On Wed, 2009-08-05 at 01:12 -0700, alecs wrote: > I'm trying to download via GET a file with name in russian and getting > Internal Server Error: > > upfile = UpFile.objects.get(file_hash=file_hash) > path = os.path.join(settings.UPLOAD_ROOT, request.user.username, > upfile.file_name) > return HttpResponseRedirect(path.decode('utf8')) > > If filename in English everything works ok. So which part of the above lines is causing the problem? Put in some print or logging statements to work out which piece of data is the problem and you'll at least have to something to work with for debugging purposes. It could be caused by anything at the moment. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Can i rise 404 from my middleware ?
On Wed, 2009-08-05 at 09:29 +0300, Mirat Can Bayrak wrote: > On Tue, 4 Aug 2009 16:47:37 -0500 > Alex Gaynor wrote: [...] > > Right now there is a bug in django's middleware where it doesn't > > correct catch exceptions: http://code.djangoproject.com/ticket/6094. > than... what should i do? Don't raise an exception. A 404 exception is eventually turned into an HttpResponse with the appropriate status code, so construct one manually and return that from the middleware. Once you return a response, no further processing happens (for request middleware). That's one of the major points about middleware. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: need help with model design and table relationship
On Tue, 2009-08-04 at 14:40 -0700, Unnamed_Hero wrote: > > > And you still haven't reduced it to a simple case that fails with a > > specific piece of data at the interactive prompt. You are trying to > > debug through three layers of curtains here. Why not remove the extra > > layers and work directly with the ORM to debug an ORM problem, as I > > suggested in the first piece of email? > > I have tried to work in interactive shell, re-read django docs, but > still - > relation "C12B_boss" does not exist. (I'm using postres, and it is > error not from django, but from DB) That's unsurprising. The problem isn't going to suddenly vanish! It's going to be easier to debug because you'll be able to find a single piece of data that demonstrates the problem. Then you will be able to construct a smaller example that shows the problem so that we can try it out for ourselves. Also, as I've suggested previously, look at the SQL schema Django is generating. Compare that to what you're trying to match in the existing database and work on making the differences go away. There is nothing more I can do to help you here. You need to reduce things to a much simpler example to isolate the problem. This is fundamental debugging technique and there is no avoiding it. Only you have access to the system that demonstrates the problem. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Getting at the fields querysets of a form in a formset
On Tue, 2009-08-04 at 14:30 -0700, bnl wrote: > Hi Folks > > I'm trying to move up from a complex form based on a model declaration > to a model formset built on the same idea. > > I have a model which has some stuff that looks something like > > class Vocab(models.Model): > ''' Holds the values of a choice list aka vocabulary ''' > name=models.CharField(max_length=64) > class Value(models.Model): > ''' Vocabulary Values ''' > value=models.CharField(max_length=64) > vocab=models.ForeignKey(Vocab) > class Coupling: > couplingType=model.ForeignKey(Vocab) > class CouplingForm(form.modelForm): > class Meta: > model=Coupling > class MyCouplingForm(CouplingForm): > def __init__(self,*args,**kwargs): > CouplingForm.__init__(self,*args,**kwargs) > vocab=Vocab.objects.get(name='couplingType') > self.fields['couplingType].queryset=Value.objects.filter > (vocab=vocab) Next time you're down at the store, you might want to pick up a few blank lines to use in your email between the class definitions. The above is very difficult to read. > > It's a bit more complex than that (understatement, I hope I haven't > mucked up the actuality in simplifying it), but I hope you get the > picture ... > > Anyway, that works fine ... but now I want to build a formset not just > a form ... > > Ideally, I want to apply the same logic to the formset that I do to > the form (via subclassing). However, I can't quite work out how to do > it. This request doesn't necessarily make sense. A formset is not a form. It's a set of forms. So *what* logic, specifically, are you trying to apply here? I'm really struggling to understand what you're trying to do, but maybe, *maybe*, this will give you an idea about how you can customise the forms in a formset and you can twist that your to your particular preferences. It will at least show you some of the relevant methods to examine: http://www.pointy-stick.com/blog/2009/01/23/advanced-formset-usage-django/ Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Select_related and foreign keys
On Tue, 2009-08-04 at 09:05 -0700, Joe LB wrote: > Hi all, > > I'm trying to access the related objects in the template by using > > {{ _set.select_related}} This isn't particularly useful in a template. Select_related() doesn't change the values you have access to and it isn't going to save you any extra database queries on subsequent uses of the original queryset, since it returns a *new* queryset that you cannot save to anything in the template. > > this works but as its not an instance and it's a query object I get > > [] > > What do I use to just display the string not the object code. What you are seeing is Python's default repr() display for a QuerySet, which is actually the repr() display of list(queryset). If you want to see the results, you have to iterate over the queryset and display the unicode() or str() value of each element. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: subclassed ModelForms initial values behavior changed from 1.1beta to 1.1
On Tue, 2009-08-04 at 22:23 +0800, Russell Keith-Magee wrote: > On Mon, Aug 3, 2009 at 3:46 AM, David Haas wrote: > > > > It looks like the change happened between rev. 10189 & 10190: 10189 > > displays the value, 10190 doesn't. > > > > Unfortunately, I don't think I can give you a completely unbiased > > answer as to what behavior I think > > is more correct, because of history and personal use :) > > > > With that out on the table, though, it seems to me that if you are > > using a model form, and you're initializing > > it with a model instance, and that model instance has a current value > > for a field on your form, the form > > ought to get initialized with that value, regardless of whether or not > > you plan on eventually saving the > > field in the database or not. If you're going to display it, it ought > > to reflect what's currently in the database. > > I think I've read some stuff about eventually making 'read only' > > forms, or marking fields on a form as 'read only', which seems like it > > could tie into this somehow, eventually, maybe. > > > > If you agree with that, though, then currently both ModelForms & > > ModelFormsets initialization is broken, because > > neither fills in the values. > > Thanks for taking the time to do the analysis and explanation. I've > now had a closer look at this - unfortunately, I'm inclined to say the > exact opposite. I think ModelForm is doing the right thing. > My reasoning stems from the fact that we are dealing with a ModelForm, > not just a Form, and the 'Meta' definition is the highest source of > authority. > > DataParentForm defines a Meta relationship with the DataParent model, > and explicitly defines that only the 'name' field is to be exposed. > > DataChildForm inherits from DataParentForm, and while it overrides the > model relationship, it doesn't override the fields definition - so at > this point, we have a ModelForm on DataChild that only exposes the > 'name' field. > > Then, you have added a 'value' field to the model. While this does > share the name of a field on the model, this is a coincidence - you > have explicitly stated that you don't want the 'value' field from the > model to be involved on the form. The 'value' FloatField could be > called anything else without error - by virtue of the inherited Meta > definition, it bears no relationship to the underlying model. > > If, on DataChildForm, you add a fields definition: > > fields = ['name','value'] > > the explicitly defined FloatField becomes an override of the default > form element rather than a standalone form element, and as a result > the initial data is populated. > > The behaviour for ModelFormSet is then consistent with that seen in > the ModelForm. > > So - to my mind, the v1.1 behaviour of ModelForm is doing the right > thing. I agree that this is a nasty edge case though, and I'd be > interested to hear if anyone has any differing opinions or reasoning. For what it's worth, I agree with Russell's analysis here. If you're inheriting from a parent class, you are saying your subclass "is-a" instance of the parent and you can't put back things from the model the parent has already excluded. That isn't "is-a", it's "same-but-different". Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Multiple instances of the same form on one page: how to get the right POST data?
On Tue, 2009-08-04 at 07:07 -0700, Berco Beute wrote: > I'm trying to add multiple instances of the same form on one page, > each with its own submit button. I know how to use the 'prefix' > argument for a form to differentiate between forms, but I can't figure > out how to get the right data when it is POST'ed back (see view.py > below). Somehow the form stays invalid, no matter what I try. Any > suggestions what I may be doing wrong? > > Thanks! > > =models.py=== > class Invite(models.Model): > invitation= models.ForeignKey(Invitation, verbose_name=_ > ('User')) > email_address = models.EmailField(_('email address')) > status= models.CharField(_('RSVP status'), max_length=1, > choices=settings.INVITE_RESPONSE_CHOICES) > > > > =views.py=== > def invite_resp(request): > invites = Invite.objects.all() > if request.method == 'POST': > invite_formz = [InviteForm(request.POST, prefix=str(index), > instance=invite) for index, invite in enumerate(invites)] > if all([invite_form.is_valid() for invite_form in > invite_formz]): > invite = invite_form.save() > return HttpResponseRedirect('/') > invite_forms = [InviteForm(instance=invite) for index, invite in > enumerate(invites)] You forgot to set the prefix here, so the form that the user is submitting their data from doesn't have the fields named correctly. You need to set it up exactly the same way at this point as you did in the POST path, with the exception of not prepopulating with data. Also, you've almost certainly left off an "else" clause here. You only want to create new, empty forms if the method is not POST (you can fall through to this point with request.method == "POST" and one of the forms being invalid). Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Multiple Logins
On Tue, 2009-08-04 at 06:28 -0700, lfrodrigues wrote: > Hi, > > I've developed a special Auth backend for a internal communication > protocol. Everything was ok but now the requirements changed and I > need to allow on the same browser (in diferent tabs) several logged > users. > > How can I have (in the same browser process) several logged users at > the same time? This is not particularly easy, but it's not impossible. The default Django session/auth combination stores the current sessionid in a cookie. That cookie is per-browser (since that's how cookies work), so you need to avoid collisions there. In fact, it seems like you'll have to end up writing your own session replacement and auth middleware to correctly set the User instance in the session. There's really no way to know which tab or window submitted the URL from a single browser, so you'll also need to include some information about hte current user in the URL so that the server side can work out which user you're meant to be inpersonating for this particular request. This is why RESTful design encourages staying away from cookies for this sort of purposes, because it's not stateless. Django's session framework is not RESTful and you're seeing the results of that. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Specifying a join table for a customized query
On Tue, 2009-08-04 at 18:41 -0700, Daybreaker wrote: > See a recent thread here: > > http://groups.google.com/group/django-users/browse_thread/thread/0ee03167b7b5e873/850ac8304bf952b4#850ac8304bf952b4 > > and this query: > > mymodel.objects.extra(select={'ordering_field': 'IF(STRCMP > (bbs_tag.name, 'notice'), '',bbs_tag.name)'}, > order_by=['ordering_field']) > > bbs_tag (=Tag._meta.db_table) should exist in the queryset, so I added > a filter condition: tags__name__contains='' to make Django to perform > a join. Urgh. Not pretty or particularly robust. It would be entirely fine for Django to hypothetically optimise away that filter condition, for example (it doesn't now, but that's not to say it will never do so). The extra() method already takes "tables" and "where" parameters, so you can use those to set up the join in a more self-contained fashion (all the custom stuff is in extra()). Or look into writing a custom Q-like filter. That isn't documented, since it's not really public API, but it's fairly easy to work out from starting at django.db.models.sql.query.Query.add_q() to see what the API looks like and it isn't going to change significantly in the near future -- in fact, it will probably become public API pretty soon by virtue of getting documented. We have enough experience now to know how that particular API shoudl work. > > Article.objects.filter(belongs_to=board, tags__name__contains='').extra > ( > select={ > '_ordering':"CASE bbs_tag.name WHEN 'notice' THEN '' END", > 'is_notice2':"bbs_tag.name = 'notice'", > }, > order_by=['-_ordering', '-written_at'] > > But this query produces 7 objects with one duplicated. > (Note that IF clause is a mysql-specific extension, so it's better to > use CASE clause that is standard.) > > The result set is a list of Article instances, but inside the query, > tags should be joined and processed. > How do I do this in more clear way? Write the SQL directly. If you want ultimate control over the SQL, then write SQL. If you want to and can express your query using the Python models and other Python objects, use Django's ORM. However, the ORM is not intended to be a 100% replacement for SQL; we already have SQL for that. In particular, the ORM does not work in terms of specifying joins between tables. It allows you to follow relations between models, which translates to joins (sometimes), but it's not a one-to-one relationship. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Apache and mod_wsgi on Ubuntu
On Tue, 2009-08-04 at 17:12 -0700, Steve1234 wrote: > I am trying to setup Apache and mod_wsgi on Ubuntu to run Django > content. I generated a minimum project using "django-admin.py > startproject mysite" creating the project in my home folder. Running > the development server works and shows the "get started" page. But > the "production" setup returns "Internal Server Error". The Apache > error.log file reports: > > ImportError: Could not import settings 'mysite.settings' (Is it on > sys.path? Does it have syntax errors?): No module named > mysite.settings > > My /etc/apache2/httpd.conf file has one line: > WSGIScriptAlias / /home/steve/mysite/apache/django.wsgi > > And the file /home/steve/mysite/apache/django.wsgi has 6 lines: > import os > import sys > sys.path.append('/home/steve/mysite') > os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' > import django.core.handlers.wsgi > application = django.core.handlers.wsgi.WSGIHandler() > > Any idea what I am doing wrong? You've set the Python path incorrectly. This is easily the most common error people make and I'm surprised you didn't find it in the searches you did in the archives before posting. This isn't anything Django specific. The Python path contains the directories from which imports are started. So if you want to import something called "mysite" it has to exist inside one of the directories on the Python path. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Django profiling logs (Like rails Mongrel logs) ?
On Mon, 2009-08-03 at 22:05 -0700, Kedare wrote: > Hello, > Is there any wait to implement the same kind of logging that Rails > provide, by example : > > Processing BlogController#list (for 127.0.0.1 at 2007-02-23 > 00:58:56) [GET] > Parameters: {"action"=>"list", "controller"=>"blog"} > SELECT * FROM posts ORDER BY created_on LIMIT 10 > Rendering blog/list > Cached page: /blog/list.html (0.0) > Completed in 0.18700 (5 reqs/sec) | Rendering: 0.10900 (58%) | DB: > 0.0 (0%) | 200 OK [http://localhos//blog/list] > > I can't find any plugin to provide that... > I find that kind of thing very useful to understand what can be the > bad query or caching strategy, are Django developpers plaining to add > a features like that ? The django-debug-toolbar project gives you a lot of that information in a browser-based view. Worth looking at. One day something like the debug toolbar might be added to Django itself, but all things that are developed as successful external projects first. It might not be too hard to write some kind of logging output like what you're after based on the information that django-debug-toolbar collects. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: formset consisting of multiple models/forms
On Mon, 2009-08-03 at 20:29 -0700, sico wrote: > Hi, > > Just to clarify here, I really want to keep using forms.ModelForm to > avoid having to redefine any data types and labels. I could create a > single form that has all the fields I want and use that in a formset. > But then I have to duplicate the field/model definitions and also > handle the binding of the data from the form to the model. Firstly, you don't necessarily need a formset here. You can use multiple Django Form subclass objects in a single HTML form. So you can create you sequence of ModelForms and pass them into your template and render them all however you like. Then validate them each in turn and if is_valid() passes, you're set to go. Alternatively, you can create a BaseFormSet subclass and override the _construct_form() method to produce each of your model forms in turn (the index "i" that is passed in is the form number in the formset). That's a small variation on the technique I use in [1], except you're no longer using formset_factory() or modelformset_factory(), as you want a fairly different form instance returned for each call to _construct_form(). There *might* be some curly bits to work around with respect to populating the data correctly in such a customised formset, so be prepared to experiment a bit and read the source. [1] http://www.pointy-stick.com/blog/2009/01/23/advanced-formset-usage-django/ Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Changing domain cookie
On Mon, 2009-08-03 at 17:51 +0100, Chris McCormick wrote: > Hi All, > > I have a strange issue happening with domain cookies. On the site I'm working > on we previously didn't have SESSION_COOKIE_DOMAIN set and so the cookie > defaulted to "Host: mysite.com" We have a bunch of users logged in with that > cookie set. Then we decided we wanted to share the cookie with our subdomains > and so we change SESSION_COOKIE_DOMAIN to be ".mysite.com" which seemed to > work > at first. We are now getting a weird issue which I have narrowed down to users > having two of the same sessionid cookie set, but one has "Host: mysite.com" > and > one has "Domain: .mysite.com" which seems to be confusing Django. The > "confusing Django" behaviour I am experiencing is that when the user logs in, > the cookie seems to switch to use the one I don't want and won't log them in. > E.g. on the Django side the login seems to work, but the user just gets a > logged out screen. Does anyone have any tips on what Django is doing > internally, and how I can fix this issue? Oh yeah, in some of my views I am > doing request.session.set_expiry(distant_future()) - is there a chance this > could be messing with the login process? I have stopped the weirdness by > unsetting SESSION_COOKIE_DOMAIN, so people can log in again successfully now, > but I'd really like to be able to use the wildcard subdomain thing. Python's Cookie module doesn't handle multiple cookies of the same name very well, so there might be something going on there. But I'm not going to spend too much time thinking about this, since there's an easy solution: In addition to changing the cookie domain, change the session cookie's name. That way you will no longer be looking for the old cookie at all (Django won't care about it) and you can just work with the new name that will only exist with one domain setting. Everybody will appear to be logged out the next time they use the site, but that shouldn't be too onerous. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: need help with model design and table relationship
On Mon, 2009-08-03 at 08:27 -0700, Unnamed_Hero wrote: [...] > And I still get > Caught an exception while rendering:relation "C12B_boss" doesn't > exist And you still haven't reduced it to a simple case that fails with a specific piece of data at the interactive prompt. You are trying to debug through three layers of curtains here. Why not remove the extra layers and work directly with the ORM to debug an ORM problem, as I suggested in the first piece of email? Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Aggregates over reverse relationships?
On Mon, 2009-08-03 at 17:45 +0300, Shai Berger wrote: > Hi all, > > With the new aggregates in django 1.1, I wonder if there's an easy way to > aggregate over reverse relationships. As an example, assume a simplistic > representation of a set of teams: > > class Team(models.Model): > name = models.CharField(max_length=100) > > class Player(moedls.Model): > name = models.CharField(max_length=100) > team = models.ForeignKey(Team) > > Now, I want to perform some operation on all the empty teams -- so I want to > do something like > > Team.objects.annotate(num_players=Count('player_set')).filter(num_players__eq=0) So what happened when you tried this? It looks like it should work and I use similar sorts of queries with success in existing code. > There may be some obvious way (which I'm currently missing) to solve the > specific problem of finding the empty teams without such aggregates; There is. :) Team.objects.filter(player=None) which is the same as Team.objects.filter(player__isnull=True) Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: UserProfile and select_related
On Mon, 2009-08-03 at 08:10 -0700, lfrodrigues wrote: > Isn't there any way to cache profile data on User side? This already happens when you call get_profile(). If you mean using a mass query, then you have just asked if there is a select_related() equivalent for reverse relations. For the answer to that, see my previous mail in this thread. > When are you > planning on closing 7270? When it is appropriate. The patch needs some fixing and it didn't make the cut for 1.1. It's a good candidate for 1.2, but the answer is always "when it's ready". > > A lot of my code uses get_profile in templates and that is always a > query. Isn't it possible to optimize this? Everything is possible. Asking the same question three or four times isn't the way to do it, however. It's been explained in this thread what you can do at the moment. Querying UserProfile instead of User is a very practical technique. Some quite large sites use it in that fashion (I'm not at liberty to disclose names, so you can trust me or not). Does this mean you can just pass around a bunch of User objects and not have to do any code changes? No. But optimisation almost always involves some code changes and passing around UserProfiles instead isn't particularly illogical. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Using email instead of username in extended "User" model?
On Mon, 2009-08-03 at 13:13 -0700, Dana wrote: > Ok, I understand the login part but what about registration? Wouldn't > the user's need a username still? Or am I misunderstanding... And what > about Django admin, it would still need a username correct? Nothing stops you from creating a random string to populate the username field with. It has to contain a unique identifier and it's often useful if that is actually identifiable -- perhaps created from an amalgam of the user's first and last names or something -- but it could be entirely random, providing it is unique. So when you are registering the user, just create a username string however you like. The user themselves doesn't have to know or care what it is. The thing is, their username won't change, their email address might (one of the many small problems with email addresses as unique and unchanging identifiers). Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Date format in modelform.
On Mon, 2009-08-03 at 11:08 -0700, zayatzz wrote: > Hello. > > I have this in my form (modelform) for birth_date field: > birth_date = forms.DateField(('%d/%m/%Y',), label='Birth Date', > required=False ), which overrides this in model: > > birth_date = models.DateField(help_text="birth date", > verbose_name="Birth date", blank=True, null=True, ) > > I also have jquery datepicker on the page which sets date in the same > format (%d/%m/%Y). But the form saves date in %Y-%m-%d format in > database, That isn't quite correct. Databases do not save datetimes as strings in any particular format. They save them as some kind of internal object. What you are seeing is that the widget rendering is using the %Y-%m-%d format for some reason. You should investigate that part of the code more closely. It won't involve the database at all (although it might be the path of creating a form from your model data that shows the issue -- so try to simulate that without using the database at all). Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Date/time field styling?
On Mon, 2009-08-03 at 11:29 -0700, mhulse wrote: > Hello, > > {{ form.start }} > > For example, outputs this: > > > > > I have tried: > > {{ form.start_0 }} and {{ form.start_1 }}, but that outputs absolutely > nothing. :) > > Is it possible to split up the two fields so I can handle them > individually? Look at the SplitDateTimeWidget in django.forms.widgets. > > Also, is it possible to control the XHTML output? I prefer use a DTD > that does not allow an ending slash. :) Django outputs XHTML. You don't get to control that. If you want different output, you will need to write different widget classes and customise each render() method on the widgets (all the output is done by the widgets, so it's nicely encapsulated). Search around before doing that, however. I have a vague feeling that somebody might have started a project like this, but I haven't ever used it. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: 'str' object is not callable
On Mon, 2009-08-03 at 09:51 -0700, Dolph wrote: > hey Ronghui, > > Thanks for the reply. I couldnt get your first suggestion to work, I > get "name 'coltrane_category_detail' is not defined". Also, Which is exactly what the problem is. In the first email you posted, you don't have any view called coltrane_category_detail. You do have one called category_detail that is in the coltrane module, so you might be intending to write coltrane.category_detail, or maybe you mean something else. In any case, the error message is correct: the function you are trying to dispatch to does not exist. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: why is not IntegrityError an attribute of models?
On Mon, 2009-08-03 at 07:36 -0700, dnedbaylo wrote: [...] > I was thinking about a case where try clause contains couple of save() > calls of different models and each model has unique field. And there > is no way to catch specific to model IntegrityError, > you can catch only "general" IntegrityError not bound to specific > model... That's because IntegrityError is something raised by the database layer. It is *not* bound to any particular model. It is the result of some table constraints being violated, so doesn't correspond directly. In other words, what you're asking for doesn't really make sense for the type of error that IntegrityError is. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: many to many model
On Mon, 2009-08-03 at 03:49 -0700, elminio wrote: > Hi, > tahnks for reply I added additional ManyToManyfield to one table and > admin panel looks ok but in fact even using syncdb new intermediate > table wasn't created. > Is there anything else I should do ? Syncdb does not incrementally update models like this. You will either have to look at the output of "./manage.py sql" and then manually add the necessary pieces, or use something like "./manage.py reset" to drop and recreate the model's tables (which will throw away the existing data), or use a tool like South to do the database migration. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: need help with model design and table relationship
On Mon, 2009-08-03 at 03:19 -0700, Unnamed_Hero wrote: > Thanks for your reply. > > And the point is that (forgot to say)... the boss field in c12b table > doesn't exists, it is virtual and exists only in my model. When you add a ManyToManyField to a Django model, it doesn't create a column in that model's database table, so that shouldn't be a problem. However, db_column doesn't make sense on a ManyToMany field, for precisely that reason. Either you use a "through" table to specify the columns via the intermediate table, or it will refer to the primary key field on the model. > I think, > this trick can work for me, but I've got (c12b_boss relation does not > exist). I thought, that if I point it to a real A22 field (unique code > field) through "db_column" directive, because there are several tables > with such relations...; but I failed. And I still can't clearly > understand what odel design I need. One way to try to work out whether your model is close is to look at the output of "manage.py sql " and compare that to the SQL you are trying to achieve. Then you can at least work out what fields need to be changed. > PS. Such field's names, data structure - are not mine work. this > database was designed over 15 years ago, and maintained by other > people... The name of the database columns does not prevent you from having descriptive names for the model fields. It's well worth the time, for your own sanity, and ours, to do so. Use the db_column parameter on each model field to then set the database column name correctly. That is a nice feature of Django's design: you can still give the Python-level attributes reasonably understandable names, no matter what sort of database naming scheme was in place. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: UserProfile and select_related
On Mon, 2009-08-03 at 02:48 -0700, alant...@neei.uevora.pt wrote: > Hello, > > I'm displaying lot of user profile picture with are on a user profile > (i'm using contrib.auth). So for each picture I have a query for the > user profile. > > I wanted to use User.objects.filter(stuff).select_related > ('userprofile') but this has no effect. Any ideas how to prevent the > +200 queries from happening? The link between the two models runs from UserProfile -> User, not the other way around. The select_related() call only follows forwards links, so it will not traverse from User to UserProfile. It's not completely trivial to add backwards-link following, particularly because there can be multiple values for backwards links. However, you can often turn this type of query around. Instead of filtering User objects, filter Userprofile objects, where you can use select_related(). Thus User.objects.filter(username="fred") becomes UserProfile.objects.filter(user__username="fred").select_related() The main trick here is that each condition needs the "user__" bit prepended, so a little munging of filters -- either automatically or by hand -- is required. You can still access the User instance attributes via obj.user.username where "obj" is now a UserProfile instance. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Non html safe chars on urls,
On Mon, 2009-08-03 at 12:27 +0300, Mirat Bayrak wrote: > Hi i have an account system that you have to validate your email after > you created an account. My validation url is lik : > www.foo.com/account/confirm/username/keyyy > > But there is a problem, sometimes username contains non html safe > chars for example : âlice, or süleyman cant go that adress... > > So, what should i do? should i restrict usuable characters on > usernames or is there another solution? Django provides some utility functions for creating valid URL's from UTF-8 strings. Have a look at the iri_to_uri() function, documented here: http://docs.djangoproject.com/en/dev/ref/unicode/#uri-and-iri-handling (Yes, that is a little bit hidden. Linking things in from all the useful places is a continual process.) Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: many to many model
On Mon, 2009-08-03 at 02:24 -0700, elminio wrote: > Hello, > > My problem is that I have (for example), a model teacher - subject > many to many. So that I made additional table named teacherSubject > with both ids. Instead of thinking about what database tables would be created, use Django's ORM as a Python tool. You want a relationship between the Teacher and Subject models, so use the ManyToManyField() to create one. Django will take care of creating the intermediate table and doing joins with it correctly in queries. Manually creating the intermediate table is making things much harder on yourself. At a minimum, even if you create the intermediate model yourself, you will need to use the ManyToManyField() on either the Teacher or Student models and use the "through" parameter to describe the intermediate model. Otherwise Django cannot know that teacher and student are directly related. It thinks they are second-level relations, which isn't so easy to map in the admin interface. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Caching template fragments without specifying expiration time
On Mon, 2009-08-03 at 01:00 -0400, Nick Fishman wrote: > > and suggests otherwise). It might not be too difficult to add support > > for an optional timeout, although the error checking requires a lot of > > care. > > I think that's the main problem. Since arguments to {% cache %} aren't > named, it doesn't seem possible to differentiate {% cache 500 key1 > key2 %} from {% cache user.id key1 key2 %}. In the first case, 500 > represents a timeout. In the second case, user.id might resolve to 500 > and represent a _key_ rather than a timeout. I'm not sure of an > elegant way to deal with this. Right. I hadn't thought of (ab)using it like that to just cache a random variable (why not do it in the view in that case?!). It's more intended for caching rendered template fragments and I thought you'd be able to tell when the first thing was a number it's a timeout and when it's a string it's a template fragment. > I'll probably stick with setting a large constant in a > context_processor and using that as the "effectively expire never" > time. I'd have to use a similar trick when using the low-level cache > API, anyway. Or you could do it the easy way and spend three minutes writing a template tag that uses the default cache value. Remember, you are *encouraged* to write your own template tags to scratch itches. You already have an example to work from. :) Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Retrieving the values from query set
On Sun, 2009-08-02 at 21:59 -0700, bvemu wrote: [...] > Is there a django way of retrieving only the values as a list and not > the fieldname Have a look at the values_list() method. That does what you are after. http://docs.djangoproject.com/en/dev/ref/models/querysets/#values-list-fields Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: locking up development server
On Sun, 2009-08-02 at 21:01 -0700, Rusty Greer wrote: > i added a column to one of my tables in my db. i added the column in > the model definition, then i went into mysql and added the column with > what i think is the appropriate alter table command. > the command i used was: > alter table db_game add column player_info_url varchar(200) not null; > > the code in the model is this: > player_info_url = models.URLField(blank=True) > > i am now able to update that table no problem from mysql. the new > field shows up just fine in the admin. i can edit other tables via > the admin, however, if i change the table i modified in the admin (not > just the new field), the development server seems to lock up. after i > restart it, all is fine until i edit that same table again. Locking up is a rare and unusual symptom. There's one intermediate test you haven't done (you've tried direct db editing and end-to-end through the web browser): can you query and edit the records via the interactive prompt? Another thing I would try is creating a copy of your settings file then modifying it to point to a database with a different name and trying a fresh install (so you aren't blowing away your current database). Then see if the problem reoccurs. You can also compare the sql from the two if there are differences in behaviour. > > i am not too concerned about the development server, i can nuke my db > and restart with that and i am sure the problem will go away. > however, when i go try to make the same change on my production > server, i don't want to have the same problems with it. any ideas > what i could have possibly done wrong? or how to fix it? will i have > the same problem with apache/wsgi on my production server. > > by the way i am running 1.0.2-final and mysql One important piece of debugging would be to upgrade to 1.0.3 as soon as you can, since there are about 6 months worth of bug fixes in there. I can't think of anything that's been added in the 1.0.X branch that would change this (the whole behaviour sounds *very * odd), but it wouldn't hurt to rule that out. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Using email instead of username in extended "User" model?
On Sun, 2009-08-02 at 20:21 -0700, Dana wrote: > Oops i mean username, not password. > > Im not clear on how I can get this to override the django login > functionality. Im reading more up on custom auth backends but Ill > admit it's a little confusing. You write a custom authentication function that compares the username and password supplied by the user in the login form against the email address and password fields in the User model -- fetch the User instance(s) matching the email address and then use the check_password() method on the User instance to see if it's valid. It should only a couple of lines of code in the skeleton code described here: http://docs.djangoproject.com/en/dev/topics/auth/#writing-an-authentication-backend Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: need help with model design and table relationship
On Sun, 2009-08-02 at 14:08 -0700, Unnamed_Hero wrote: > I have a table with a list of corporations; each corp has a field with > it unique number. > There is a table, filled with people, each record contains a field > with a corp's unique field (where each person works) > > Task: when displaying info about corporation, also fetch info about > people working at. > > Also there are several tables with such relationship with a corp > table. > > So, it seems to be a many-to-many relationship. > > there is come code > > class c12b (models.Model): > id = models.AutoField (primary_key=True) > A15 = models.CharField ('Телетайп', max_length=20, blank= True) > A17 = models.CharField ('Телекс', max_length=20, blank= True) > A19 = models.CharField ('Факс', max_length=40, blank= True) > A34 = models.CharField ('Код промышленности',max_length=5, > blank=True) > A29 = models.CharField ('E-mail', max_length=50, blank=True) > A30 = models.CharField ('Сайт', max_length=40, blank= True) > A3 = models.CharField ( 'ИНН',max_length=10, blank=True) > A21 = models.CharField ('Реквизиты банка' ,max_length=255, > blank=True) > A22 = models.CharField ('Код ОКПО', max_length=8, blank=True ) > #CORP INIQUE KEY > #here I've tried to create a related field > boss = models.ManyToManyField (Dolgnost, db_column="A22", > through='bosses_table') > class Meta: > db_table='C12B' > > class bosses_table (models.Model): > c12b = models.ForeignKey (c12b, to_field="A22") I'm surprised Django didn't raise a validation error here, since c12b.A22 is required to be a unique field in order to be the target of a to_field parameter and you haven't marked it as unique in the above model. > dolgnost = models.ForeignKey (Dolgnost, > to_field="A22",unique=False) > > > #in view.py > ... > result = c12b.objects.filter(A34__exact ="02100") > return render_to_response ("prkp/lista.html", { >"result":result, > ... > #template > {% for i in result %} > > {% for b in i.boss.all %} > {{ b.U1 }} > {% endfor %} > {{ i.boss.U1 }} > > Finally I've got an exeption > Caught an exception while rendering:relation "search_bosses_table" > doesn't exist I would start by removing as many variables from the debugging situation as possible. In particular, instead of debugging this through the template system, use an interactive shell. Work out the exist record in "result" that is causing the problem so that you can narrow things down to the exact piece(s) of data that are causing the problem. There doesn't seem to be anything immediately wrong with your models, although I would put some effort into naming the fields more descriptively ("A34" is hardly easy to debug when it pops up in a traceback). I would also simply make A22 the primary key of the c12b model (and probably the boss model as well, if it's similar) so that you don't even need the intermediate table and can just use a normal ManyToManyField. Generally, if you are using "through" on a ManyToManyField, it would be because the intermediate table contains more than just the two linking fields. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Caching template fragments without specifying expiration time
On Sun, 2009-08-02 at 04:25 -0400, Nick Fishman wrote: > I was wondering if it's possible to not specify the expiration time > when using the {% cache %} tag to cache template fragments. With the > low-level API, cache entries will expire after a timeout configured in > CACHE_BACKEND. Is it possible to use the same default when caching > template fragments? > > In particular, I'd like to use model signals to invalidate cache > entries. That way, entries won't be invalidated after an arbitrary > time period, but rather when they're actually invalid. Nathaniel > Whiteinge wrote on 2008-12-03 that the {% cache %} tag creates entries > with keys "fragment_name:additional:arguments:seperated:by:colons", so > this seems possible. The "cache" template tag always requires a timeout (although the docstring on the function in django.templatetags.cache.do_cache() lies and suggests otherwise). It might not be too difficult to add support for an optional timeout, although the error checking requires a lot of care. So you might want to have a swing at adding this support and open an enhancement ticket with a patch in Trac if you get that far. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Template and substitute
On Sat, 2009-08-01 at 19:29 -0700, David wrote: > Hi, > > When I tested sql of MySQL in Python interactive shell, I got an > error of "not enough arguments for format string". I checked the > arguments however I could not find anything wrong. > > Can anybody give me a clue? > > Thanks so much. > > > >>> sql = Template('select dimension1 ,adddate(current_date,-1),current_date, > >>> ifnull(sum(case when date_format(creation_date,\'%Y-%m-%d\') = > >>> adddate(current_date,-1) then ifnull($ss_1,0) end),0) as \'PreviousDay\', > >>> ifnull(sum(case when date_format(creation_date,\'%Y-%m-%d\') = > >>> current_date then ifnull($ss_2,0) end),0) as \'Today\' from > >>> message_alert where dataset_id = $ss_3 and dimension1 in ($ss_4) and > >>> hour(creation_date) = hour(now())-1 group by dimension1 having > >>> (ifnull(sum(case when date_format(creation_date,\'%Y-%m-%d\') = > >>> current_date then ifnull($ss_5,0) end),0) / ifnull(sum(case when > >>> date_format(creation_date,\'%Y-%m-%d\') = adddate(current_date,-1) then > >>> ifnull($ss_6,0) end),0)) $ss_7 $ss_8') > > >>> > >>> sql = sql.substitute(ss_1='metric1', ss_2='metric1', ss_3=2, > >>> ss_4='557796,558069,558230', ss_5='metric1', ss_6='metric1', ss_7='>=', > >>> ss_8=0.05) You seem to be trying to create raw SQL using Django's template system. Please don't do that. It's like trying to use a shovel to hammer in a nail, but less effective. You are also using something other than Django's templating system since django.templates.Template does not have a substitute() method. And Python format markers in strings are things start with "%", not "$", so "ss_1" and friends aren't variables in the string. If you are trying to create raw SQL, write it out as a string and pass the parameters in to the execute() call. Do not substitute them into the string first, since that is the easiest way to introduce SQL injection attacks. If you need more information about how to use cursor.execute(), have a read of PEP 249. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: using the stable api
On Sat, 2009-08-01 at 19:59 +, Faheem Mitha wrote: > Hi Malcolm, > > Thanks for the helpful reply. > > On Sat, 01 Aug 2009 12:24:29 +1000, Malcolm Tredinnick > wrote: > > > On Fri, 2009-07-31 at 11:42 -0400, Faheem Mitha wrote: [...] > >> 3) Get the sessionid. I had to change request.COOKIES['sessionid'] > >> to request.COOKIES[settings.SESSION_COOKIE_NAME] > > > The default value of settings.SESSION_COOKIE_NAME has always (and > > remains) "sessionid". However, it's a little more portable to use > > the latter form (request.COOKIES[settings.SESSION_COOKIE_NAME) in > > your applications, since then they are usable no matter what the > > setting happens to be. A Django application writer is not > > necessarily in control of the settings that will be used when the > > application is installed. > > To summarize, I've changed settings.SESSION_COOKIE_NAME from their > default value, so this breaks request.COOKIES['sessionid'], and in > this case, using request.COOKIES[settings.SESSION_COOKIE_NAME) is > preferable, because it will work no matter what the value of > settings.SESSION_COOKIE_NAME happens to be. Is that a correct summary? Correct. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Stopping people loging in twice
On Fri, 2009-07-31 at 20:56 -0700, django user wrote: > So is there a viable django solution for this problem? You can implement your own session support. It's not that difficult. Django is just a layer on top of Python, so there's a Django solution to any computable problem. Django's default contrib.sessions framework, however, is not going to be useful to you for this problem. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Stopping people loging in twice
On Fri, 2009-07-31 at 19:43 -0700, django user wrote: > I'm interested in a solution for this as well. > > I am thinking that a good way might be to rewrite the auth middleware > to check and see if a user login for this user exists and if it does > then remove that login and log in the current user. A message could > then be passed to the login page letting them know that they have > logged in elsewhere and their session at this computer was ended. HTTP is a stateless protocol. By design. As has been pointed out in another reply in this thread, the concept of "already logged in" is therefore no very well defined. Because it implies there is a concept of logged out. Which generally doesn't happen. All you can know is that you have seen a particular session cookie before. However, you are not guaranteed to know that you will never see a session cookie again in the future unless the user explicitly tells you to delete it. And that isn't always possible. What if you have browser-based sessions, so the cookies expires when the browser is closed. And now the user's browser crashes, or they shut it down, or their laptop battery runs out? They no longer have the cookie and so they cannot tell you to remove it. That's just one of a large number of scenarios in which you are setting things up so that users will not be able to use your site as a result of fairly normal behaviour of themselves and their computers. > > I don't know if django has a good way to query if the user is logged > in or not... You cannot query for session identifiers by username, no. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Dynamic Choices for ChoiceField
On Fri, 2009-07-31 at 16:31 -0700, mviamari wrote: > Hello, > > I'm trying to make a form for data entry into my database that uses > ChoiceFields for foreign keys. Obviously, the ideal choice would be > ModelChoiceField, however I'm not using the django ORM, so I've > assumed that's not going to work (I'm using Elixir/SQLAlchemy). > > I originally set the choices parameter in the ChoiceField declaration > to be derived from a query result from SQLAlchemy (returned as an > array of tuples). The problem is that the choices don't update when > the database changes. They are fixed to whatever was present when the > server is initialized (or at least it appears to be). If you have specified the choices field as a parameter to a Field subclass in a Form class, then it will be evaluated whenever that Form class is parsed (probably at import time). That's normal Python behaviour. > I'm looking for suggestions/advice on to get the ChoiceField choices > to update when the form is the used. "Used" is probably a bit ambiguous here. It's probably easier to think in terms of "when an instance of the form class is created." The solution is to update the choices attribute on the appropriate field in the Form subclass's __init__() method. For example class MyForm(forms.Form): options = forms.ChoiceField() def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) choices = ... # <-- create a sequence of 2-tuples self.fields["options"].choices = choices You can do whatever you like to populate the "choices" variable in the above fragment. The only requirement is that you end up with a sequence of pairs which are the submitted form value and the human readable text for the form element. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: how to get some related data from different tables to one queryset?
On Fri, 2009-07-31 at 14:42 -0700, Unnamed_Hero wrote: > I have something like this: > > class Translation1(models.Model): > code = models.IntegerField(primary_key=True) > description = models.CharField() > > class Translation2(models.Model): > code = models.IntegerField(primary_key=True) > description = models.CharField() > > class TranslationN(models.Model): > code = models.IntegerField(primary_key=True) > description = models.CharField() > > class MainDB (models.Model): >tr1_code = models.IntegerField() #code from Translation1 >tr2_code = models.IntegerField() #code from Translation2 >tr3_code = models.IntegerField() #code from Translation3 If these are meant to be referring to entries in the tables for Translation1, etc, then make them ForeignKey fields, not IntegerFields. The way you have set up your models, there is no way for Django to know there is any relationship here. [...] > For limiting fields I've created a manager for MainDB, and it works > fine. Then I've tried to do like this: > > > class my_MainDB (MainDB): >tr1_value = models.ForeignKey (Translation1) > > #views.py > result = my_MainDB.gos_req.select_related() #gos_req - my manager > > but I see it is wrong, because djando doesn't know that tr1_value must > be related to tr1_code field... [...] > Is my only way is using this RAW SQL? Unless you are able to fix your modelling, yes. You haven't modelled a system of related data. You have said there are various integers floating around, but not relationships between them. Regards, Malcolm > > > --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: using the stable api
On Fri, 2009-07-31 at 11:42 -0400, Faheem Mitha wrote: > > Hi everybody, > > I upgraded from somewhere around Django 1.0 to 1.0.2, and some things > broke and had to be changed. In the following, f is an object of class > 'django.core.files.uploadedfile.TemporaryUploadedFile'. I need to > > 1) Get the contents of the file corresponding to f. I had to change > f['content'] to f._file.read() > > From the docs (specifically, 'core/files/uploadedfile.py') it looks like > f.read() might be the right thing? The correct way to access uploaded file data is documented here: http://docs.djangoproject.com/en/dev/topics/http/file-uploads/#handling-uploaded-files That is the public API, and you are correct in thinking that read() is the method you're after here. > > 2) Get the filename of the file corresponding to f. I had to change > f['filename'] to f._name. This is also documented in the above reference. Use the "name" attribute on the UploadedFile isntance. > > 3) Get the sessionid. I had to change request.COOKIES['sessionid'] to > request.COOKIES[settings.SESSION_COOKIE_NAME] The default value of settings.SESSION_COOKIE_NAME has always (and remains) "sessionid". However, it's a little more portable to use the latter form (request.COOKIES[settings.SESSION_COOKIE_NAME) in your applications, since then they are usable no matter what the setting happens to be. A Django application writer is not necessarily in control of the settings that will be used when the application is installed. > > It is presumably better to use a stable API rather than less stable > internals, It is *always* better. :-) Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: "join" query in Django?
On Thu, 2009-07-30 at 23:42 -0700, Asinox wrote: > Thanks Malcom for replay, but, is not working for me, i think that is > simple just .filter("field1__field2"), but i cant make the join i try > with .filter("field1__field2") where the field1 is the PK and the > field2 is the FK. > > here is my query: > > p = Diligencia.objects.filter(Q(socio=request.user.id),Q(status=0) | Q > (status=1)| Q(status=3)).filter("id__diligencia") > > and the error is: too many values to unpack It's effectively impossible to debug this from the information you've provided, because we cannot see the model(s) you are trying to query against. I am, however, very suspicious of the bit that says filter("id__diligencia"), since "id" is almost always the auto-generated primary key field and not a reference to another model. Please construct some simple models that show the problem you're seeing. Also, the error isn't just reported as you say above. It also has a traceback in there, which is typically very useful, as it shows us where the error is coming from. > > im new with Django i cant understand this error, i searched and i cant > find answer about it. > > The another try was: > > p = Diligencia.objects.filter(Q(socio=request.user.id),Q(status=0) | Q > (status=1)| Q(status=3)).select_related() > > in this case i dont have errors but the data that i want to show from > the second table is not showing... and Django dont have any setting > function that will show the "SQL" that is happening in any query, You can try this approach, which shows the SQL after the query has been run: http://docs.djangoproject.com/en/dev/faq/models/#how-can-i-see-the-raw-sql-queries-django-is-running Or look at the output of p.query.as_sql() (where "p" is your queryset, above) to see the results of the SQL that would be sent to the database. Or look at django-debug-toolbar for a more in-browser view of thigns. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: How to save a model...
On Thu, 2009-07-30 at 12:33 -0700, zayatzz wrote: > ... Hello! > > I have a model (profile) which's only required field is its foreignkey > - django.contrib.auth.User. > > Following the example of forementioned model and its manager i created > manager for the profile: > > class ProfileManager(models.Manager): > def create_profile(self, username): > "Creates and saves a User with the given username, e-mail and > password." > now = datetime.datetime.now() > profile = self.model(None, username) > profile.save() > return profile It's very tricky to pass positional arguments to the __init__ method of a model. Django does it itself when it creates models, because it knows how the fields are structured, but it's very hard to get right and not recommended in normal code. Instead, use keyword arguments. So you would write something like this: user_instance = User.objects.get(username=username) profile = self.model(user = user_instance) profile.save() The other change I've made here is to retrieve the correct User object, since Django doesn't automatically know how to go from your "username" string to a particular User instance. > > and Profile model is like this : > class Profile(models.Model): > user = models.ForeignKey(User, unique=True) > .. > several other stuff all have null=True > ... > objects = ProfileManager() > > Now when i do this in a view: > profile = Profile.objects.create_profile(request.user) > > I get an error: > > Exception Type: TypeError > Exception Value: int() argument must be a string or a number, not > 'User' > > So why is this not working? For the future, it is highly recommended to post the full traceback. On the debug page you see in your web browser, there is a link that says "cut-and-paste view". Click on that to get something that is suitable for sticking in email. In this case, it's kind of possible to guess what was causing the error (although I may have guessed poorly). At other times, it isn't, so a little guidance from the traceback can often work wonders. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: "join" query in Django?
On Thu, 2009-07-30 at 21:23 -0700, Asinox wrote: > Hi, guys, how or where is the "join" query in Django? > > i think that Django dont have "join"..but how ill make join? SQL-level joins happen automatically when required. You specify your queryset in terms of filter() and exclude() calls and Django works out which tables are needed to compute that result. Links between models are specified using the double-underscore notation. Thus, "foo__bar" means to use the "foo" field on the current model (a link to a related model) and follow that to the "bar" field on the other end of the relation. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Custom Manage.py Commands
On Thu, 2009-07-30 at 17:18 -0700, mviamari wrote: > I'm trying to create a custom manage.py command for my project. The > example in the documentation only shows how to do this for custom > commands inside of an app. Is it possible to do the same at the > project level? The concept doesn't particularly make sense, since Django is app-based. "Projects" are a bit of a convenient way of grouping things, but they're just a settings file, a root URL conf and some apps. Which is a way of saying that isn't supported. It's fairly logical, however, to create an app that only provides your support for things like that this. Lots of people have apps that just contain template tags or just contain templates or even management commands. They don't need to contain models or anything like that. Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---
Re: Simple query on a ManyToMany field?
On Thu, 2009-07-30 at 18:14 -0600, Adam Olsen wrote: > Suppose I have the following models: > > class Tag(models.Model): > card = models.ForeignKey('Card') > name = models.CharField(max_length=10) > > class Card(models.Model): > # whatever > > Say I have a list, like the following: words = ['christmas', 'mother'] > > This list can be of variable length. How can I write a query that > will return a list of Card objects that match ALL (not any) of the > words? Is there a way to do it in a line or two without traversing > all of the card objects? I've written a couple of solutions for this over the years. Here's a summary of some of them: http://www.pointy-stick.com/blog/2009/03/10/using-djangos-aggregation-features/ Regards, Malcolm --~--~-~--~~~---~--~~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~--~~~~--~~--~--~---