Re: Turn off migrations completely in Django 1.7

2016-04-20 Thread Matt Schinckel


On Wednesday, December 2, 2015 at 6:31:31 PM UTC+10:30, john@gmail.com 
wrote:
>
> +1 for disabling migrations completely - for several reasons.
>
> 1. Right now, I'm trying to run tests against a production database with 
> runserver, in *read-only* mode - but it fails because it can't create the 
> django_migrations table.  (I'm in the process of upgrading from Django 1.4 
> to 1.8, so the table doesn't yet exist in production.) 
>

2. Our mysql database is 3TB, with some tables of up to 500GB - and I 
> assume that migrating them with Django - without taking the system down for 
> days - is not possible.  Instead, we use Percona's pt-online-schema-change, 
> which does an excellent job of migrating big tables, whilst keeping them 
> fully usable with no downtime.
>

When upgrading from 1.4 to 1.7+, you shouldn't be changing anything in the 
database. Sure, you'll want to build up the migrations, but you won't 
actually want to apply them, only fake them. If you are attempting to 
change your db structure at the same point in time as upgrading from 
pre-1.7 to post-1.7, you are making it much harder than it needs to be. 
(Yes, I'm going through the same process, with a database of similar size. 
Mine is postgres though).
 

> Point 2 is covered, I think, by setting all models to unmanged, as we do - 
> but that doesn't help me with the upgrade process in point 1 - unless I'm 
> missing something?
>
> (Yes, perhaps I could jump through hoops and make a second, writable 
> database, with appropriate routers etc, to enable creation of the 
> django_migrations table, to get past point 1 - but if django migrations are 
> useless to us anyway... disabling migrations entirely seems far more 
> logical.)
>
>
>

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


Re: Problems Sending Email From Django SIte

2014-02-01 Thread Matt Schinckel
Your ADMINS setting is incorrect.

In python, the value ((a,b)) is not a 1-tuple containing a 2-tuple, as you 
want, 
but a single 2-tuple, which django interprets as a tuple containing _just_ 
email
addresses.

Try:

ADMINS = (('Mark', 'x...@example.com'),)

Note the trailing comma after the inner tuple.

Matt.

On Saturday, February 1, 2014 3:21:32 PM UTC+10:30, mark wrote:
>
> Exim4 has two logs - main and reject.
>
> Message from python prompt and mutt - shows activity in main, but not 
> reject.
>
> Message from Server 500 error with django app - no activity in main, and a 
> message in reject - 
>
> 2014-01-31 21:30:55 unqualified recipient rejected:  H=localhost 
> [127.0.0.1]
>
> That is all I have. 
>
> My settings.py files...maybe you will see something missing or 
> mis-configured for email from a django site (I removed some sensitive 
> information).
>
> *The first file base.py:*
>
> import os
> BASE_DIR = os.path.dirname(os.path.dirname(__file__))
>
>
> # Application definition
>
> INSTALLED_APPS = (
> 'django.contrib.admin',
> 'django.contrib.auth',
> 'django.contrib.contenttypes',
> 'django.contrib.sessions',
> 'django.contrib.messages',
> 'django.contrib.staticfiles',
> 'django.contrib.humanize',
> 'south',
> 'inventory',
> )
>
> MIDDLEWARE_CLASSES = (
> 'django.contrib.sessions.middleware.SessionMiddleware',
> 'django.middleware.common.CommonMiddleware',
> 'django.middleware.csrf.CsrfViewMiddleware',
> 'django.contrib.auth.middleware.AuthenticationMiddleware',
> 'django.contrib.messages.middleware.MessageMiddleware',
> 'django.middleware.clickjacking.XFrameOptionsMiddleware',
> )
>
> DEBUG = False
>
> TEMPLATE_DEBUG = False
>
> ROOT_URLCONF = 'inventory_project.urls'
>
> LANGUAGE_CODE = 'en-us'
>
> TIME_ZONE = 'America/Phoenix'
>
> USE_I18N = True
>
> USE_L10N = True
>
> USE_TZ = True
>
> *The second file base_beagle.py:*
>
> # settings/base_beagle.py
> from base import *
>
> STATIC_ROOT = os.path.join(BASE_DIR, 'static')
> STATIC_URL = 'http://192.168.5.126:7000/static/'
>
> MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
> MEDIA_URL = 'http://192.168.5.126:7000/media/'
>
> *The third file prod_beagle.py*
>
> # settings/prod_beagle.py
> from base_beagle import *
>
> # SECURITY WARNING: keep the secret key used in production secret!
> SECRET_KEY = 'xx'
>
> # SECURITY WARNING: don't run with debug turned on in production!
> DEBUG = False
>
> TEMPLATE_DEBUG = False
>
> ALLOWED_HOSTS = ['192.168.5.126', 'localhost']
>
> EMAIL_HOST = "localhost"
> EMAIL_PORT = 25
> EMAIL_SUBJECT_PREFIX = "[Django-beagle] "
>
> DATABASES = {
> 'default': {
> 'ENGINE': 'django.db.backends.mysql',
> 'NAME': 'inventory_prod',
> 'USER': '',
> 'PASSWORD': '***',
> }
> }
>
> INTERNAL_IPS = ("127.0.0.1","192.168.5.126")
>
> ADMINS = (('mark', 'x...@xx.xxx'))
>
> LOGIN_URL = '/mom/inventory/login/'
>
> WSGI_APPLICATION = "inventory_project.wsgi.application"
>
>
> Thanks,
>
> Mark
>
>
> On Fri, Jan 31, 2014 at 8:49 PM, m1chael  >wrote:
>
>> can you tail a mail server log file, while trying to send a django
>> e-mail, and see what happens? also take a look at a log file for
>> command line and mutt do a comparison of all. maybe that will help
>>
>> On Fri, Jan 31, 2014 at 10:35 PM, Mark Phillips
>>  wrote:
>> > Thank-you for your response...However,
>> >
>> > 1. I can send email from the command line and from mutt.
>> >
>> > 2. I can send email from a python prompt using the settings.py in my 
>> app.
>> >
>> > These two facts tell me the mail server is configured properly.
>> >
>> > 3. Only my django app cannot send email.
>> >
>> > This fact leads me to believe my django app is mis-configured for 
>> sending
>> > email. In all other aspects, my app works as designed.
>> >
>> > Do you have any other helpful suggestions?
>> >
>> > Mark
>> >
>> >
>> > On Fri, Jan 31, 2014 at 7:26 PM, m1chael  
>> wrote:
>> >>
>> >> Your mail server needs configuring.
>> >>
>> >> On Fri, Jan 31, 2014 at 8:15 PM, Mark Phillips
>> >>  wrote:
>> >> > A follow up. After hitting send, I realized how to simulate an error 
>> - I
>> >> > asked for a page with a nonexistent id. Like the polls example in the
>> >> > django
>> >> > tutorial, I used an url with a poll_id that does not exist in my 
>> site. I
>> >> > got
>> >> > a Server Error (500) page, but no email. I looked in the exim4 reject
>> >> > log
>> >> > and found:
>> >> >
>> >> > 2014-01-31 18:07:04 unqualified recipient rejected:  H=localhost
>> >> > [127.0.0.1]
>> >> >
>> >> > I googled this error and have not had any luck figuring it out. 
>> Since I
>> >> > can
>> >> > send email from the command line and a python script with the same
>> >> > settings.py file as my site, could I be missing something in the 
>> 

Re: m2m symmetry confusion

2013-04-11 Thread Matt Schinckel


On Friday, April 12, 2013 9:52:10 AM UTC+9:30, Lachlan Musicman wrote:
>
> On 12 April 2013 08:43, Dennis Lee Bieber  
> wrote: 
> > On Thu, 11 Apr 2013 16:41:37 +1000, Lachlan Musicman 
> >  
>
> > declaimed the following in gmane.comp.python.django.user: 
> > 
> > An individual typically only has two parents (unless you are 
> > considering birth and adoption, which may be needed to handle some of 
> > the odd situations forming with the various "same sex marriage" models), 
> > so many-to-many isn't really appropriate. And an individual could have 
> > many children. 
> > 
> > So I'd have a pair of links for 
> > 
> > father 
> > mother 
> > 
> > and that is IT... Children and Siblings are all query results (children 
> > of X are those with the appropriate parent slot = X). 
>
>
> I like your reasoning, but I disagree on your result. First, it 
> doesn't relate partners, second, it presumes two parents (I am a step 
> father). 
>

But a partner relationship is not at all related to a parent-child 
relationship.

That is, you may have children with a person who is not your partner. And,
you may have a partner and not have children.

And, you may have more than one partner (depending upon where you are,
you may have more than one partner simultaneously).

If you will only store adoptive OR birth parents, then you can get away with
a single mother and father fields. But, even for adoptive relationships, you
probably need a start date (and possibly a finish date), so I think they 
should
be stored seperately.

Thus, you have:

Person
 - date-of-birth
 - date-of-death
 - mother (fk-> Person)
 - father (fk -> Person)
 - adoptive_parent (m2m -> Person, maybe use a through table
to get start and finish dates).

The issue you have then is that you have two fks to Parent,
which means you would have to query differently to get a father's
children to a mother's. Or you could wrap '.children()' to get the
value.

 

> So I think I'm going to go with a 
>
> parent m2m 
> partner m2m 
>
> and take your advise to trash sibling and children. 
>
> Back to the grindstone then. 
>
>
Or, you could use the parent m2m with a through table to add
the relevant data. birth/adoptive parent, etc.

And, the partner m2m could also use a through table to store
start and finish times of the relationship.

Family relationships are hard...

Matt.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




Re: Queries to multiple tables

2012-11-11 Thread Matt Schinckel
Following up: if it affects a single instance of an object, then it belongs 
as a model method.

If it affects any number of them, then it should perhaps go on the manager 
(or even the queryset: I use django-model-utils PassThroughManager for this 
a lot).

Matt.

On Sunday, November 11, 2012 3:53:26 AM UTC+10:30, Javier Guerra wrote:
>
> On Sat, Nov 10, 2012 at 6:15 AM, Tomas Ehrlich 
>  
> wrote: 
> > I usualy put methods like this one into Model, although Manager is also 
> > possible. Definitely not View or sth else. 
>
> definitely in the model. 
>
> you'd use it like this: 
>
> accnt = get_object_or_404 (Account, pk=account_id) 
> payee = get_object_or_404 (...) 
> accnt.make_payment (payee, amount) 
>
> it would be as easy as adding a method to your Account class, for example: 
>
> class Account (models.Model): 
> .. 
> .. 
>
> def make_payment(self, payee, amount, save=True): 
> if amount > self.balance: 
> throw NotEnoughFunds 
> self.balance -= amount 
> payee.balance += amount 
> if save: 
> self.save() 
> payee.save() 
>
> (of course, a serious accounting app don't modify balances but 
> registers debit/credit entries) 
>
> -- 
> Javier 
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/pU7gNc-iJe8J.
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 HTTP Basic Auth

2012-10-18 Thread Matt Schinckel
You may want to look into requests, which wraps http request-response 
handling in a nicer wrapper.

http://pypi.python.org/pypi/requests/

Matt.

On Friday, October 19, 2012 1:15:06 PM UTC+10:30, Aaron C. de Bruyn wrote:
>
> On Thu, Oct 18, 2012 at 6:55 PM, django  >wrote:
>
>> I am trying to create a Django app, one of the thing I do in that is 
>> write a connection.py which connects to  a remote server. In that 
>> connection string I need to send one of the parameter as "http_auth = 
>> http_auth.HTTPBasicAuth(user, password)". I am not sure how to do that in 
>> Django. I searched the web a lot and nothing I got which is very relevant 
>> to what I am doing. Can anyone please help me. 
>
>
> If I understand you correctly, you want to connect to a service that uses 
> HTTP Basic Auth in connection.py and do something with the data.
>
> You might look into python's urllib2 library.
>
> I found this snippet:
>
> import urllib2, base64
>
>
> request = urllib2.Request("http://api.foursquare.com/v1/user;)
>
>
> base64string = base64.encodestring('%s:%s' % (username, 
> password)).replace('\n', '')
>
>
> request.add_header("Authorization", "Basic %s" % base64string)   
>
>
> result = urllib2.urlopen(request)
>
> Here:
>
> http://stackoverflow.com/questions/635113/python-urllib2-basic-http-authentication-and-tr-im
>
>
> -A
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/Ir4PG9WJmVkJ.
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: loop user.get_profile displays none in a template

2012-10-18 Thread Matt Schinckel
user.get_profile() returns a model instance, not a dict. Model instances 
have no .items() method.

Matt.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/YAOT45p0fxEJ.
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: Missing manage.py

2012-10-04 Thread Matt Schinckel
An even better solution is to always work in a virtualenv: that way you can 
easily try out new packages, and not worry about conflicts.

Matt.

On Thursday, October 4, 2012 10:30:06 PM UTC+9:30, Ramiro Morales wrote:
>
> I think so. The usual reason for the problem you are experiencing is a 
> previous installation of Django on top of which the one you are trying 
> to use was installed without unintalling the older one first *. 
>
> So, the recommended action in such cases is to ensure you start with a 
> clean slate buy removing any and all traces of the old files causing 
> trouble. 
>
> 2012/10/4, Django_Newbie : 
> > Hi.. 
> > I am using Django 1.4.1 on Windows 7 and face similar problem. I dont 
> see 
> > manage.py 
> > 
> > All I have is: 
> > __init__.py 
> > settings.py 
> > urls.py 
> > wsgi.py 
> > 
> > 
> > Is reinstalling Django only option? 
> > 
> > 
> > On Monday, 16 April 2012 16:56:32 UTC+5:30, Faeez wrote: 
> >> 
> >> Hi, 
> >> 
> >> I have a problem whenever I create a new project using the start 
> project 
> >> command, no manage.py file is created. 
> >> 
> >> I'm using Mac OS X. Thank you in advance 
> >> 
> > 
> > -- 
> > You received this message because you are subscribed to the Google 
> Groups 
> > "Django users" group. 
> > To view this discussion on the web visit 
> > https://groups.google.com/d/msg/django-users/-/_GE2ct9_qi0J. 
> > To post to this group, send email to 
> > django...@googlegroups.com. 
>
> > To unsubscribe from this group, send email to 
> > django-users...@googlegroups.com . 
> > For more options, visit this group at 
> > http://groups.google.com/group/django-users?hl=en. 
> > 
> > 
>
> -- 
> Enviado desde mi dispositivo móvil 
>
> Ramiro Morales 
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/lXh1Hyfr9M0J.
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: Alternatives to CBVs (class based views)

2012-09-12 Thread Matt Schinckel
One really small nitpick: when returning a 405, it is a requirement that 
you return a header with the acceptable methods:
>
>
> 10.4.6 405 Method Not Allowed

> The method specified in the Request-Line is not allowed for the resource 
identified by the Request-URI. The response MUST include an Allow header 
containing a list of valid methods for the requested resource.

(From http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html).


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/8vKvmPp9uTgJ.
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: JSONField: which app to choose ?

2012-07-11 Thread Matt Schinckel
Michael,

I've been able to reproduce it: I'm not quite sure of the best way to deal 
with it.

One solution is to set either null=True, or blank=True on the field, or set 
a default.

The trick is, an empty string isn't valid JSON. I guess I've always been 
using a default (usually of {} or [], depending upon context).

Happy for you to suggest improvements, though.

I believe it's actually related 
to 
https://bitbucket.org/schinckel/django-jsonfield/issue/13/integrityerrors-when-using-empty-string

Matt.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/tymGeL-UuCgJ.
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: JSONField: which app to choose ?

2012-07-11 Thread Matt Schinckel
Hi Michael.

It should 'just work' in the admin: I'm using it fairly extensively, and 
most of our access is through the admin (or a JSON api).

If we can get a minimal failing test, then I'll make sure it gets fixed.

(And thanks, Reinout, for the referral/comment)

Matt.


On Wednesday, July 11, 2012 7:21:45 AM UTC+9:30, Michael Palumbo wrote:
>
> Can you get it work in the admin ?
> I don't understand why I get a ValidationError  "[u"'' is not a valid JSON 
> string."] as soon as I try to reach the Add admin page of my Model...
>
> import jsonfield
> class Mapping(models.Model):
> data_map4 = jsonfield.JSONField()
> -
> class MappingAdmin(admin.ModelAdmin):
> fields = ['data_map4']
> list_display = ('data_map4',)
>
> Thanks.
>
> Le mardi 10 juillet 2012 22:08:50 UTC+2, Reinout van Rees a écrit :
>>
>> On 09-07-12 20:52, Michael Palumbo wrote: 
>> > Hi, 
>> > 
>> > I have found several implementations of a Django JSON Field. 
>> > Have you ever tried one ? Which one do you recommend ? 
>>
>> I'm using the 'django-jsonfield' on pypi: 
>> http://pypi.python.org/pypi/django-jsonfield/  
>>
>> It is https://bitbucket.org/schinckel/django-jsonfield/  on bitbucket. 
>> I looked at it with a colleague and it seemed to have a bit more 
>> validation than some others. Little things. 
>>
>>
>> Reinout 
>>
>> -- 
>> Reinout van Reeshttp://reinout.vanrees.org/  
>> rein...@vanrees.org http://www.nelen-schuurmans.nl/  
>> "If you're not sure what to do, make something. -- Paul Graham" 
>>
>>
>>
>>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/4PanQBEU2swJ.
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: Where admin classes should be registered ?

2012-06-27 Thread Matt Schinckel
I generally register admin models where I define them, and then just import 
that
file in admin/__init__.py

If you are getting multiple registration errors, it may be that your app 
appears
twice in sys.path (perhaps as app, and project.app?).

That's generally a Bad Thing(tm).

Matt.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/VXzngj1e75sJ.
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 page doesn't auto-refresh

2012-06-27 Thread Matt Schinckel
I've found that this is a fairly common situation. For instance, Location 
has an FK to Company,
and then ManyToMany to StaffMember. But, only StaffMembers that have their 
FK set to
the same Company should be selectable in their inline.

This need not just be a ManyToMany thing, either. The Manager of a Location 
should also
be a StaffMember, but may only be one who is associated with the same 
Company.

This is one example: another, perhaps more common one, is Country & 
State/Province.

The available choices for a State/Province depend upon which Country is 
selected.

For the OP: the only way to do this requires JavaScript on the client end, 
and creating
views to return the limited set of objects you wish to be able to select 
from. When your
user changes Country, for instance, you then fetch the available list of 
States for that
country, and use that to populate the State field options.

I have an example (of exactly this) in my fork of django-countries: 
https://bitbucket.org/schinckel/django-countries/src

Specifically, have a look at the JS: 
https://bitbucket.org/schinckel/django-countries/src/0482ff867b4c/django_countries/static/countries/js/update_provinces_select.js

It's not especially well documented, and the JS only works for country 
field being 
called country, and province field being called province, but it might be a 
nice start for you
to see how to do it.


Matt.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/qIbITxaVnUcJ.
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: Nested Foreign Key relationships in Admin?

2012-05-21 Thread Matt Schinckel
The admin.*Inline objects will not render nested inlines.

See https://code.djangoproject.com/ticket/9025

Matt.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/jZYypQmUa3cJ.
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: DB joining 3 tables in django admin, while searching on the primary table

2012-05-19 Thread Matt Schinckel
You may be able to use prefetch_related to do what you want: it will all 
depend upon your model structure. select_related is easier, but only 
follows an fk in one direction.

Matt.

On Sunday, May 20, 2012 12:27:57 AM UTC+9:30, Aditya Sriram M wrote:
>
> Hi,
>
> again, my models are Customer, Users and Devices.
>
> I would like to search by Customer and retrieve all 'select_related' rows 
> of all the three models.
> Eg. like this..
>
> Customer1 User1 Device1
> Customer1 User1 Device2
> Customer1 User2 Device1
> Customer1 User2 Device2
> etc etc..
>
> Is this possible in Django? If so how?
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/QJ87PppeEKcJ.
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: What actually happens during syncdb?

2012-05-07 Thread Matt Schinckel
I'll preface this by saying I work with postgres, so some syntax stuff may 
be different.

To work within a different schema, you just need to tell the database to 
use that schema as part of the connection process. In postgres, this means 
issuing the command:

SET search_path TO schema;

I'm currently working through a project that allows for multiple schemata, 
and do this before re-running parts of the database table creation process, 
but this is almost certainly overkill for what you want.

https://bitbucket.org/schinckel/django-multi-schema/

Matt.

On Tuesday, May 8, 2012 12:27:01 AM UTC+9:30, Cass wrote:
>
> Hey!
>
> Django newbie here.
>
> I built out a django admin site that's up and running using a SQL Server 
> database. I now want to convert the tables that django generated for my 
> models over to a different database schema. 
>
> Here was my process and there are probably a couple missteps in here:
>
> 1) I modified models.py so that db_table = 'schema].[tablename' (hack?)
> 2) I ran syncdb after altering models.py, but syncdb complained saying 
> that the syntax was wrong during the index creation step.
> 3) I looked at the sql it was using to create indices, and it was indeed 
> wrong. My hack was causing it to try to create indices named 
> [schema].[indexname]. I changed the sql so that the indices to create would 
> just be called [indexname], and then ran this code directly on the 
> database. 
>
> At this point, I felt like everything should be okay given that the state 
> of the database and the state of models.py are theoretically synced up. 
> (however, syncdb never ran successfully because of the index problem).
>
> I restart my Apache instance, and go to the admin site expecting to see my 
> newly created blank tables reflected in the interface (i.e. no data). 
> However, I actually see all my old data! This is strange, because models.py 
> no longer references the old tables.
>
> I was wondering, am I doing something silly or does syncdb actually do 
> something behind the scenes and needs to complete successfully before my 
> changes are reflected?  
>
> After noticing that my changes were not reflected, I tried running syncdb 
> again. But this time syncdb didn't even make it past the table creation 
> step, hiccuping that the table has already been created.
>
> Thanks so much for your help!
>
> Cassandra
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/acLOdCiRniwJ.
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: Any tool to validate django templates?

2012-04-16 Thread Matt Schinckel
Generally, I just use syntax highlighting in my text editor: that usually 
helps me find errors.

TextMate has a nice HTML (Django Template) mode.

Matt.


On Monday, April 16, 2012 2:12:14 AM UTC+9:30, Marcin wrote:
>
> Hi all,
>
> I've got a template that isn't parsing, but the error is the 
> nondescript: TemplateSyntaxError: Could not parse the remainder: '"{%' from 
> '"{%'
>
> Is there a tool that can help locate the source of the error?
>
> Marcin
>
> -- 
> Marcin Tustin
> Tel: 07773 787 105
>
>  

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/IOteWda5w0UJ.
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: DB queries at import time

2012-04-12 Thread Matt Schinckel
If you install django-devserver, and enable SQL queries in the console, then
every query will be displayed as it happens, and you should be able to 
track them
down.

Matt.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/ELbykFSSiFwJ.
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: Simplest way to get all models for which admin interface exists

2012-03-14 Thread Matt Schinckel
All installed ModelAdmin models:

>>> from django.contrib.admin import site
>>> site._registry.keys()

If you only got at this from `manage.py shell`, then you may need to import 
your urls.py file first.

Getting those that are not registered is a bit longer:

>>> from django.db.models import get_models
>>> from django.conf import settings
>>> set(get_models()).difference(site._registry.keys())

Matt.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/QZ2pV8Mj240J.
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 deployment practices -- do people use setup.py?

2012-03-14 Thread Matt Schinckel
I don't use a setup.py for my _project_ deployment, but I do have a 
setup.py for each of the apps that I use within a project (or at least 
those that are 'reusable')

For project deployment, I use a fabfile that does the following:

* installs public keys onto the server (if necessary)
* creates the directory structure required (if necessary)
* copies the project onto the server
* installs requirements from REQUIREMENTS.txt
* runs collectstatic, migrate, etc
* restarts the web server (apache/nginx/whatever).


So, I can do:

$ fab deploy --host production.server



I can do each of these parts separately, if necessary, or the whole lot. I 
also have a wrapper around django-admin.py:

$ fab django:collectstatic --host server

And one around web server restart:

$ fab apache:graceful --host server


Matt.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/QLWwo6y_fV8J.
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: urllib2

2012-03-13 Thread Matt Schinckel
That response indicates you do not have permission to access that resource 
on that server. Are you sure you are hitting the correct URL?

You may want to look into requests, it is a nicer interface for interacting 
with http servers.

Matt.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/92pVcGBl21sJ.
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 can't forms access the request object?

2012-03-12 Thread Matt Schinckel
You are mixing up views and forms. The OP was asking about forms, not views.

Personally, I'm starting to hit more and more cases where I would like the 
form to be able to access the request (and associated data). For instance, 
being able to limit the queryset of choices for a related field, depending 
upon the logged in user.

(I have an API framework that uses forms for de/serialisation, called 
django-repose, but it's not fully ready for human consumption. I'm still 
thinking about the best way to handle this particular issue, for instance).

Matt.

On Monday, March 12, 2012 6:17:17 PM UTC+10:30, skhohlov wrote:
>
> Shacker,
>  Django migrates  from function based view to the class based. It will
> be nice to catch a good resource about class view usage because
> official documentation is very poor.
>
> 2012/3/12 shacker :
> > Thanks for the explanations Masklinn and dstuffte - this makes a lot more
> > sense now. I guess I was thinking of this in more simplistic terms - I 
> was
> > assuming that a form is always invoked from a view, so naturally it would
> > inherit the request object. I'm having trouble thinking of  a use case 
> where
> > a  form would  not be part of any request/response cycle, but if that 
> were
> > true, then you're right - it would not be necessarily connected to 
> request.
> >
> >
> > Also, I see that part of the problem is that a view is a *function* and 
> its
> >  args  are passed context objects, while a form is a *class* and its 
>  args
> > are only what class it inherits from - so yeah, there's a semantics 
> problem
> > of how one would pass in request.
> >
> > And you're right, it's not a hard problem to solve - just that the 
> solution
> > is a bit more verbose than I'd like it to be.
> >
> > Thanks again,
> > ./s
> >>
> >>
> > --
> > You received this message because you are subscribed to the Google Groups
> > "Django users" group.
> > To view this discussion on the web visit
> > https://groups.google.com/d/msg/django-users/-/G0UkLvyadAgJ.
> >
> > 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.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/K1w7NHduiAgJ.
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: About managing dependencies in a collaborative development team and good practices.

2012-02-22 Thread Matt Schinckel
Not sure if it was mentioned earlier in this thread (couldn't find it), but 
what some people miss is that virtualenv is not just for development. You 
can, and should, deploy to a virtualenv on your server too.

Matt.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/hwr8yDEH584J.
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: Converting a string representation of query to Django object (Q).

2012-02-22 Thread Matt Schinckel
The other option, which should work in your case:

expcodes = ['...', '...']

Result.objects.filter(analysis__experiment__experiment_code__in=expcodes)

Q objects are great, but not always needed.

Matt.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/TRw7jvOIFpEJ.
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: @commit_on_success with Class based view in Django 1.3

2012-02-15 Thread Matt Schinckel
You can use the @method_decorator decorator decorator.

https://docs.djangoproject.com/en/dev/topics/class-based-views/#decorating-class-based-views

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/s5ShG52nRpcJ.
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: Validators for fields in Proxy Model - possible without monkeypatching?

2012-01-16 Thread Matt Schinckel
You can probably use a form to do most of what you want, with the caveat 
that as long as your restrictions are more restrictive than any db 
constraints that auth.User puts in there are.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/yqvx-0MGSxsJ.
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 to examine and act on old vs. new at .save() time

2012-01-10 Thread Matt Schinckel
The way I generally do this type of thing 
is: https://gist.github.com/1591723

Lately, I've been using model validation: the clean() method instead of the 
save() method, but I can't remember if this is always called.

https://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects

The other thing you can do is have a pre_save signal listener. That might 
be useful if you have several classes that need to have the same check done.

https://docs.djangoproject.com/en/dev/ref/signals/#pre-save

Regards,

Matt.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/CRw399vSaLIJ.
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: Highlighting Active Navigation Link - correct approach?

2012-01-10 Thread Matt Schinckel
I have a reusable application I use for generating site-wide menu items. It 
does this (as well as dynamically showing/hiding menu items based on if the 
logged in user can access the view).

https://bitbucket.org/schinckel/django-menus

Actually, I think that was the one I put on pypi today, too.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/U3H0VIbAiW0J.
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: Limiting choices for ModelForm's ForeignKey/ManyToMany

2012-01-04 Thread Matt Schinckel
I've been playing around with a reusable/declarative syntax for doing this, 
as I seem to do it all of the time.

https://bitbucket.org/schinckel/django-filtered-form

You inherit from FilteredForm, and set either simple 'filters' or 
'instance_filters' attributes on the form class:

class MyModelForm(FilteredForm):
filters = {'staff': models.Q(deleted=False)}
instance_filters = {'staff': 'company.people'}

'filters' allows you to use Q objects to filter the related objects (in 
this case, only selecting non-deleted staff), and instance_filters allows 
you to set the queryset based on an attribute that the instance has. In the 
case above, it would set the queryset for staff to the MyModel's 
company.people attribute chain, and then filter those objects based on the 
deleted attribute.

Until about 5 minutes ago it was a private repo on bitbucket: I'm using it 
on a project (in production), but it needs cleaning up, documenting and 
packaging.

Matt.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/q3KkDec7XUQJ.
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 filter for serialized model.Field's

2011-12-22 Thread Matt Schinckel
I'm guessing it's got to do with testing for equality. It will be 
restricted to how the field prepares data for querying the database, and 
(speaking as the maintainer of JSONField) you need to be very careful with 
querying on json fields, as the data is stored as a string, so changes 
about how it serialises can affect query results.

You can restrict queries to `__contains` queries, and query for keys, but 
there is not really any way to have structured queries that exactly match a 
defined dict, for instance.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/0XmtRfZDBFcJ.
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: Filtering across tables

2011-12-08 Thread Matt Schinckel
Tip: have a teddy bear/rubber ducky/other toy that you can explain your 
problem too. They (probably) won't be able to solve it, but formulating it 
in a way to explain what is wrong to someone else is a great way to get 
more clarity on exactly what the problem is, and then solving it yourself.

Personally, I have an empty beer bottle I explain to, but that's because I 
always seem to have a surplus of empty beer bottles.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/ily_g0MZZ5QJ.
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: Suggestions on "Loading" for possible long load-times?

2011-11-02 Thread Matt Schinckel
Russ mentioned it in passing, but I'll point it out for clarity: Celery is 
a great framework for handling background tasks.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/TwtPwcwjzvkJ.
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 access model class for a ModelAdmin?

2011-10-18 Thread Matt Schinckel
If you are in an instance method of a ModelAdmin, you can use `self.model` 
to get the model associated with the ModelAdmin.

Have a look in django.contrib.admin's source for what methods you can 
override, or hook into.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/fHAVbMmqNqMJ.
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 - how to create a private subpage?

2011-10-11 Thread Matt Schinckel
That line (p = ...) is in a view, right?

It will probably want to be:

p = Publisher.objects.filter(status='p', pub_type='private_gallery', 
user_gallery=request.user).order_by('-id')

Matt.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/3cHEiVe8eecJ.
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.



Virtualenv and Django in Production

2011-09-20 Thread Matt Schinckel
I use virtualenv in production. It means you can install python packages using 
pip without having root or sudo access on the server.

You can also isolate installs, and use no-site-packages.

I can't think of a reason not to use it.

Matt.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/BNM2owzrojoJ.
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 achieve a construction similar to clean_?

2011-09-09 Thread Matt Schinckel
You can find it in django.forms.forms.BaseForm._clean_fields 
(django/forms/forms.py line 271, the line you'll want to look at is 286).

To solve your specific problem, you'll want to do something like:

for field in self.model._meta.fields:
if hasattr(self, "process_%s" % field.name):
getattr(self, "process_%s" % field.name)()

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/j3Zewm0agQUJ.
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: Update the parent model when a related (inline) model changed?

2011-08-25 Thread Matt Schinckel
The advantage of using post_save or overriding save() is that it is 
immediate: if you then return a representation of the parent model, it will 
be up-to-date.

If you use django-celery (or similar) it may take some time to update.

Of course, the disadvantages is that your request has to wait for the update 
of the parent model to finish before it returns a response.

Matt.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/yeQ4Xckyb1sJ.
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 Development environment

2011-08-23 Thread Matt Schinckel
OS:
- Mac OS X (Lion / Snow Leopard, depending on machine).
Editor:
- Formerly TextMate, now BBEdit
Database:
- Postgres installed locally
General (python/os) tools:
- virtualenv, pip, fabric, mercurial, git (for -e installation of dev 
versions on github)
Server tools:
- memcached, Werkzeug
Django apps that are almost always installed:
- south, compressor, django-test-utils, sentry, django-model-utils, 
johnny-cache, django-devserver, django-test-extensions

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/WM1ljqy1D24J.
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: extending the User profile - which way to go?

2011-08-21 Thread Matt Schinckel
You haven't really provided a reason why to 'do it the django way', rather 
than inheriting from User.

You do make a valid point about the separate data being in a different 
table: the difference would be that with using UserProfile, you need to 
either do the .select_related() yourself, of have a second db query when you 
do a .get_profile(). With the inheritance method, django will do the joins 
for you.

This may actually bite: there are some circumstances where a join is more 
expensive than a second query. In either case, right now is probably not the 
time to worry about it. Wait until it becomes a performance issue.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/aYGkovCMC_4J.
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: Best approach to handling different types of Users

2011-08-19 Thread Matt Schinckel

On Friday, August 19, 2011 12:07:44 PM UTC+9:30, Andre Terra (airstrike) 
wrote:
>
> Until you install some third party app that accesses
> User.objects.all() and then suddenly nothing works as it's supposed
> to.
>
> Why wouldn't it? The User subclasses will still appear in the 
User.objects.all() queryset. 

> You can access the User object from its related UserProfile instance
> and do everything you say from there instead of breaking the
> convention. Nobody's stopping you from writing an abstract
> BaseUserProfile model with an FK to User and custom UserProfile
> subclasses. I just don't see any advantages in going down that path.
>
 As I said, 'at this stage', it all seems to be working out okay. I have 
plenty of 3rd party apps, and even some of my own, that access User, and 
they still work with sub-classes.

> Because how will you access every user if you ever need to? What if
> someone gets promoted? How will you separate view from model logic?
> Are you going to rewrite forms for every user class? That's probably
> going to be hard to maintain.
>
 You can still access User.objects.all(). I even have a way to access the 
sub-classes (downcasting) when fetching all users.

> FWIW, profiles are the canonical solution. They are also the only
> elegant solution, at least until the app loading branch lands on
> trunk, which should then allow you to register a different class as
> User. But that won't happen any time soon..
>
See, I don't see them as an elegant solution. Having to do:

user.get_profile().date_of_birth 

instead of:

user.date_of_birth

irks me every time I write the code. UserProfile has always felt to me that 
it was a patchy way of extending User.

Matt.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/-B-vk5gzPqcJ.
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: Best approach to handling different types of Users

2011-08-18 Thread Matt Schinckel
Lately, I have been looking at using subclasses of auth.User as a way of 
segmenting users.

This appears (to me, at this stage, anyway) to have several advantages over 
using the UserProfile approach.

* You can have extra attributes on the subclass. For instance, one set of 
users belong to a Company, and I can do this FK relation from the subclass. 
Similarly, I can have a date_of_birth field that is attached to the user, 
rather than the UserProfile. From a performance perspective, this doesn't 
make a lick of difference, as a subclass of a concrete class still has a 
join anyway.
* You can easily have different user classes appear differently in the 
admin.
* You can have different relationships between particular User types and 
other objects. For instance, a Staff user may 'work_at' a Location, but an 
'AreaManager' may have a 'manages' relationship to an Area. You can still do 
this with auth.User, but every user will have every relationship.

The biggest helper for this was to have an authentication backend that 
automatically selects the subclass, so that you no longer get a User object 
in request.user, but whatever you want.

A drawback is that you can't easily change the field types: email, which I 
use for authentication, needs to be unique. You can handle this with 
validation checking on forms, but that requires you to remember to build 
this into your forms. The other way is to monkey-patch the User class 
directly, and manually fix the database to not allow duplicates on the email 
column.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/Y6qCTdPzU9sJ.
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: m2m assignments lost when saving in admin but not shell

2011-08-17 Thread Matt Schinckel
I had similar problems, but I put it down to doing something 'unusual'.

Try setting a pdb breakpoint in your admin class, and see if there is 
anything odd. I found that I was getting failures due to save(commit=False) 
meaning that an object had no primary key, and I had to do some fancy stuff 
to replace the save_m2m method with one that handled my relationship.

Matt.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/KNtxJaZzTtIJ.
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 store variable timedeltas in a Django model?

2011-08-14 Thread Matt Schinckel
I've also created a TimeDeltaField.

It stores internally in PG as an INTERVAL, but as a string in other dbs.

http://hg.schinckel.net/django-timedelta-field

Matt.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/JznS7wxQwakJ.
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-pdb on PyPI

2011-08-02 Thread Matt Schinckel
That's nice.

I've figured out how to enable this and django-devserver (since they both 
override 'runserver', they clash).

You can just install the middleware (dependent upon settings.DEBUG, 
naturally).

Documentation patch forthcoming.

Matt.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/JIL0oVT7YFkJ.
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: Nesting model forms with admin

2010-05-03 Thread Matt Schinckel
On May 3, 8:23 am, Spaceman Paul  wrote:
> I can't find the ticket, Matt.  If you could forward me a link, or
> just
> dig that patch up for me, I'd greatly appreciate it.

http://code.djangoproject.com/ticket/9025

I haven't looked at this much since November, so it may not be that
useful.

Matt.

-- 
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: Nesting model forms with admin

2010-05-02 Thread Matt Schinckel
I have a patch: it was a while ago, but I was about to dig it up
again.

In the meantime, there is an open ticket - I think my patch is
attached.

Matt

On Apr 20, 10:49 am, Spaceman Paul  wrote:
> I'm looking at extending the django admin app for a project, as it
> does about 96% of what we need straight out of the box.  The main
> feature not offered is what might be called nested modelforms.
>
> Stretching the example from the InlineModelAdmin documentation (which
> does almost the exact opposite of what I want), suppose we have the
> following models:
>
> class Author(models.Model):
>    name = models.CharField(max_length=100)
>
> class Book(models.Model):
>    author = models.ForeignKey(Author)
>    title = models.CharField(max_length=100)
>
> Suppose also that I don't want to reuse Authors between books.  In
> this trivial example, I would simply merge the Author field into the
> Book Model:
>
> class Book(models.Model):
>    author = models.ForeignKey(Author)
>    title = models.CharField(max_length=100)
>    author_name = models.CharField(max_length=100)
>
> But in a more complex situation, I might want to keep the Author
> fields in a separate table either simply for organisational reasons,
> or because a Book might have multiple types of Authors:
>
> class Book(models.Model):
>    original_author = models.ForeignKey(Author)
>    abridging_author = models.ForeignKey(Author)
>    translating_author = models.ForeignKey(Author)
>    title = models.CharField(max_length=100)
>
> But still, I want to be able to make all fields to appear in a single
> admin form per book, without a separate view for handling authors.  I
> picture it as working something like this:
>
> class AuthorAdmin(admin.NestedModelAdmin):
>     pass
>
> class BookAdmin(admin.ModelAdmin):
>     nested_forms = [ ('original_author', AuthorAdmin),
>                               ('abridging_author', AuthorAdmin),
>                               ('translating_author', AuthorAdmin),
>                             ]
> admin.site.register(Book, BookAdmin)
>
> My questions:
>
> 1) Is there some feature in the admin application that already does
> this that I have overlooked?
> 2) Does anybody already have a patch that does something similar?
>
> Assuming the answer to both the above is "no", I'm prepared to dive in
> and implement it myself (the admin code looks reasonably clean and
> well structured).  Assuming I do implement it myself:
>
> 3) Are there any subtle gotchas in the admin code I should be aware of
> before I start?
> 4) Any suggestions of more elegant designs would be appreciated.
> 5) Is there anybody else in Django land who would be interested in
> this sort of functionality? Would the admin maintainers have any
> technical or ideological reasons for rejecting a patch to implement
> this if I submitted one?
>
> Regards,
>
> Paul.
>
> --
> 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 
> athttp://groups.google.com/group/django-users?hl=en.

-- 
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: Django Newbie seeking for advice

2010-04-13 Thread Matt Schinckel
On Apr 13, 11:12 pm, Mister Yu  wrote:
> Hi Ian,
>
> Thanks for replying. The information is really useful.
>
> however, when i checked out the openid link you gave me, the project
> seems still on a testing stage, and on the website, it says: "A modern
> library for integrating OpenID with Django - incomplete, but really
> nearly there (promise)"
>
> are you sure that it's working and wont break after some time?

I don't think anyone can be truly sure: if it is working now, and the
OpenID specs are stable (I assume they are), then it should work for
the forseeable future. Django may (but is unlikely to) change making
it not work, but if it is written "properly", then such a change is
likely to break innumerable third-party apps.

At the very least, you will have access to the source code, and be
able to make it work again.  Which, frankly, you will need to do if
you write your own OpenID library.

Matt.

-- 
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: Is the DoesNotExist exception the only way to check if an object exists?

2010-04-10 Thread Matt Schinckel
On Apr 10, 8:30 am, Kevin Teague  wrote:
> There is nothing exceptional about exceptions in Python. McDonc does a
> good job at explaining how to think about exceptions as less than
> exceptional:
>
> http://plope.com/Members/chrism/exceptions_arent_errors/view
>
> The only arguably exceptional part is that ideally the ORM would raise
> a plain KeyError exception instead of a custom exception when a key
> look-up fails ...

It makes a difference if you are likely to find an object or not - at
least in terms of performance.

If you are expecting to find an object, (and only one), the setup of a
try: except: clause is minimal, but if you are not finding an object
more often than not, it turns out to be much slower to have the
exception raised.

Having said that, the cost of having two DB queries may overcome that
anyway: len(queryset) followed by queryset.get() is probably going to
hit the database twice. A better solution would be to do a
queryset.all(), see if the length is 1, and then get the first value
by index 0.

Matt.

-- 
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: QuerySet returned based on a Python List?

2010-03-28 Thread Matt Schinckel


rmschne wrote:
> I have a query in Django with returns a queryset.
>
>   c1=Contact.objects.filter(hostid__tablename=s)
>
> where "s" is a string holding a tablename.
>
> What I want to do is have Django return a query set where "s" is not
> just a string, but a Python list, e.g. ['01','03','54'].
>
> How do i construct a query that would do this?  I suspect it is not
> the filter function, but can't spot something else that would work.
> Thanks

c1=Contact.objects.filter(hostid__tablename__in=list_of_names)

The ORM is cool.

-- 
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: automatically import lots of modules at python manage.py shell time?

2010-03-28 Thread Matt Schinckel
On Mar 28, 3:35 am, Rolando Espinoza La Fuente 
wrote:
> On Fri, Mar 26, 2010 at 7:39 PM, Bjunix  wrote:
> > django-extensions[1] brings the shell_plus command which auto-imports
> > all models in installed apps. You can use this or have a look at it's
> > source.
>
> Yes. shell_plus is quite handy.
>
> $ bin/manage.py shell_plus
> [...]
> From 'api' autoload: RequestLog
> From 'lostiempos' autoload: Section, Subsection, Ad, HtmlArchive,
> SearchHistory, SearchHistoryCount
> From 'south' autoload: MigrationHistory
>
> Imports all your models by default. Also with iPython you can write
> "from" then press [Up]
> and will show you the entries starting with "from" in the history.
>

I wrote a similar app called django-bshell which does the same, but
uses bpython as the shell.

You can find this on pypi, and it adds a 'bshell' manage command.

Matt.

-- 
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: Any way to have a ModelForm tied to 2 Models?

2010-03-26 Thread Matt Schinckel
On Mar 26, 11:11 am, Continuation  wrote:
> I have 2 models: A, B
>
> I need a form that inserts/updates both fields of A and fields of B.
>
> Is there any way to create a ModelForm tied to A & B? Or do I need to
> use the plain old Form?

You can use a ModelForm on one, and add the extra fields to it, and
handle these in save().

I did this to get some extra behaviour in the admin, although in a
user-page I would probably use two forms.

-- 
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: Negate querysets

2010-03-23 Thread Matt Schinckel
On Mar 23, 11:23 pm, "Vinicius Mendes | meiocodigo.com"
 wrote:
> Ok. The code proposed by Tim Shaffer works and gives only one query.
> But it makes use of subselects, what is heavy for the database. Take a
> look at the generated SQL:
>
> 'SELECT `auth_user`.`id`, `auth_user`.`username`,
> `auth_user`.`first_name`, `auth_user`.`last_name`,
> `auth_user`.`email`, `auth_user`.`password`, `auth_user`.`is_staff`,
> `auth_user`.`is_active`, `auth_user`.`is_superuser`,
> `auth_user`.`last_login`, `auth_user`.`date_joined` FROM `auth_user`
> WHERE NOT (`auth_user`.`id` IN (SELECT U0.`id` FROM `auth_user` U0
> WHERE U0.`first_name` = vinicius )) LIMIT 21'
>
> I was thinking of something like:
>
> 'SELECT `auth_user`.`id`, `auth_user`.`username`,
> `auth_user`.`first_name`, `auth_user`.`last_name`,
> `auth_user`.`email`, `auth_user`.`password`, `auth_user`.`is_staff`,
> `auth_user`.`is_active`, `auth_user`.`is_superuser`,
> `auth_user`.`last_login`, `auth_user`.`date_joined` FROM `auth_user`
> WHERE NOT `auth_user`.`first_name` = vinicius  LIMIT 21'

For this example, you can just use:

>>> User.objects.exclude(first_name='vinicius')

Matt.

-- 
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: Negate querysets

2010-03-22 Thread Matt Schinckel
On Mar 23, 6:17 am, Phlip  wrote:
> > Just create another queryset that excludes everything in your first
> > queryset:
>
> > negated_queryset = User.objects.exclude(id__in=queryset.values("id"))
>
> QuerySets are already so easy to plug-n-play... Ain't there a way to
> do it without whacking the database twice?

Are you sure it hits the db twice? I seem to recall a similar case
where I thought I was, but since the queryset evaluation is lazy, the
ORM potentially has the ability to make this into a single query.

(I can't recall if when I did this sort of thing I was using
SQLAlchemy, but I _think_ it was pure django).

Matt.

-- 
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: Admin Site Performance Problem

2010-02-25 Thread Matt Schinckel
On Feb 26, 11:45 am, sixpackistan  wrote:
> Anybody have any ideas on this?
> I am running django 1.1.1 using mod_python on apache 2.2.
> We have a large database of items (defined in the model as "item")
> that are searchable by serial number (which is indexed in the
> database).  On the public site, one can enter in a serial number and
> the appropriate item is displayed for edit quite fast.  On the admin
> site, if one selects an item from the list display it takes almost a
> minute for the same item to come up for edit.  Does the django admin
> site use a different API or methodology for retrieving data?  Any
> ideas why the admin site would be so much slower when it is displaying
> the same data as the public site?

If you are displaying inlines, that also have a Foreign Key reference
to another object, that is almost certainly the reason.

Try having a look at the django-debug-toolbar, or the queries
generated in your DBMS (or try devserver) to find out where the
slowdown is.

You can use raw_id_fields in the admin to improve performance
significantly.

Matt.

-- 
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: two different models, order by date

2010-02-24 Thread Matt Schinckel
On Feb 24, 6:59 am, Nick  wrote:
> In the view set up something like
>
> all = [Books.objects.all() & Movies.objects.all()].orderby('date')
>

I thought: "super, I have been looking for this", but:

"Cannot combine queries on two different base models."

Matt.

> On Feb 23, 2:22 pm, ds  wrote:
>
>
>
> > Hello group,
>
> > i have a simple question here, i've been trying to found the answer
> > but somehow i got confused if this is wheter possible or not:
>
> > I have two django models, movies and books , i want to get all the
> > objects from both models and order them by date, getting result_set
> > that
> > might look like this:
>
> > movie1
> > movie2
> > book1
> > movie3
> > book2
>
> > is this possible?
> > if so, where should i be reading to learn how to?
>
> > thanks!
>
> > damian

-- 
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: how to set default value as current time in TimeField

2010-02-16 Thread Matt Schinckel
On Feb 16, 10:43 pm, Masklinn <maskl...@masklinn.net> wrote:
> On 16 Feb 2010, at 13:29 , Matt Schinckel wrote:
>
> > On Feb 16, 5:37 pm, Masklinn <maskl...@masklinn.net> wrote:
> >> On 16 Feb 2010, at 08:13 , harryos wrote:
>
> >>> hi
> >>> I am using a TimeField and want to set the default value as current
> >>> time.I know the field normalizes to a datetime.time object.In a
> >>> DateField ,I can put (default=datetime.date.today) and this will set
> >>> the current day .Similarly I tried (default=datetime.now().time) for
> >>> TimeField ..and can get a default time value when the page is
> >>> loaded.But after waiting for a couple of minutes,I   loaded the page
> >>> again(without restarting the server) and the timevalue shown was the
> >>> old one ,not current time.
>
> >> Argument are only evaluated once, so `default=datetime.now().time` sets 
> >> the default to the `datetime.now().time` as it is when evaluated. Once.
>
> >> Just wrap the thing in a `lambda` and you should be good to go: 
> >> `default=(lambda:datetime.now().time)`
>
> > You don't even need to do this.  Just remove the () from
> > datetime.now(), and it will do what you want it to.
>
> > If you pass in a callable as the default, this will be called each
> > time the object is created.
>
> > Matt.
>
> Except in this case he wants a `time` object, not a `datetime` one. Are you 
> sure Django handles the coercion/conversion from `datetime` to `time`?

Sorry, my mistake. For some reason I thought there was a
datetime.time.now() method.

The lambda is the best solution.

-- 
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: how to set default value as current time in TimeField

2010-02-16 Thread Matt Schinckel
On Feb 16, 6:00 pm, Masklinn  wrote:
> On 16 Feb 2010, at 08:51 , harryos wrote:
>
> > thanks ,that worked..
>
> > any idea about calculating the duration? I can do a - between two
> > datetime.datetime objects to get a timedelta.. but that doesn't work
> > with datetime.time objects
>
> Nope, seems datetime.time doesn't define __add__ and __sub__. Apparently, 
> only datetime.datetime and datetime.date support timedelta-type operations 
> (which kind-of makes sense, as timedeltas can span days).
>
> You have the option of converting to a datetime via time.strftime and 
> datetime.strptime, even though it's ugly and probably quite inefficient:
>
>     >>> t
>     datetime.time(8, 56, 20, 653330)
>     >>> datetime.strptime(t.strftime('%H:%M:%S'), '%H:%M:%S')
>     datetime.datetime(1900, 1, 1, 8, 56, 20)

Or use datetime.combine to combine both time objects with the same
date, and then add/subtract.

As Masklinn says, you hit overflow very easily with addition and
subtraction of time objects/timedeltas.  For instance, even with a
short timedelta:

datetime.time(20,0) + datetime.timedelta(hours=3)

What is the value of this expression? datetime.time cannot exceed
datetime.time(23,59,59). Does it tick over to (0,0,0) again.

Sorry, bad pun.

[I actually have a use case similar to this - where the values I store
are open/close times. Sometimes, the close time can be earlier than
the open time, if the shop is open past midnight. It gets messy
quickly].

-- 
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: how to set default value as current time in TimeField

2010-02-16 Thread Matt Schinckel
On Feb 16, 5:37 pm, Masklinn  wrote:
> On 16 Feb 2010, at 08:13 , harryos wrote:
>
>
>
> > hi
> > I am using a TimeField and want to set the default value as current
> > time.I know the field normalizes to a datetime.time object.In a
> > DateField ,I can put (default=datetime.date.today) and this will set
> > the current day .Similarly I tried (default=datetime.now().time) for
> > TimeField ..and can get a default time value when the page is
> > loaded.But after waiting for a couple of minutes,I   loaded the page
> > again(without restarting the server) and the timevalue shown was the
> > old one ,not current time.
>
> Argument are only evaluated once, so `default=datetime.now().time` sets the 
> default to the `datetime.now().time` as it is when evaluated. Once.
>
> Just wrap the thing in a `lambda` and you should be good to go: 
> `default=(lambda:datetime.now().time)`

You don't even need to do this.  Just remove the () from
datetime.now(), and it will do what you want it to.

If you pass in a callable as the default, this will be called each
time the object is created.

Matt.

-- 
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: Custom Admin Form for ManyToMany, missing Green Plus Sign?

2010-02-16 Thread Matt Schinckel


On Feb 14, 3:49 pm, john  wrote:
>
> Yes, the Items model data can be accessed through another part of the
> Admin interface, but I think the purpose of the Green Plus Sign was to
> alleviate this extra step.

Try registering the model of that type with the admin. The green plus
will only appear if the model is registered - otherwise it is unable
to find a change_form to allow for adding/editing the initial values.

-- 
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: Custom Admin Form for ManyToMany, missing Green Plus Sign?

2010-02-13 Thread Matt Schinckel
On Feb 14, 9:30 am, john  wrote:
> Hi, I just had fun creating a new Custom Admin Form to sort a
> ManyToMany field by ABC order (why isnt it in ABC order by default on
> the "def __unicode__" item?)  It works great, but now the Green Plus
> Sign to add more items to the list is missing, where did it go?  I
> guess its not enabled by default?
>
> Does anyone know where I can search on this more, and/or what this
> Green Plus Sign is called?  Is this just an extra command that needs
> to be entered or do I have to reinvent the wheel to get this back to
> working?
>
> thanks!
>
> This is the Green Plus Sign im looking for (even though this is for a
> ForeignKey field):http://docs.djangoproject.com/en/dev/_images/admin10.png
>
> My code if you want to take a look (sorry that a lot of it has to be
> redacted):
>
> # more xyz/admin.py
> from abc.xyz.models import Items,Stuff
> from django.contrib import admin
> from django import forms
>
> class StuffForm(forms.ModelForm):
>
> item=forms.ModelMultipleChoiceField(queryset=Items.objects.order_by('item'))
>
>         class Meta:
>                 model=Stuff
>
> class StuffAdmin(admin.ModelAdmin):
>         exclude=('items',)
>         form=StuffForm
>
> admin.site.register(Stuff, StuffAdmin)
>
> # more xyz/models.py
> class Items(models.Model):
>         item=models.CharField(max_length=100)
>
>         def __unicode__(self):
>                 return self.item
>
> class Stuff(models.Model):
>         items=models.ManyToManyField(Items)

I found it rather hard to follow your code, but I think the problem
might be that you haven't registered the object that is missing the
'green plus sign' with the admin.  Without it, you cannot create new
objects of that type. You can access existing objects from other
models, however, which provides the behaviour you describe.

Matt.

-- 
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: InlineModelAdmin related items on two levels

2010-02-13 Thread Matt Schinckel
Oh, and it is not flawless, there were still some issues I didn't get
sorted out. I had some validation errors of some sort, I think, when
updating data under certain circumstances, but I never quite
completely tracked it down.

-- 
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: InlineModelAdmin related items on two levels

2010-02-13 Thread Matt Schinckel
On Feb 14, 6:19 am, Ogi Vranesic  wrote:
> Hi all
>
> I read the very good tutorial 
> onhttp://docs.djangoproject.com/en/dev/ref/contrib/admin/
> and understood that the admin interface has the ability to edit models on the
> same page as a parent model and these are called inlines. For two related
> models is this easy:
>
> class A (models.Model):
>    name =...
>
> class B(models.Model):
>    a = models.ForeignKey(A)
>    title = ...
>
> in admin.py:
>
> class B(admin.TabularInline):
>     model = B
>
> class AAdmin(admin.ModelAdmin):
>     inlines = [
>         B,
>     ]
>
> and the result ist, that in add/change of A we can also add/change its child
> models B
>
> My Problem is   that I however by B model have also child models:
> class C
>   b = models.ForeignKey(B)
>   name = ...
>
> My Question is :
> Is it possible than one can add/edit models of A on the one page together with
> child models B and C as child models of B.
>
> Any hint or idee would be very appreciated

Sounds like you want nested inlines. There is no built-in way to do
this with django. I did some work (and got a solution working), but it
required significant change to the installed django. I was planning on
trying to make it into an installable app, but didn't get far.

I do have a diff: I've just put it at http://pastie.org/823968 - this
is with a fairly old trunk though, so it may not merge back in that
well right now.

It was based on another nested-inline diff I had come across, but I
don't seem to have the link any more.

Matt.

-- 
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: Analyzing modules before application start

2010-01-21 Thread Matt Schinckel
On Jan 22, 12:00 am, Filip Gruszczyński  wrote:
> I would like to go through all registered apps before server is
> started and check if certain modules (and then process them). I guess
> this mechanism is similar to the one, which looks for models or tests
> in django application. Is there any easy way to do this and where
> should inject such code? Into manage.py?

This is the registration pattern, used by django.contrib.admin

Look through the source of django.contrib.admin, and pay attention to
the autoregister() function.

Matt.
-- 
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: Splitting tests.py

2010-01-20 Thread Matt Schinckel


On Jan 20, 9:25 pm, Olivier Guilyardi <m...@xung.org> wrote:
> On 01/20/2010 10:58 AM, Matt Schinckel wrote:
>
> > On Jan 19, 7:21 am, Olivier Guilyardi <m...@xung.org> wrote:
> >> On 01/18/2010 10:04 PM, Ramiro Morales wrote:
>
> >>> On Mon, Jan 18, 2010 at 4:40 PM, Olivier Guilyardi <m...@xung.org> wrote:
> >>>> Hi,
> >>>> I'm trying to split tests.py into individual files into a tests/ 
> >>>> subfolder, but
> >>>> that doesn't work.
>
> [...]
>
> >> No error, the tests are not run. When splitting, it says:
>
> >> Ran 0 tests in 0.000s
>
> >> Instead of the following with tests.py:
>
> >> Ran 14 tests in 1.875s
>
> [...]
>
>
>
>
>
> > Drop into ./manage.py shell, and make sure you can import app.tests:
> > errors doing this will silently fail.
>
> > (May or may not solve your problem, but it has happened to me about a
> > dozen times today: I split my tests.py into:
>
> > tests/
> >     __init__.py
> >     integration/
> >         __init__.py
> >         *.py
> >     unit/
> >         __init__.py
> >         *.py
>
> > and so on.)
>
> Please see my last mail, this issue is resolved. Indeed it was import-related
> and silently failing.

Yes, it came through as I was replying :)

> I believe this is a Django bug, although I got no comments to my last post.

It is certainly annoying: tests just don't run, and the only way to
find out why is to drop into a shell and import the offending
module...

Might put some time into finding out why exceptions are not propagated
while importing tests in django.

Matt.
-- 
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: Splitting tests.py

2010-01-20 Thread Matt Schinckel
On Jan 19, 7:21 am, Olivier Guilyardi  wrote:
> On 01/18/2010 10:04 PM, Ramiro Morales wrote:
>
>
>
>
>
> > On Mon, Jan 18, 2010 at 4:40 PM, Olivier Guilyardi  wrote:
> >> Hi,
>
> >> I'm trying to split tests.py into individual files into a tests/ 
> >> subfolder, but
> >> that doesn't work.
>
> >> I correctly import everything from within tests/__init__.py, as previously 
> >> said
> >> on this mailing list:
> >>http://groups.google.com/group/django-users/browse_frm/thread/10cfd65...
>
> >> But that doesn't work. I tested on Django 1.0.2 and SVN r12255, same thing.
>
> >> Any clue?
>
> > What do you mean with "doesn't work" ?. Do you get a traceback? No
> > error but your
> > tests aren't being run?, ...
>
> No error, the tests are not run. When splitting, it says:
>
> Ran 0 tests in 0.000s
>
> Instead of the following with tests.py:
>
> Ran 14 tests in 1.875s
>
> > Try with SVN r12254 because the test infrastructure was refactored in r12255
> > and it still has some small rough edges.
>
> I reverted back to r12254, same problem.

Drop into ./manage.py shell, and make sure you can import app.tests:
errors doing this will silently fail.

(May or may not solve your problem, but it has happened to me about a
dozen times today: I split my tests.py into:

tests/
__init__.py
integration/
__init__.py
*.py
unit/
__init__.py
*.py

and so on.)

Matt.
-- 
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: OS X 10.6 Snow Leopard Setup Tutorial

2010-01-15 Thread Matt Schinckel
On Jan 16, 8:41 am, Malcolm Box  wrote:
> On Fri, Jan 15, 2010 at 6:37 PM, Jonathan Eatherly <
>
> jonathan.eathe...@gmail.com> wrote:
> >    One of these days I would like to make a DMG that sets up
> > everything for the user. If anyone would be interested in a DMG single
> > setup executable please let me know and maybe I will make it a weekend
> > project.
>
> I'd be eternally grateful (well, at least pretty happy) with such a DMG -
> I've spent too much time fighting this particular install for my sanity.
>
> A couple of comments from when I've done this:
>
> - an easier way to get libjpeg is to install MacPorts 
> (http://www.macports.org) which gives an apt like package manager ('port')
> - my incomplete notes from doing this suggest that with MySQL on the path
> then easy_install MySQLdb will work.  The key seems to be having my.conf on
> the path
>

I use brew (http://github.com/mxcl/homebrew) instead of MacPorts.

IIRC, I had to install git first, but everything else is installed
view brew, without the requirements of sudo, which makes a nice
change.

You can even have it so that it installs python modules/ruby gems in
the same manner.

Matt.
-- 
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: Test fixtures loaded ~100 times faster by overwriting BaseDatabaseCreation.create_test_db + question

2010-01-15 Thread Matt Schinckel
On Jan 14, 11:07 pm, Russell Keith-Magee 
wrote:
> On Thu, Jan 14, 2010 at 4:43 PM, Piotr Czachur  wrote:
> > Guys,
> > I was really unhappy to see how slow fixtures are loaded before every
> > test. I'm not talking about initial_data stuff that is loaded just in
> > beginning, and then reset by rollback. Fixtures used for unit tests
> > are loaded on demand (fixtures = [f1, f2]), and this is really slow,
> > because thousands of SQL queries going to database (SELECTs, SELECTs,
> > INSERTs).
> > For my small test suite (130 tests) and small fixtures (15 items) I've
> > recorded ~16000 queries to database - I was really blown away by this
> > number. 99% of this queries was related to fixtures loading.
>
> We are well aware of the speed problems associated with fixture setup
> and teardown during testing. We're open to any practical suggestions
> on how to speed them up.
>

I came across some similar issues with an Event/Occurrence pair of
models (each Event has one or more occurrences, representing the
potentially repeating nature of the event).  Because an Event could
have many thousand Occurrences, and modifying the Event may require
modifying, or even recreating all of the Occurrences, I looked at some
ways to improve performance.

Because we have a series of homogenous object types, we can combine
all of the SQL queries into one. I wonder if something similar could
be done with fixtures: create all of the objects, but instead of
saving them one at a time, save them in one batch.  I hand coded the
query, as this was a development exercise, and wasn't for production.

This would probably require significant thought as to the best way to
do this: perhaps a create_many() method on the Manager might be a
better solution?

I think I'll have another look at this - I'm about to revisit that
code anyway.

Any other suggestions are welcome, too :)

>
> As I said, we're more than happy to look at any proposal to improve
> the speed of testing in Django, but those changes can't come at the
> cost of fundamentally changing what it means to write a test.

Agreed. I use the different fixtures in test classes to have a known
state at the beginning of each test, that varies across test cases.

Matt.
-- 
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: Only Email + Password ( without username )

2010-01-15 Thread Matt Schinckel
On Jan 14, 8:12 pm, Alexander Dutton  wrote:
> On 14/01/10 09:51, nameless wrote:> I am asking whether is a good solution to 
> having 2 fields with the
> > same value ( username and email ) because both are required.
> > Or is there another solution ?
>
> This depends on whether you don't want distinct usernames hanging
> around, or you simply want people to be able to log in using their
> e-mail address.
>
> My inclination in the latter case would be to automatically generate
> usernames as random strings, but not expose them. You can then create a
> custom authentication backend[0] which uses the email address in place
> of the username.

Hey, I like this idea.

> Usernames are good things to have around to refer to people, as e-mail
> addresses can change and usernames generally don't. If user details are
> to be exposed in some way (e.g.  by activity feeds or to other users)
> you want some sort of immutable identifier for each user.

Also, there is no reason that two users could not have the same email
address.
There is no unique=True on the email field.

Matt.
-- 
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: How to get ModelAdmin given a Model

2010-01-11 Thread Matt Schinckel
On Jan 12, 4:11 am, Tomasz Zieliński
 wrote:
> On 11 Sty, 16:23, Marco Rogers  wrote:
>
> > I'm reposting this from earlier to see if I have better luck. I need
> > to be able to get the ModelAdmin associated with a model at runtime.
> > Similar to how django.db.models.get_model allows you to retrieve a
> > model.
>
> >     admin_class = get_admin(Model)
>
> > Is this possible?
>
> > The original post has more info.
>
> >http://groups.google.com/group/django-users/browse_thread/thread/0cd0...
>
> Maybe something like this:
>
> 1. Write something like django.contrib.admin.autodiscover, to get all
> ModelAdmins
> 2. Iterate those ModelAdmins, retrieve models they are attached to and
> store this mapping in a dict.
> 3. def get_admin(model):
>         return admin_to_model[model]

You should be able to iterate through admin.site._registry, and pull
out the one you need.

from django.contrib import admin
def get_admin(model):
for k,v in admin.site._registry.iteritems():
if v is model:
return v

Written in a browser.

Matt.
-- 
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: Rails-style form value deserializer?

2009-12-19 Thread Matt Schinckel
On Dec 20, 2:22 pm, Todd Blanchard  wrote:
> I think what i actually want is a form set, but I don't find that all that 
> well done either.
>
> What I'm finding lacking is the ability to put a master/detail relationship 
> in a single form.  For instance, Author/Books.

You can achieve this with an inline formset.

> Furthermore, I don't see a nice way to work with dynamically expanding forms 
>- IOW, allow the user to keep adding books to an Author using DHTML.

This, however, is harder. I have been thinking about the best way to
do this, and with a formset, you need to make sure that the POSTed
values match up with what the form management tags say.

More recently, I have been using jQuery, and the RESTful interface I
provided for my apps, to add an object. I haven't combined this with a
formset as yet, but one way might be to have a formset with a large
number of extra forms, that are hidden until a new one is added.  This
feels a little hacky, however.

> So far my impression of forms is - ick - lame.

I think of forms as simply the method of sanitising the input from the
user. I have had to subclass the forms quite heavily, but it can
generally do what I want.

--

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: Displaying Calculated Values in Django Admin

2009-12-16 Thread Matt Schinckel
On Dec 17, 12:03 pm, Streamweaver  wrote:
> Is it possible to display calculated values for models in the admin
> interface.  I know about the list_display attribute for model.Admin
> but all I really want to do is add text to a model edit form so I can
> see calculated values.
>
> For instance I have a model called Profile with a DateField called
> birthday.  I have a method as a @property that returns calculated age
> as of today.  I'd like to display the calculated age as text in the
> model editing form in the admin interface.
>
> How would I do this.
>
> i.e. displaying the property below as text in the admin interface
>
> class Profile(models.Model):
> ...
>
>     @property
>     def age(self):
>         """Returns age in years as of today."""
>         today = date.today()
>         return self.age_bydate(today)
>
> Thanks for any input.

You can add in fields to a custom form, which can do this.

class ProfileAdmin(admin.ModelAdmin):
form = forms.ProfileAdminForm


Matt

--

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: Extranet : Complete project behind login?

2009-12-16 Thread Matt Schinckel
On Dec 17, 2:07 am, Shawn Milochik  wrote:
> You can do it easily with middleware.
>
> Here's what I wrote for this exact purpose:http://pastebin.com/f52e6ef04
>
> You will have to add it to MIDDLEWARE_CLASSES in your settings.py.

I use a similar middleware for putting the whole site behind HTTP
Basic Auth.

http://www.djangosnippets.org/snippets/1720/

Matt.

--

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: Any way to make get_or_create() to create an object without saving it to database?

2009-12-14 Thread Matt Schinckel
On Dec 15, 4:13 am, Continuation  wrote:
> When using get_or_create(), when created=True, is there any way to
> make it so that it creates an object without saving it to DB?
>
> I want to take the newly created object, do some validation tests, and
> only save it to DB if it passes all tests.

You can just create an object, using:

obj = Class(**kwargs)

This will not then be persistent, and should do what you need. Note
that validation that includes ManyToMany relations will not work.

Matt

--

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: Forms - readonly representation?

2009-12-03 Thread Matt Schinckel
On Dec 4, 8:50 am, Todd Blanchard  wrote:
> I'd gotten nearly a dozen responses to a later question so I figured the 
> threshold of awareness had passed on this one.

Don't assume that everyone who reads is in a similar timezone as you.
My machine shows your first post in this thread as 0305, and your
second post at 0529. I would have answered now, had Nick not already
provided a superior response.

--

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: Show additional user information in admin

2009-12-03 Thread Matt Schinckel
On Dec 4, 5:26 am, Kai Timmer  wrote:
> 2009/12/3 bax...@gretschpages.com :
>
> > How, exactly? I tried this, with no luck:
>
> I can't get it working too. Can someone please provide a simple
> example? That would be really great.

I have an app called person which has my UserProfile in it:

in the admin.py, I have the following:

from django.contrib import admin, auth
from reversion.admin import VersionAdmin
from django.contrib.auth.admin import UserAdmin

if auth.models.User in admin.site._registry:
admin.site.unregister(auth.models.User)

from person.models import Person

class PersonInline(admin.StackedInline):
model = Person
verbose_name_plural = u"details"
# fieldsets = ((None, {'fields': (('first_name', 'last_name'),
'email')}),)

from admin_helpers.helpers import admin_link

class UserAdmin(UserAdmin, VersionAdmin):
inlines = (PersonInline,)
filter_horizontal = ('groups',)
list_filter = ('groups',)

fieldsets = (
(None, {'fields': ('username', 'password',
('is_active', 'is_staff', 'is_superuser'))}),
('Groups', {'fields': ('groups',)}),
)

admin.site.register(auth.models.User, UserAdmin)

--

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: Forms ModelMultipleChoiceField with checkboxes?

2009-11-23 Thread Matt Schinckel
On Nov 20, 7:52 pm, leoz01  wrote:
> I think the easiest way is to make your own widget or otherwise you
> can make your own form field.
>
> On 19 nov, 10:19, Benjamin Wolf  wrote:
>
>
>
> > Hello,
>
> > I'm using Django's form and ModelMultipleChoiceField.
> > ModelMultipleChoiceField produces a select list with multiple options.
> > Is it possible to use
> > checkboxes instead?
>
> > Thanks,
> > Greets Ben

I seem to remember coming across a MultiCheckboxWidget somewhere.

In fact, it is called CheckboxSelectMultiple, and there is a post in
this forum about it:

http://groups.google.com/group/django-users/browse_thread/thread/97d0c9bf70757e2e/d723ff480aef0cc2?lnk=raot

And a post on Stack Overflow:

http://stackoverflow.com/questions/1268209/django-modelform-checkbox-widget

Matt.

--

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




Re: Django on Dreamhost internal server error

2009-11-16 Thread Matt Schinckel
On Nov 17, 6:57 am, Christophe Pettus  wrote:
> On Nov 16, 2009, at 12:55 PM, Alessandro Ronchi wrote:
>
> > I'm using mod_passenger.
>
> Isn't that for Ruby rather than Python?

You can use mod_passenger for python, with a passenger_wsgi.py file.

(I use it on my development machine with Passenger.prefpane so I don't
need to fuddle with vhosts).

--

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




Re: QuerySet Question

2009-11-13 Thread Matt Schinckel
On Nov 14, 1:01 am, Chris  wrote:
> Thanks for your reply.
>
> From reading around it sounds as though I am probably not meant to
> solve this in the template (though this does seem like the easier
> option).
>
> I have figured out that I could solve this through an SQL statement as
> follows:
>
> select *, (select Count(*) FROM shop_track_owners where
> track_id=shop_track.id and user_id=<< here>>>)"owned" from shop_track;
>
> I have run this and it works. There are two problems though:
>
> 1: How do I do this through django querysets? I would like to keep the
> database abstracted.

You can execute arbitrary SQL like this using the extra method on a
queryset.  Something like:

qs.extra(select={'count':'SELECT count(*) FROM shop_track_owners where
track_id=shop_track.id and user_id=%i' % user.id)

>
> 2: This will probably be rather awkward to do when talking about
> artists or albums... Could I somehow modify the .track_set function of
> the album model to not just return tracks (select * from shop_track)
> but to run my other funky query?
>
> Also I have had another thought: I could add an "owned" field to the
> Track model. This could remain null for all tracks in the database
> forever, but could be used in the view when grabbing the tracks to
> pass the template whether or not each track is owned by the current
> user. For example:
>
> tracks = Track.objects.all()
> for track in tracks:
>     if request.user in track.owners:
>         track.owned = True
>
> Then render to response. Again, a couple of potential problems:
>
> 1: Does altering the track object (track.owned = True) also alter the
> object within tracks? I don't know if it a reference or a copy. If it
> is a copy, is there any way of shoving it back in the queryset?
>
> 2: There is still the problem of what to do when talking about albums.
> Could you do something like:
>
> for album in albums:
>     for track in album.track_set():
>        if request.user in track.owners:
>            track.owned = True
>
> Again, would setting track.owned = True affect the track within the
> album's track_set()? I would assume not... I think album.track_set()
> executes a new database query to get the set, right? Is there any way
> around this?
>
> One last possibility that I can think of: is there any way of allowing
> the track model to get at the request object? This would allow me to
> write a method in the track model (owned) that checks if the track is
> owned by the user in the request and then returns a bool.
>

You can't always assume there is a request object: for instance any
interaction with the system through ./manage.py shell doesn't have a
request object.  Also, consider that there may be many request objects
in the system at one time, if many users are using the system
simultaneously.

This is something that belongs in the view, and probably no lower, as
that is the last place where there is _always_ a request object.

Having said that, you could do something like this in the model:

def owned(self, request):
"See if the user of this request owns this object"
return request.user in self.track_owners

This then means you can call that method from anywhere, and pass in
the current request object.
> Thanks again.
>
> On Nov 12, 8:12 pm, Tomasz Zieliñski
>
>
>
>  wrote:
> > On 12 Lis, 16:12, Chris  wrote:
>
> > > Is there a way of getting a model function to access user details so
> > > that I can do a simple "if track.owned" in the template? Is there a
> > > better solution to doing it in the view? Is there something I have not
> > > thought of? What would be the "best practice" solution to this?
>
> > Just some quick ideas (after 10h of work, so watch out ;)):
>
> > 1. You can write custom tag {%ifowned track request.user%}
>
> > 2. You can try something less elegant:
>
> > {%for user in track.m2m_users.all%}
> > {%ifequal user request.user%}
> > 
> > {%endifequal%}
> > {%endfor%}
>
> > - but it's only good for small apps, as a temp solution.
>
> > --
> > Tomasz Zieliñskihttp://pyconsultant.eu

--

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




Re: Django Admin interface crashes with.

2009-11-12 Thread Matt Schinckel
On Nov 13, 1:40 pm, Rick Caudill  wrote:
> I do have non-ascii data in my database.  That is allowed, right???

Yeah, in general. What appears to be happening here (and Karen is
right, we need more to go on), but data that is being loaded into a
DecimalField contains non-ascii data.

Matt.

--

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




Re: Django Admin interface crashes with.

2009-11-12 Thread Matt Schinckel
On Nov 13, 7:06 am, Rick Caudill  wrote:
> Hi Everyone,
>
> This is my first time posting but I have been using Django for about a
> year now and love it.  I am having one problem that I can't solve
> though and it is taking too long so I thought I would ask and see if
> someone can help me.  So I have a Admin interface that is crashing.
> The error that I am getting is:
>
> DjangoUnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in
> position 5: ordinal not in range(128). You passed in
>  ( 'django.forms.forms.BoundField'>)
>
> Can anyone help with this

It looks like you have a non-ascii character in your source file, or
some data that is in your database.

Matt.

--

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




Re: admin.site.register() - help

2009-11-11 Thread Matt Schinckel
On Nov 12, 4:18 pm, neridaj  wrote:
> since FlatPage is already registered how do I properly register an
> InlineModelAdmin object?
>

You can use:

admin.site.unregister(FlatPage)

and then re-register with your FlatPageAdmin class:

admin.site.register(FlatPage, MyFlatPageAdmin)

--

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




Re: django test client doesn't handle non-multipart data in PUT

2009-11-08 Thread Matt Schinckel

On Nov 9, 11:45 am, Russell Keith-Magee <freakboy3...@gmail.com>
wrote:
> On Mon, Nov 9, 2009 at 9:40 AM, Matt Schinckel <matt.schinc...@gmail.com> 
> wrote:
>
> > I am developing a django site that has a RESTful API, and allows for
> > json representations of the resources.
>
> > I have hit a bit of a hitch with respect to the data that I need to
> > PUT, to do with the inbuilt test client.
>
> > If I use client.post(url, data, content_type='application/json',
> > **AUTH), then it works fine: I can create an object no worries.  If I
> > use client.put(url, data, content_type='application/json', **AUTH),
> > then it fails, when it tries to encode the multipart data, which it
> > shouldn't be doing.
>
> > Anyone else come across this?
>
> Yes :-)
>
> http://code.djangoproject.com/ticket/11371
>
> This bug was fixed in trunk about 2 weeks ago. It's available in the
> latest SVN revisions of trunk and the 1.1.X branch. When the stable
> 1.2 and 1.1.2 versions are released, they will include the fix.
>

Super. I was tracking trunk, with some local modifications.  Pulled
and merged the current revision.  All good now.
--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



django test client doesn't handle non-multipart data in PUT

2009-11-08 Thread Matt Schinckel

I am developing a django site that has a RESTful API, and allows for
json representations of the resources.

I have hit a bit of a hitch with respect to the data that I need to
PUT, to do with the inbuilt test client.

If I use client.post(url, data, content_type='application/json',
**AUTH), then it works fine: I can create an object no worries.  If I
use client.put(url, data, content_type='application/json', **AUTH),
then it fails, when it tries to encode the multipart data, which it
shouldn't be doing.

Anyone else come across this?
--~--~-~--~~~---~--~~
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: Problems width add_to_class

2009-11-05 Thread Matt Schinckel

On Nov 6, 7:34 am, Sandra Django  wrote:
> Hi friends, I have a problem. I'm trying to add to User class of Django an
> attribute. For that I'm using add_to_class method. I did the following:
>
>    1. Delete from Data Base the tables: «auth_user», «auth_user_groups» y
>    «auth_user_user_permissions».
>    2. In models.py of «main» aplication I put the following:
>
>    from django.contrib.auth.models import User
>    User.add_to_class('new_attribute', models.CharField(max_length = 150))
>
>    3. I did syncdb and the tables that I had deleted before were created
>    again
>    4. When I go to Data Base, appears in the table «auth_user» the
>    «new_attribute» field, however, not in users form of Django
>

You will probably want to either subclass the UserForm, or the admin
template.

The User form is different to generic model forms.  I would suggest
you look at the django.contrib.admin files that deal with this
particular form.

Matt.
--~--~-~--~~~---~--~~
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: Inlines and foreign key

2009-10-29 Thread Matt Schinckel

On Oct 30, 3:53 am, Alessandro Ronchi 
wrote:
> I've made a Profile model (Socio) for my users and now I need to be able to
> edit the users detail in profile model in admin.
>
> THe problem is that I can add an Inline only from User to Profile, because
> User doesn't have a foreign key to profile.

I had a similar problem. I have a Person class, which is effectively a
Profile (but may exist without an attached User). It is trivial to
have the Person fields appear in the User admin page, but not the
other way around.

My solution was to have a custom PersonAdminForm, which allows for
setting of the username and password (and validates these, creating a
new user if one was not previously attached).  This form is then
attached to the PersonAdmin class.

Hope the snippets below help.

person/admin.py

class PersonAdmin(VersionAdmin):
model = Person
form = PersonAdminForm

person/forms.py

class PersonAdminForm(forms.ModelForm):
user_active = forms.BooleanField(required=False, label='Can log
in',
help_text="Allow this person to log in to the web interface.")
username = forms.CharField(required=False)
password1 = forms.CharField(required=False,
label='Password',
widget=forms.PasswordInput)
password2 = forms.CharField(required=False,
label='Password (repeat)',
widget=forms.PasswordInput)

groups = forms.ModelMultipleChoiceField(required=False,
queryset=auth.models.Group.objects)

def __init__(self, *args, **kwargs):
forms.ModelForm.__init__(self, *args, **kwargs)
person = kwargs.get('instance', None)
if person:
user = person.user
if user:
self.fields['groups'].queryset = person.company.groups
self.fields['groups'].initial = map(lambda x:x.pk,
user.groups.all())
self.fields['user_active'].initial = user.is_active
self.fields['username'].initial = user.username
self.fields['password2'].help_text = 'Enter the same
password into both boxes to change it.'
self.fields['user_active'].help_text = 'Allow %s to
log in to the web interface.' % user.name
self.fields['active'].help_text = 'Allow %s to be
rostered on for shifts.' % user.name

else:
self.fields['groups'].widget = forms.HiddenInput()
self.fields['groups'].help_text = 'People must be able
to log in to assign them to groups.'
self.fields['company'].widget = forms.HiddenInput()
self.fields['company'].help_text = 'People cannot be moved
between companies.'
else:
self.fields['groups'].widget = forms.HiddenInput()
self.fields['groups'].help_text = "Choose groups after
creating the person."
# TODO: use Ajax to load the group list after the company
has been chosen.

class Meta:
model = Person

def clean_username(self):
"""
See if there is already a user with this username.  If this
username
is already associated with the user that is attached to this
person,
then that is okay.
"""
username = self.cleaned_data['username']
if username == "" and (self.cleaned_data['user_active'] or
self.instance.user):
raise forms.ValidationError(_("A username must be supplied
to enable login."))
users = auth.models.User.objects.filter(username=username)
if self.instance.user:
users = users.exclude(pk=self.instance.user.pk)
if users.count() != 0:
raise forms.ValidationError(_("A user with that username
already exists."))

return username

def clean_password2(self):
password1 = self.cleaned_data.get("password1", "")
password2 = self.cleaned_data["password2"]
if password1 != password2:
raise forms.ValidationError(_("The two password fields
didn't match."))
return password2

def clean_groups(self):
co_groups = self.cleaned_data['company'].groups.all()
return [group for group in self.cleaned_data['groups'] \
if group in co_groups]

def save(self, commit=True):
"""
If there isn't a user linked to this person, and there is a
username,
then we need to create a user.  Otherwise, we need to alter
the
values in the existing user object.

"""
forms.ModelForm.save(self, commit=False)

if self.cleaned_data['username'] != "":
if self.instance.user:
user = self.instance.user
# Set groups: easiest method-clear then re-add.
user.groups.clear()
user.groups.add(*self.cleaned_data['groups'])
else:
user = auth.models.User()


user.username = self.cleaned_data['username']
if self.cleaned_data['password2'] 

Re: View count ignore auto_now

2009-10-26 Thread Matt Schinckel

On Oct 27, 8:56 am, TheIvIaxx  wrote:
> Hello, I have a simple page model that has created and modified fields
> with auto_add and auto_now set to True.  I'd like to keep track of the
> number of views per page so i added a views field to the model.
> However if i increment the views and save, then the modified gets
> changed.  This trivializes the modified field as it will be updated
> every time someone views the page.  Is there a way to update a single
> field only with the ORM or will i have to do a SQL query?

You /may/ be able to do it with a OneToOne relation instead of a
field.

(Just an idea, I haven't tested it).

Matt.
--~--~-~--~~~---~--~~
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: Definitive solution for foreignkey filtering in Admin

2009-10-25 Thread Matt Schinckel

On Oct 24, 5:14 am, Tim Valenta  wrote:
> I've been searching for a while on how to intercept querysets in
> forms, to apply a custom filter to the choices on both foreignkey and
> m2m widgets.  I'm surprised at how there are so many similar questions
> out there, dating back to 2006.

[snip]

> The only solution I've seen has dealt with filtering by User foreign
> key (being that User is available in the request object in views), and
> that's primarily for non-Admin views.

[snip]

> I've been looking at the code for the above noted API method,
> formfield_for_foreignkey, and I really can't see a way to get
> references to an instance of the object being edited.  I would need
> such a reference to successfully override that method and filter my
> queryset on this relationship.

I too spent some time looking at formfield_for_foreignkey, and had no
luck.

You can subclass ModelAdmin, and then limit the objects in the field's
queryset.

** admin.py **

class LocationAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
forms.ModelForm.__init__(self, *args, **kwargs)
location = kwargs.get('instance', None)
if location:
self.fields['contract'].queryset = Contract.objects.filter
(company=location.company)

class LocationAdmin(admin.ModelAdmin):
model = Location
form = LocationAdminForm


I also had to do something similar with Inlines, when I did the same
type of thing.  This is not my exact code, but it is very close, and
suited toward your use case.

Matt.
--~--~-~--~~~---~--~~
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: Check Constrains in Django

2009-10-13 Thread Matt Schinckel

On Oct 14, 9:57 am, Christophe Pettus  wrote:
> On Oct 13, 2009, at 4:46 PM, Geobase Isoscale wrote:
>
> > Do your mean that its not possible for Django to recognize  
> > postgreSQL defined Check constraints when data is entered in the Form?
>
> That's correct.  CHECK constraints on the PostgreSQL database are not  
> automatically enforced at the form level in Django.  You'll need to  
> check and enforce those separately in your Django code.

The database will always prevent data that breaks constraints being
committed, however.  My patch changes the validation process so that
it will test those constraints automatically, and alert you in the
manner expected (raising ValidationError, and in the admin, putting
those lovely red boxes around the field).

I also hook into the creation process, and create the constraints in
the table/column definition.  Otherwise, you would need to add in the
constraints afterwards.  This isn't that relevant if you are not using
the syncdb command, for instance.

As for how to patch your installation: I use a mercurial mirror of
django, which I patch against.  There is no reason you could not just
patch the installed version, by manually looking at the diffs in the
patch, and applying those to the relevant files.

I was going to extend the patch, but my use of check constraints at
this stage is limited to strictly simple cases (start < finish, for
instance).  You may be able to extend it, and I am happy to help test
them, but I haven't really looked at geodjango, so I don't know much
about it.

Matt.
--~--~-~--~~~---~--~~
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: Check Constrains in Django

2009-10-13 Thread Matt Schinckel

On Oct 14, 12:55 am, Geobase Isoscale  wrote:
> Hi All,
>
> I'm working with PostgreSQL database.
> I wonder how Django handles Check Constraints both (range and value based).
> To ensure integrity of data in the database as postresql does.
>
> How are they implemented in models and views.
>

Django does not have the ability to add in check constraints into the
postgresql database for you from your models, nor does it have the
ability to easily mark columns or tables as having said constraints.

I did raise a ticket about this, and create a patch (which I am
using), but it is specific to postgresql, and limited to simple
constraints.

The usual way is to have the constraints applied in the forms, using
the clean_column() and clean() methods.  I prefer having them at both
the database and model level, however.

You can see the thread in django-developers (http://
groups.google.com.au/group/django-developers/browse_thread/thread/
38937992972c7808/ef9783182671b348?lnk=gst=check
+constraint#ef9783182671b348), and the ticket (http://
code.djangoproject.com/ticket/11964).

Matt.
--~--~-~--~~~---~--~~
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: ORM

2009-10-08 Thread Matt Schinckel

On Oct 8, 6:18 pm, Marek Pietrucha  wrote:
> I see that all of you guy's know what your talking about. I was
> thinking way won't you share some knowledge to this 
> topic:http://groups.google.com/group/django-users/browse_thread/thread/1517...
>

What does this have to do with this thread?  You have asked the
question, asking it again isn't likely to (at least this soon) result
in more response.

Matt.
--~--~-~--~~~---~--~~
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: combining user and userprofile in admin

2009-10-01 Thread Matt Schinckel



On Oct 2, 8:58 am, Matt Schinckel <matt.schinc...@gmail.com> wrote:
> On Oct 2, 3:20 am, booty <boot...@gmail.com> wrote:> I am creating an 
> application where I want the admin site to display
>
> > But I am not able to sort by these values (nor filter, nor search).
>


I seem to have missed this line.

You can use things in the search_fields attribute that look like
'user__username' to get access to related objects fields.

This doesn't seem to work for list_filter, though.

Matt.
--~--~-~--~~~---~--~~
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: combining user and userprofile in admin

2009-10-01 Thread Matt Schinckel


On Oct 2, 3:20 am, booty  wrote:
> I am creating an application where I want the admin site to display
> the User and the UserProfile (my extensions to the User class)
> together in the list view.
>
[snip]

> My problem is that I want my User Profile fields to be displayed in
> the User list page (http://.../admin/auth/user/) and be able to filter
> and sort by these (User Profile) fields. But admin does not seem to
> get access to the get_profile method:
>
> list_display = ('first_name',
>                     'last_name',
>                      #get_profile, #adding this does not give access
>                    )
>
> I can of course write a function in MyUserAdmin to give access to
> individual UserProfile properties, and they will be diplayed
> correctly. e.g.
>
> class MyUserAdmin(UserAdmin):
>     inlines = [
>         UserProfileInline,
>     ]
>
>     def home_page(self):
>          return self.get_profile().home_page
>
>     list_display = ('first_name',
>                     'last_name',
>                     home_page
>                    )
>
> But I am not able to sort by these values (nor filter, nor search).
>
> Is there anyway to have the admin site have access to the UserProfile
> model as if it was part of the User model?

Methods and properties that you have in either the AdminModel, or the
Model itself, that take no arguments, can be used in the
list_display.  Which appears to be what you have done.

Is there anything else you are trying to achieve other than this?

Matt.
--~--~-~--~~~---~--~~
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: Does the auto_now attribute do updates even if the same data is inserted?

2009-09-28 Thread Matt Schinckel

On Sep 28, 11:27 pm, Iqbal Abdullah  wrote:
> Hi guys,
>
> I have a quick question:
>
> I have set auto_now=True for one of my DateTimeFields.
>
> Lets say I have a model object like so:
>
> >> a = MyModel.objects.get(id="10")
> >> print a.id
> >> "10"
> >> a.id = "10"
> >> a.save()
>
> will this cause my DateTimeField to change it's timestamp?

I would suspect yes, but surely it is trivial to test, and find out?

Matt.

--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---