Re: If you have multiple custom users - what should you set AUTH_USER_MODEL to?

2017-06-19 Thread 'Victor Hooi' via Django users
If you go down the user-profiles route - how would you handle managing each
of those via the Django Admin?

For example - say you have 3 user "types" - each just being User, with a
different profile linked to it. How would you manage each of those via the
admin interface?

On Mon, 19 Jun 2017 at 17:53 James Schneider <jrschneide...@gmail.com>
wrote:

>
>
> On Jun 18, 2017 10:11 PM, "Victor Hooi" <victorh...@gmail.com> wrote:
>
> Hi,
>
> Say you have multiple custom users, each inheriting from AbstractUser. The
> docs mention setting AUTH_USER_MODEL:
>
>
> https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#substituting-a-custom-user-model
>
> However, what happens if you have *multiple* custom users - which would
> you set it to?
>
>
> The answer is to rethink your user model(s). The idea being that a 'user'
> should be thought about at a very high level.
>
> There should only be one canon user model in use as far as system
> authentication is concerned. The 'type' of user rarely warrants the use of
> a separate model, rather the type would typically be made available as an
> attribute of your system User (notice the capital U), restricted by either
> a static list of possible choices (
> https://docs.djangoproject.com/en/1.11/ref/models/fields/#choices) or by
> utilizing a foreign key to another model containing the list of potential
> user types.
>
> Your User model (which can be named anything you like, I'm just
> referencing User for brevity) should contain only a minimal amount of
> information needed for authentication, and any information that would be
> needed regularly on every request.
>
> Ideally, the User 'type' would be made a part of the User Profile, which
> can be recalled quickly via a 1to1 FK relationship (
> https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#extending-the-existing-user-model
> ).
>
> One of the few cases where this information could be stored directly on
> the User is when the authorization system (permissions and user tests for
> access) are contingent on the 'type' of user you are examining, which
> effectively turns it into a role. However, unless you have a static
> (unchanging) list of user roles (which is a more apropos description
> anyway), you may still consider using a M2M relationship to a role table
> and update the User manager to automatically join the two tables when users
> are queried.
>
> Having separate 'user' models as you've mentioned leads to the exact issue
> you've brought up. If you are trying to find a user, you need a separate
> query for every type of user you have in every location where you need a
> list of users or perform searching for specific users. This causes an
> artificial and unnecessary inflation of the number of queries run for each
> request, and complicates the code trying to parse multiple sets of results.
>
> Proxy models may also be an alternative (
> https://docs.djangoproject.com/en/1.11/topics/db/models/#proxy-models).
> However, those can be a bit unwieldy to handle and present the same issues
> as pulling a user list.
>
> -James
>
>
>
>
> --
> You received this message because you are subscribed to a topic in the
> Google Groups "Django users" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/django-users/UrUN9PWKwMs/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to
> django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/CA%2Be%2BciWkc8XrQEnS9ET12Y%3D5nToFV29QTqHwOrcPMX_rvEM17g%40mail.gmail.com
> <https://groups.google.com/d/msgid/django-users/CA%2Be%2BciWkc8XrQEnS9ET12Y%3D5nToFV29QTqHwOrcPMX_rvEM17g%40mail.gmail.com?utm_medium=email_source=footer>
> .
> For more options, visit https://groups.google.com/d/optout.
>

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


If you have multiple custom users - what should you set AUTH_USER_MODEL to?

2017-06-18 Thread Victor Hooi
Hi,

Say you have multiple custom users, each inheriting from AbstractUser. The 
docs mention setting AUTH_USER_MODEL:

https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#substituting-a-custom-user-model

However, what happens if you have *multiple* custom users - which would you 
set it to?

Regards,
Victor

-- 
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/fddfc562-1d61-4592-a6ee-b7bc2b6a7909%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Canonical way of handling multiple types of users? (Profiles vs subclassing django.contrib.auth.models.AbstractUser)

2017-06-18 Thread Victor Hooi
Aha, thanks for the good points.

I could go down the route of using auth.groups.

I'd still need a user profile to store the additional fields - are you
thinking I should only have a single Profile class, and make all the fields
nullable?

The issue though is still - how do I integrate this with Google Admin well?
Ideally we'd want different sections to edit teachers, vs students vs
parents - but not sure if this is possible.

On Wed, 14 Jun 2017 at 21:45 Mike Dewhirst <mi...@dewhirst.com.au> wrote:

> On 14/06/2017 8:59 PM, Victor Hooi wrote:
> > Resurrecting a slightly old thread =), but coming back to this project.
> >
> > Say I have multiple models that each have their own user profile.
> >
> > Let's assume that each type of user is mutually exclusive (i.e. a
> > student cannot be a teacher etc.)
>
> IMO that's a problematic assumption. It is usually best to model real
> life and if you take simplifying shortcuts (i.e. a student cannot be a
> teacher etc.) which don't work out in practice for any reason you end up
> with a project which has to turn itself inside out to keep working.
>
> For me, the "canonical way" would be to use roles. By that I mean
> auth.groups.
>
> I have been bitten before and learned long ago that assumptions related
> to people and what they do/are can be plain wrong.
>
> I would be assuming that a student could also be a teacher. And vice
> versa. And simultaneously! And there's nothing outrageous in that.
> Students often become teachers and as tutors can fill both roles at once.
>
> auth.groups let's you do all sorts of things including role reversals
> and dual roles. You might need object permissions as well if you have
> information silos so that being in a teacher role for one should not
> give unfettered access to a different silo accessed as a student.
>
> In any case, such an approach is usually simpler than software which
> deviates from reality.
>
> That'll be 2c
>
> Mike
>
> >
> > class Student(models.Model):
> > user = models.OneToOneField(User, on_delete=models.CASCADE)
> >
> > class Teacher(models.Model):
> > user = models.OneToOneField(User, on_delete=models.CASCADE)
> >
> > class Parent(models.Model):
> > user = models.OneToOneField(User, on_delete=models.CASCADE)
> >
> >
> > How do you use the Django Admin to manage multiple types of users?
> >
> > The docs mention adding an inline to UserAdmin - however, this seems
> > to assume you only have one model with a user profile - what if you
> > have multiple?
> >
> > Regards,
> > Victor
> >
> > On Monday, 14 November 2016 04:57:53 UTC+11, me.vineetkothari wrote:
> >
> > Use one to many field or many to many field
> >
> > On Wed, Nov 9, 2016 at 3:06 PM, Melvyn Sopacua <m.r.s...@gmail.com
> > > wrote:
> >
> > Hi,
> >
> > > What is the current canonical way to handle multiple
> > user-profiles in
> > > Django?
> >
> > it highly depends on how you see these objects:
> >
> >     1. different types of users (requirement: a user can only be
> > one type)
> > 2. one type of user with additional information from different
> > sources
> > 3. different types of users, but users can be multiple types
> >
> > Obviously the third is the hardest.
> >
> >
> > On Tuesday 08 November 2016 16:54:43 Victor Hooi wrote:
> >
> > > For example - say you have "Teachers", "Students", "Parents"
> > - you may
> > > have slightly different fields for each one and/or different
> > > behaviour. Students will have things like grades, Parents
> > may have
> > > 1-to-many Students etc.
> >
> > Here you clearly think of them as types, instead of Humans and
> > yet they
> > can fulfill multiple roles. It also doesn't matter what is in the
> > profile, as long as you don't care about enforcing required
> > information
> > at the model layer.
> > You can make one profile model with the union of all fields
> > and use
> > group membership to enforce requirements. So a Human which is
> > member of
> > the Teachers group must have "date_employed" filled in while
> > Student
> > must have "date_enrolled". Similarly, you can use group
> > membership to
>

Re: Canonical way of handling multiple types of users? (Profiles vs subclassing django.contrib.auth.models.AbstractUser)

2017-06-14 Thread Victor Hooi
Resurrecting a slightly old thread =), but coming back to this project.

Say I have multiple models that each have their own user profile. 

Let's assume that each type of user is mutually exclusive (i.e. a student 
cannot be a teacher etc.)

>
> class Student(models.Model):
> user = models.OneToOneField(User, on_delete=models.CASCADE)

 

class Teacher(models.Model):
> user = models.OneToOneField(User, on_delete=models.CASCADE) 

 

class Parent(models.Model):
> user = models.OneToOneField(User, on_delete=models.CASCADE)


How do you use the Django Admin to manage multiple types of users?

The docs mention adding an inline to UserAdmin - however, this seems to 
assume you only have one model with a user profile - what if you have 
multiple?

Regards,
Victor

On Monday, 14 November 2016 04:57:53 UTC+11, me.vineetkothari wrote:
>
> Use one to many field or many to many field
>
> On Wed, Nov 9, 2016 at 3:06 PM, Melvyn Sopacua <m.r.s...@gmail.com 
> > wrote:
>
>> Hi,
>>
>> > What is the current canonical way to handle multiple user-profiles in
>> > Django?
>>
>> it highly depends on how you see these objects:
>>
>> 1. different types of users (requirement: a user can only be one type)
>> 2. one type of user with additional information from different sources
>> 3. different types of users, but users can be multiple types
>>
>> Obviously the third is the hardest.
>>
>>
>> On Tuesday 08 November 2016 16:54:43 Victor Hooi wrote:
>>
>> > For example - say you have "Teachers", "Students", "Parents" - you may
>> > have slightly different fields for each one and/or different
>> > behaviour. Students will have things like grades, Parents may have
>> > 1-to-many Students etc.
>>
>> Here you clearly think of them as types, instead of Humans and yet they
>> can fulfill multiple roles. It also doesn't matter what is in the
>> profile, as long as you don't care about enforcing required information
>> at the model layer.
>> You can make one profile model with the union of all fields and use
>> group membership to enforce requirements. So a Human which is member of
>> the Teachers group must have "date_employed" filled in while Student
>> must have "date_enrolled". Similarly, you can use group membership to
>> determine what information to show.
>> Splitting them out in different profiles is a matter of preference and
>> optimization, not of design.
>>
>> > The docs mention using a django.db.models.signals.post_save
>> > <https://docs.djangoproject.com/en/1.10/ref/signals/#django.db.models.
>> > signals.post_save> signal on User, but I'm guessing that won't work
>> > here if you have multiple types of users.
>>
>> When you have multiple *profiles* this will work just fine. It's also
>> not a big problem to solve, because user creation and updating is not an
>> uncontrollable process like the docs suggest.
>> User creation via commandline or automated process really only happens
>> in tests and backup restore procedures.
>>
>> In production it's your job to properly set permissions for meddling
>> with users in the admin and to provide forms that include relevant
>> profile information. When providing good forms the signal is actually
>> disruptive: you already have the information available, you save the
>> user then save the profile information. Having a signal fire that
>> doesn't have access to that profile information is not very useful and
>> can lead to validation errors simply because the handler doesn't have
>> the context.
>>
>> > Or are you better off subclassing
>> > django.contrib.auth.models.AbstractUser? (I get the impression using
>> > profile models is less invasive).
>>
>> The case for subclassing is really only one:
>> Do you not have the right information in the standard user model to
>> authenticate the user?
>> Highly specialized cases aside, it's better to use profiles.
>>
>> A prominent example for not having the right information is when
>> authentication happens with SSL certificates rather then
>> username/password. Another is having different authentication servers
>> and what server to use is depending on a field that isn't in the user
>> model, like "faculty" or "signup_date.year".
>>
>> Hope this helps,
>> --
>> Melvyn Sopacua
>>
>> --
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To unsubscribe from this gr

Canonical way of handling multiple types of users? (Profiles vs subclassing django.contrib.auth.models.AbstractUser)

2016-11-08 Thread Victor Hooi
Hi,

What is the current canonical way to handle multiple user-profiles in 
Django?

For example - say you have "Teachers", "Students", "Parents" - you may have 
slightly different fields for each one and/or different behaviour. Students 
will have things like grades, Parents may have 1-to-many Students etc.

I understand you can use a OneToOne field to associated different user 
profiles with each type of user:

https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#extending-the-existing-user-model

The docs mention using a django.db.models.signals.post_save 

 
signal on User, but I'm guessing that won't work here if you have multiple 
types of users.

Or are you better off subclassing django.contrib.auth.models.AbstractUser? 
(I get the impression using profile models is less invasive).

Regards,
Victor

-- 
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/314de801-0ca7-4eb3-abb9-7a3044994bcd%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: I can't run django server nor activate the virtualenv

2014-04-28 Thread Victor Hooi
Hi Fred,

Are there any lines *below* the error message you pasted?

The last line I can see is:

File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", 
> line 40, in import_module 

__import__(name)


Is there anything else?

Cheers,
Victor

On Monday, 28 April 2014 03:03:40 UTC-7, Fred DJar wrote:
>
>
>
>
> *Hello guys, i'm a newbie so bear with me :)I have installed python 2.7 
> and django 1.6 on my desktop (ubuntu 14)but i can't run the application or 
> activate the virtualenv*
>
> *this is the message i got:*
> ubuntu@ubuntu:~/Downloads/saf$ python manage.py runserver
> Traceback (most recent call last):
>   File "manage.py", line 10, in 
> execute_from_command_line(sys.argv)
>   File 
> "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", 
> line 399, in execute_from_command_line
> utility.execute()
>   File 
> "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", 
> line 392, in execute
> self.fetch_command(subcommand).run_from_argv(self.argv)
>   File 
> "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", 
> line 242, in run_from_argv
> self.execute(*args, **options.__dict__)
>   File 
> "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", 
> line 280, in execute
> translation.activate('en-us')
>   File 
> "/usr/local/lib/python2.7/dist-packages/django/utils/translation/__init__.py",
>  
> line 130, in activate
> return _trans.activate(language)
>   File 
> "/usr/local/lib/python2.7/dist-packages/django/utils/translation/trans_real.py",
>  
> line 188, in activate
> _active.value = translation(language)
>   File 
> "/usr/local/lib/python2.7/dist-packages/django/utils/translation/trans_real.py",
>  
> line 177, in translation
> default_translation = _fetch(settings.LANGUAGE_CODE)
>   File 
> "/usr/local/lib/python2.7/dist-packages/django/utils/translation/trans_real.py",
>  
> line 159, in _fetch
> app = import_module(appname)
>   File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", 
> line 40, in import_module
> __import__(name)
>
>

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


Using filter_horizontal with InlineAdmin - should work, right?

2014-04-07 Thread Victor Hooi
Hi,

I'm hacking up a system to manage attendees at a camp.

I have a Person model (which might be better as a customer UserModel, still 
not sure).

There are multiple types of people - e.g. camp attendees, staff, 
supervisors etc.

Each person that is a camp attendee will also have an "Attendance" model 
associated with it (but other types of people will not have one).

If you think I'm better off modelling it a different way (e.g. abstract 
models, or some kind of inheritance), I'm open to suggestions.

This is my models.py fragment for Attendance:

class Attendance(models.Model):
> person = models.OneToOneField(Person)
> stream = models.ForeignKey(Stream)
> subjects = models.ManyToManyField(Subject)
> camp = models.ForeignKey(Camp)


This is my admin.py for Person:

class AttendanceInline(admin.TabularInline):
> model = Attendance 

 

class PersonAdmin(admin.ModelAdmin):
> date_hierarchy = 'date_of_birth'
> fieldsets = (
> ('Personal Details', {
> 'fields': ('first_name', 'middle_name', 'last_name', 'gender', 
> 'date_of_birth', 'passport_number', 'working_with_children_check', 'photo', 
> 'school', 'home_church')
> }),
> ('Contact Details', {
> 'fields': ('email', 'phone_number', 'postal_address', 
> 'home_address')
> }),
> ('Other - think of a better name', {
> 'fields': ('serving_church', 'supervisor', 'year_12')
> })
> )
> inlines = [
> AttendanceInline,
> ] 

 

admin.site.register(Person, PersonAdmin)


and my admin.py for Attendance:

class AttendanceAdmin(admin.ModelAdmin):
> filter_horizontal = ['subjects']



When I edit a Person model, I want to have an inline for Attendance, and in 
that, use a filter_horizontal widget for "subjects".

However, currently, AttendanceAdmin on it's own has the filter_horizontal, 
but the inline does not.

This ticket seems to imply it should work:

https://code.djangoproject.com/ticket/8292

hence I'm assuming I've wired up something wrong in the above - any 
thoughts?

Cheers,
Victor

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


Loading data from Django into RedShift - ORM vs SQL?

2013-10-17 Thread Victor Hooi
Hi,

We have a Django eCommerce site, from where we want to load transactional 
data into Amazon RedShift (i.e. basically ETL).

This would probably be a batch load run either once a day, or at intervals 
throughout the day.

(I'm also curious about whether it's possible to stream the data in, but I 
don't think that will work well with RedShift).

My question is regarding how we should be extracting the data - we can 
either hook directly into the Django ORM, or just use SQL by hand.

What are people's experiences with either approach? Any thoughts on 
pros/cons of either?

Cheers,
Victor

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


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

2013-09-24 Thread Victor Hooi
Hi,

I'm trying to use aggregation to count the number of "likes" on an item.

The likes for an item are stored in a related model, called LikeStatus:

class Item(models.Model):
> ...
> class ItemLikeStatus(models.Model):
> LIKE_STATUS_CHOICES = (
> ('L', 'Liked'),
> ('U', 'Unliked'),
> ('A', 'Abstained (no vote)'),
> ('N', 'Not seen yet'),
> )
> user = models.ForeignKey(User)
> item = models.ForeignKey(Item)
> liked_status = models.CharField(max_length=1, 
> choices=LIKE_STATUS_CHOICES)


I'm using the following aggregation:

items_by_popularity = 
> Item.objects.all().annotate(Count('itemlikestatus')).order_by('-itemlikestatus__count')[:number_requested]


However, I would like to count up only the like statuses where the 
liked_status code is "L".

My thoughts are that I can iterate through the entire Item set myself and 
do a filter on the related itemlikestatus for each Item, and produce the 
aggregation by hand. However, that seems like a silly way to do it, and 
doesn't really use the database.

I was wondering if there's a smarter way to still use aggregation, but 
filter out to only count a subset of related ItemLikeStatus?

Cheers,
Victor

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Using environment variables in settings.py - good practice? How to handle missing variables gracefully?

2013-09-18 Thread Victor Hooi
Hi,

Hmm, in many cases there isn't really a sensible default (e.g. API keys or 
passwords).

I was asking more in terms of - is this the "right" way of doing it in 
Django, or are people using some other technique to handle configuration 
you don't want in the repo?

And is there a special exception type you should throw if it's not being 
set, or is there a better way to handle it?

Cheers,
Victor

On Thursday, 19 September 2013 15:54:15 UTC+10, Dig wrote:
>
> Hi,
>
>   Do you means some thing like this?
>
> os.environ.get('SOME_VARIABLE', 'default_value')
>
> Regards,
> Dig
> On Sep 19, 2013 1:37 PM, "Victor Hooi" <victo...@gmail.com > 
> wrote:
>
>> Hi,
>>
>> I have several settings in my Django settings.py file that are specific 
>>
>> Currently, I'm grabbing these from environment variables in settings.py:
>>
>> import os
>>> ...
>>> # TODO - We need to gracefully catch if these aren't set.
>>> SOME_VARIABLE = os.environ['SOME_VARIABLE']
>>
>>
>> This includes things like API keys, database IPs, database 
>> username/passwords, static file locations etc.
>>
>> I then set these in the virtualenv activate script.
>>
>> Is this a good practice in Django?
>>
>> Also, is there a graceful way of catching when these aren't set? 
>> Currently, I'm using some of those settings variables in models.py, and 
>> it's failing silently. Should I put each os.environ call in a try/except 
>> block, or is there a more Pythonic way?
>>
>> Cheers,
>> Victor
>>
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an 
>> email to django-users...@googlegroups.com .
>> To post to this group, send email to django...@googlegroups.com
>> .
>> Visit this group at http://groups.google.com/group/django-users.
>> For more options, visit https://groups.google.com/groups/opt_out.
>>
>

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.


Using environment variables in settings.py - good practice? How to handle missing variables gracefully?

2013-09-18 Thread Victor Hooi
Hi,

I have several settings in my Django settings.py file that are specific 

Currently, I'm grabbing these from environment variables in settings.py:

import os
> ...
> # TODO - We need to gracefully catch if these aren't set.
> SOME_VARIABLE = os.environ['SOME_VARIABLE']


This includes things like API keys, database IPs, database 
username/passwords, static file locations etc.

I then set these in the virtualenv activate script.

Is this a good practice in Django?

Also, is there a graceful way of catching when these aren't set? Currently, 
I'm using some of those settings variables in models.py, and it's failing 
silently. Should I put each os.environ call in a try/except block, or is 
there a more Pythonic way?

Cheers,
Victor

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.


Using PredictionIO with Django - where to put client creation?

2013-09-09 Thread Victor Hooi
Hi,

I have a Django app that I'm using with PredictionIO 
(http://prediction.io/), which is a wrapper around Apache Mahout.

They also have a Python client that sends data to the backend server:

http://pythonhosted.org/PredictionIO/predictionio.html

As part of this, I've attached post_save signals to my Django models, so 
that I create the appropriate PredictionIO users and items when the Django 
models get created.

So in my models.py files, I have things like:

from django.dispatch import receiver
> from django.db.models.signals import post_save
> import predictionio
> ...
> client = 
> predictionio.Client(appkey="pEICENyM27veyCwxj0R7LgeK8WnSg9TV5ediToCciuZAkUkLFVmZw9lOCWEqYu5s")
> ...
> class Product(models.Model):
> ...define Product fields...
> ...
> @receiver(post_save, sender=Product)
> def create_recommender_product(sender, instance=None, created=False, 
> **kwargs):
> if created:
> client.create_item(str(instance.id), ('type1',))


I have a similar setup for my custom User model, and also a post_save 
signal for when a user likes/dislikes a product.

My question is - I've put the client creation code at the top of models.py 
- my understanding was this only gets called once when we first read in 
models.py, then it gets re-used each time.

Is the above good practice?

And also, the prediction.io calls in my post_save functions are all 
blocking - is that a major issue? Should I be shoving this into something 
like Celery, or is the above acceptable?

Cheers,
Victor

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Bulk-creating two ForeignKey linked models - id field for relationship isn't set properly?

2013-08-20 Thread Victor Hooi
Hi,

Cool, thanks for the link to the ticket. Very interesting reading, and I
learnt something =).

Apparently the ticket says the patch still needs docs/tests - guess it'll
be a while before this gets integrated then...hmm.

Cheers,
Victor


On Wed, Aug 21, 2013 at 2:11 AM, Simon Charette <charett...@gmail.com>wrote:

> This is a known limitation of `bulk_create`: objects used for bulk
> creation are not assigned a primary 
> key<https://code.djangoproject.com/ticket/19527>
> .
>
> Le mardi 20 août 2013 05:57:52 UTC-4, Victor Hooi a écrit :
>
>> Hi,
>>
>> *1. Bulk Creating Products/ProductImages*
>>
>> I have a Django custom management command that bulk-loads a list of
>> products and product images from a JSON file.
>>
>> I have a Product model, along with an ProductImage model - each Product
>> may have many ProductImages.
>>
>> class Product(models.Model):
>>> ...
>>> name = models.CharField(max_length=**200, help_text='Name of this
>>> product.')
>>> description = models.TextField(help_text='**Short description of
>>> this product.')
>>> external_id = models.CharField(max_length=**100, unique=True,
>>> help_text='Unique identifier for this product provided by the supplier.')
>>> brand = models.ForeignKey(Brand)
>>> supplier = models.ForeignKey(Supplier)
>>> selling_price = models.DecimalField(max_**digits=10,
>>> decimal_places=2, help_text='The price which we\'re selling this product
>>> at.')
>>> original_price = models.DecimalField(max_**digits=10,
>>> decimal_places=2, help_text='The original retail price of this product,
>>> before any discounts.')
>>> current_stock_level = models.PositiveIntegerField(**default=0)
>>> current_sold_count = models.PositiveIntegerField(**default=0)
>>> ...
>>
>>
>> class ProductImage(models.Model):
>>> product = models.ForeignKey(Product, related_name='images')
>>> image = models.ImageField(max_length=**200,
>>> upload_to='product_images')
>>> # TODO - Do we actually want to make retina images a distinct column
>>> in the database? May need to revisit this.
>>> retina_image = models.ImageField(max_length=**200,
>>> upload_to='product_images')
>>> size = models.ForeignKey(ImageSize)
>>> ordinal = models.PositiveIntegerField(**default=0)
>>> class Meta:
>>> ordering = ['ordinal']
>>> unique_together = ('product', 'size', 'ordinal')
>>> def __unicode__(self):
>>> return u'%s image %i for %s' % (self.size, self.ordinal,
>>> self.product.name)
>>
>>
>> I have a single look that iterates through the JSON file, creating a list
>> of Products, as well as a list of ProductImages that link back to those
>> products. (The below is an extract)
>>
>> products = []
>>> product_images = []
>>> ...
>>> for product in json_data:
>>> brand, created_new_brand = Brand.objects.get_or_create(**
>>> name=product['brand'])
>>> if created_new_brand:
>>> new_brands_created += 1
>>> ...
>>> current_product = Product(name = product['name'],
>>> brand = brand,
>>> supplier = supplier,
>>> description =
>>> product['description'],
>>> ...
>>> )
>>> ...
>>> for image_set in product['images']:
>>> for size in image_sizes.keys():
>>> product_images.append(**ProductImage(product =
>>> current_product,
>>>image =
>>> image_set[size],
>>>retina_image
>>> = image_set[size],
>>>size =
>>> image_sizes[size],
>>>ordinal =
>>> image_set_counter,
>>>))
>>> image_set_counter += 1
>>> ...
>>> Product.objects.bulk_create(**products)
>>> ...
>>

Re: Bulk-creating two ForeignKey linked models - id field for relationship isn't set properly?

2013-08-20 Thread Victor Hooi
Hi,

In the source file (JSON) - I have a list of Products dictionaries.

The images are one of the elements in that dictionary - hence, the link 
between them is that images is a child of Product.

Hence, when I loop through to create Product, I can create the images and 
link it there.

At the end, the ProductImage objects all have a valid Product field, but no 
valid Product_id field - perhaps I can create all the 
Products/ProductImages, do a bulk_create() on the Products, then do a 
lookup for each ProductImage for that Product and assign a valid product_id?

However, not sure whether doing that extra lookup is going to be any better 
than just iterating through and doing a save() each round and avoiding 
bulk_create() altogether.

Cheers,
Victor

On Tuesday, 20 August 2013 22:51:57 UTC+10, Daniel Roseman wrote:
>
> On Tuesday, 20 August 2013 12:10:34 UTC+1, Victor Hooi wrote:
>
>> Hi,
>>
>> 1. Hmm, in that case, using bulk_create may not work - I'm currently 
>> relying on generating the full lists of Products and ProductImages, then 
>> saving in a batch at the end.
>>
>> So I need to loop through and call .save() individually on each Product, 
>> then the corresponding ProductImages, before moving onto the next Product().
>>
>> Are there any workarounds for this, or any way I could still leverage on 
>> bulk_create()?
>>
>>
> Can you bulk save the Products first, then assign them to the 
> ProductImages and bulk save those?
> --
> DR.
>

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Bulk-creating two ForeignKey linked models - id field for relationship isn't set properly?

2013-08-20 Thread Victor Hooi
Hi,

1. Hmm, in that case, using bulk_create may not work - I'm currently 
relying on generating the full lists of Products and ProductImages, then 
saving in a batch at the end.

So I need to loop through and call .save() individually on each Product, 
then the corresponding ProductImages, before moving onto the next Product().

Are there any workarounds for this, or any way I could still leverage on 
bulk_create()?

2. Cool, thanks for the tip - completely forgotten about this - enumerate() 
will be very useful =).

Cheers,
Victor

On Tuesday, 20 August 2013 20:40:52 UTC+10, Daniel Roseman wrote:
>
> On Tuesday, 20 August 2013 10:57:52 UTC+1, Victor Hooi wrote:
>
>> Hi,
>>
>> *1. Bulk Creating Products/ProductImages*
>>
>> I have a Django custom management command that bulk-loads a list of 
>> products and product images from a JSON file.
>>
>> I have a Product model, along with an ProductImage model - each Product 
>> may have many ProductImages.
>>
>> class Product(models.Model):
>>> ...
>>> name = models.CharField(max_length=200, help_text='Name of this 
>>> product.')
>>> description = models.TextField(help_text='Short description of this 
>>> product.')
>>> external_id = models.CharField(max_length=100, unique=True, 
>>> help_text='Unique identifier for this product provided by the supplier.')
>>> brand = models.ForeignKey(Brand)
>>> supplier = models.ForeignKey(Supplier)
>>> selling_price = models.DecimalField(max_digits=10, decimal_places=2, 
>>> help_text='The price which we\'re selling this product at.')
>>> original_price = models.DecimalField(max_digits=10, 
>>> decimal_places=2, help_text='The original retail price of this product, 
>>> before any discounts.')
>>> current_stock_level = models.PositiveIntegerField(default=0)
>>> current_sold_count = models.PositiveIntegerField(default=0)
>>> ...
>>
>>
>> class ProductImage(models.Model):
>>> product = models.ForeignKey(Product, related_name='images')
>>> image = models.ImageField(max_length=200, upload_to='product_images')
>>> # TODO - Do we actually want to make retina images a distinct column 
>>> in the database? May need to revisit this.
>>> retina_image = models.ImageField(max_length=200, 
>>> upload_to='product_images')
>>> size = models.ForeignKey(ImageSize)
>>> ordinal = models.PositiveIntegerField(default=0)
>>> class Meta:
>>> ordering = ['ordinal']
>>> unique_together = ('product', 'size', 'ordinal')
>>> def __unicode__(self):
>>> return u'%s image %i for %s' % (self.size, self.ordinal, 
>>> self.product.name)
>>
>>
>> I have a single look that iterates through the JSON file, creating a list 
>> of Products, as well as a list of ProductImages that link back to those 
>> products. (The below is an extract)
>>
>> products = []
>>> product_images = []
>>> ...
>>> for product in json_data:
>>> brand, created_new_brand = 
>>> Brand.objects.get_or_create(name=product['brand'])
>>> if created_new_brand:
>>> new_brands_created += 1
>>> ...
>>> current_product = Product(name = product['name'],
>>> brand = brand,
>>> supplier = supplier,
>>> description = 
>>> product['description'],
>>> ...
>>> )
>>> ...
>>> for image_set in product['images']:
>>> for size in image_sizes.keys():
>>> product_images.append(ProductImage(product = 
>>> current_product,
>>>image = 
>>> image_set[size],
>>>retina_image 
>>> = image_set[size],
>>>size = 
>>> image_sizes[size],
>>>ordinal = 
>>> image_set_counter,
>>>))
>>> image_set_counter += 1
>>> ...
>>> Product.objects.bulk_create(p

Bulk-creating two ForeignKey linked models - id field for relationship isn't set properly?

2013-08-20 Thread Victor Hooi
Hi,

*1. Bulk Creating Products/ProductImages*

I have a Django custom management command that bulk-loads a list of 
products and product images from a JSON file.

I have a Product model, along with an ProductImage model - each Product may 
have many ProductImages.

class Product(models.Model):
> ...
> name = models.CharField(max_length=200, help_text='Name of this 
> product.')
> description = models.TextField(help_text='Short description of this 
> product.')
> external_id = models.CharField(max_length=100, unique=True, 
> help_text='Unique identifier for this product provided by the supplier.')
> brand = models.ForeignKey(Brand)
> supplier = models.ForeignKey(Supplier)
> selling_price = models.DecimalField(max_digits=10, decimal_places=2, 
> help_text='The price which we\'re selling this product at.')
> original_price = models.DecimalField(max_digits=10, decimal_places=2, 
> help_text='The original retail price of this product, before any 
> discounts.')
> current_stock_level = models.PositiveIntegerField(default=0)
> current_sold_count = models.PositiveIntegerField(default=0)
> ...


class ProductImage(models.Model):
> product = models.ForeignKey(Product, related_name='images')
> image = models.ImageField(max_length=200, upload_to='product_images')
> # TODO - Do we actually want to make retina images a distinct column 
> in the database? May need to revisit this.
> retina_image = models.ImageField(max_length=200, 
> upload_to='product_images')
> size = models.ForeignKey(ImageSize)
> ordinal = models.PositiveIntegerField(default=0)
> class Meta:
> ordering = ['ordinal']
> unique_together = ('product', 'size', 'ordinal')
> def __unicode__(self):
> return u'%s image %i for %s' % (self.size, self.ordinal, 
> self.product.name)


I have a single look that iterates through the JSON file, creating a list 
of Products, as well as a list of ProductImages that link back to those 
products. (The below is an extract)

products = []
> product_images = []
> ...
> for product in json_data:
> brand, created_new_brand = 
> Brand.objects.get_or_create(name=product['brand'])
> if created_new_brand:
> new_brands_created += 1
> ...
> current_product = Product(name = product['name'],
> brand = brand,
> supplier = supplier,
> description = 
> product['description'],
> ...
> )
> ...
> for image_set in product['images']:
> for size in image_sizes.keys():
> product_images.append(ProductImage(product = 
> current_product,
>image = 
> image_set[size],
>retina_image = 
> image_set[size],
>size = 
> image_sizes[size],
>ordinal = 
> image_set_counter,
>))
> image_set_counter += 1
> ...
> Product.objects.bulk_create(products)
> ...
> for product_image in product_images:
> product_image.save()


I then call bulk_create() on the products list, which succeeds.

However, when I try to call .save() or bulk_create() on the ProductImage, 
they fail, saying that product_id is NULL.

IntegrityError: null value in column "product_id" violates not-null 
> constraint
> DETAIL:  Failing row contains (8, null, 
> https://cdn.foobar.com.au/site_media/uploads/product_im..., 
> https://cdn.foobar.com.au/site_media/uploads/product_im..., 4, 0).


If I actually inspect one one of the items in the ProductImages list - 
product_image.product seems to point to a valid product, however, 
product_image.product_id seems to be None:

ipdb> p product_image.product
> 
> ipdb> p product_image.product_id
> None


This is strange, because if I manually create the same ProductImage from 
the shell, the product_image.product_id field is populated.

I'm guessing this product_id field should resolve to the pk id of the 
product in product_image.product, right?

However, in my case, when I instantiate each ProductImage and set it to a 
Product, that actual Product hasn't been saved to the database - I'm 
guessing that Product.id hasn't been generated yet, and the ProductImage 
object I have is somehow broken?

Is there another way I can achieve this then? (Loop through file, creating 
a list of Products and ProductImages, then bulk_creating them?)

*2. Image Set Counter*

Also, second question - in the last code segment above, I have a 

Representing infinity or "no limit" in an integer field?

2013-08-19 Thread Victor Hooi
Hi,

I have a Django IntegerField that I'm using to store the purchase limit for 
a product.

purchase_limit = models.IntegerField()


I also need to represent no limit (i.e. infinity) as well in that field.

I was thinking of just using NULL to represent no limit.

purchase_limit = models.IntegerField(blank=True, null=True)


Zero would have a meaning for this field (you can't buy any), however 
negative numbers don't have any meaning.

Hence, another option is just to use say, -1 as the value to represent no 
limit.

Any thoughts on either option, or which one is more "correct"?

Cheers,
Victor

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Model verbose name appears to split up on capitalisation (e.g. "iOS") - any way to suppress this?

2013-08-15 Thread Victor Hooi
Hi,

That works =):

<https://lh3.googleusercontent.com/-mks31U0PuKs/Ugx7iHJ2mVI/XyI/gPwj2aOfiEo/s1600/Screen+Shot+2013-08-15+at+4.55.48+PM.png>
I just found the same thing mentioned on SO as well:

http://stackoverflow.com/a/9111694

Hmm, I'm guessing this is a known gotcha and workaround, right? Is it 
documented anywhere in the Django docs, or is it considered too much of an 
edge case?

Cheers,
Victor

On Thursday, 15 August 2013 15:08:00 UTC+10, Mike Dewhirst wrote:
>
> On 15/08/2013 2:06pm, Victor Hooi wrote: 
> > For example, verbose_name-Plural on the main admin page (/admin) still 
> > seems to insist on capitalising the first "i" - as in, it appears as 
> > "IOS clients", rather than "iOS clients", as it's set in class Meta: 
> > 
>
> Try verbose_name = " iOS Clients" with a leading space 
>

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Model verbose name appears to split up on capitalisation (e.g. "iOS") - any way to suppress this?

2013-08-14 Thread Victor Hooi
Hi,

Aha, that's embarrassing...yes, it was the lowercase M.

The extra spacing appears to be fixed now.

However, capitalisation still seems a bit funny.

For example, verbose_name-Plural on the main admin page (/admin) still 
seems to insist on capitalising the first "i" - as in, it appears as "IOS 
clients", rather than "iOS clients", as it's set in class Meta:

<https://lh4.googleusercontent.com/-NuvqTprAkbM/UgxS0cVyvrI/Xxk/-KzZKnrMiZk/s1600/Screen+Shot+2013-08-15+at+2.00.38+PM.png>
However, strangely enough the verbose_name is capitalised correctly:

<https://lh4.googleusercontent.com/-D95Sku29KNk/UgxTFcXOyRI/Xxs/Aq9c2Pn6xDM/s1600/Screen+Shot+2013-08-15+at+2.03.12+PM.png>
Is there any way to fix that issue?

And DRF is just being completely random, but I guess I'll ned to look into 
that to see where it's getting it's verbose form from:

<https://lh3.googleusercontent.com/-SyhDu2sXyRM/UgxTmrTck4I/Xx4/3IxlNTqQHZw/s1600/Screen+Shot+2013-08-15+at+2.05.22+PM.png>

Cheers,
Victor

On Thursday, 15 August 2013 12:50:40 UTC+10, Ramiro Morales wrote:
>
> On Wed, Aug 14, 2013 at 11:46 PM, Victor Hooi 
> <victo...@gmail.com> 
> wrote: 
> > Hi, 
> > 
> > I have a Django model: 
> > 
> >> class iOSClient(models.Model): 
> >> ... 
> >> class meta: 
> >> ... 
> >> verbose_name = 'iOS client' 
> >> verbose_name_plural = 'iOS clients' 
> > 
> > 
> > However, when this model appears in the Django Admin, or in say, Django 
> Rest 
> > Framework, the human-readable name seems to given as "I os client" or "i 
> os 
> > client". 
> > 
> > Is there any way to easily suppress this behaviour? 
>
> These textual representations should be obeying what you specified with 
> the verbose_name* options. 
>
> Are you actually using "meta"? It should be Meta with a capital M. 
>
> Can you try that and tell us if that solves things for you? 
>
> -- 
> Ramiro Morales 
> @ramiromorales 
>

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.


Model verbose name appears to split up on capitalisation (e.g. "iOS") - any way to suppress this?

2013-08-14 Thread Victor Hooi
Hi,

I have a Django model:

class iOSClient(models.Model):
> ...
> class meta:
> ...
> verbose_name = 'iOS client'
> verbose_name_plural = 'iOS clients'


However, when this model appears in the Django Admin, or in say, Django 
Rest Framework, the human-readable name seems to given as "I os client" or "i 
os client".

Is there any way to easily suppress this behaviour?

Cheers,
Victor

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.


Re: Returning random model objects - is order_by('?') on Postgres safe to use now?

2013-08-07 Thread Victor Hooi
Hi,

The issue is that apparently, for ORDER BY RANDOM, the database will foo
through and generate a random number for *every* row in a new column, then
do a sort by that be column.

Obviously that's an expensive operation and since that column is random,
it's a worst case sort.

For my code I was using randint to generate random numbers between 0 and
the highest pk (and handling ObjectDoesNotExist).

Hence, this was meant to be faster and cheaper.

However, I'm curious if database backend has changes significantly?

Cheers,
Victor
On 08/08/2013 12:11 PM, "Tom Lockhart" <tlockhart1...@gmail.com> wrote:

> I haven't used the feature, but there is no reason to think that having
> the db backend do a random sort is any slower than you doing it yourself.
>
> If your query can reduce the number of rows returned to a relatively small
> number, any "order by" should have acceptable performance. If not, it will
> be expensive no matter who does the work.
>
> hth
>
>     - Tom
>
> On 2013-08-07, at 6:55 PM, Victor Hooi <victorh...@gmail.com> wrote:
>
> Hi,
>
> We have some code to return randomised Django model instances.
>
> Initially, I was using random.randint(), and returning objects by index
> between 0 < max_id.
>
> This was based on the Django docs:
>
> https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by
>
> specifically, the part:
>
> Note: order_by('?') queries may be expensive and slow, depending on the
>> database backend you’re using.
>
>
> This blog post from February 2011 also seems to back that up:
>
> http://www.peterbe.com/plog/getting-random-rows-postgresql-django
>
> However, I just ran the benchmarks on my own box running Django 1.5 and
> Postgres 9.2.4, and the ORDER BY RANDOM() approach was slower, but not
> substantially so (certainly not to the extent hinted at by the blog post).
>
> I'm curious - what are other people's experiences with using ORDERY BY
> RANDOM versus other approaches?
>
> Has Postgres made some recent changes which makes ORDER BY RANDOM the
> better option now?
>
> Which database backends specifically should we be warned about when saying
> that order_by('?') is expensive and slow?
> Cheers,
> Victor
>
> --
> 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.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
>
>
>
>  --
> You received this message because you are subscribed to a topic in the
> Google Groups "Django users" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/django-users/QJk3HDYAkro/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to
> django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>
>

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.


Returning random model objects - is order_by('?') on Postgres safe to use now?

2013-08-07 Thread Victor Hooi
Hi,

We have some code to return randomised Django model instances.

Initially, I was using random.randint(), and returning objects by index 
between 0 < max_id.

This was based on the Django docs:

https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by

specifically, the part:

Note: order_by('?') queries may be expensive and slow, depending on the 
> database backend you’re using.  


This blog post from February 2011 also seems to back that up:

http://www.peterbe.com/plog/getting-random-rows-postgresql-django

However, I just ran the benchmarks on my own box running Django 1.5 and 
Postgres 9.2.4, and the ORDER BY RANDOM() approach was slower, but not 
substantially so (certainly not to the extent hinted at by the blog post).

I'm curious - what are other people's experiences with using ORDERY BY 
RANDOM versus other approaches? 

Has Postgres made some recent changes which makes ORDER BY RANDOM the 
better option now?

Which database backends specifically should we be warned about when saying 
that order_by('?') is expensive and slow?
Cheers,
Victor

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.




Re: Using standard Django admin User forms for Custom User model?

2013-08-05 Thread Victor Hooi
Hi,

I got it working at a basic level by just registering against UserAdmin.

from django.contrib.auth.admin import UserAdmin
> admin.site.register(Customer, UserAdmin)


For custom fields, I just needed to add them to fieldsets.

However, even though I could view/edit users, adding new Users failed - the 
forms seemed to be looking specifically for auth_user.

Apparently this is something that could be made easier?

https://code.djangoproject.com/ticket/19353
http://stackoverflow.com/a/17496836/139137

Is that something that could be in 1.6?

Cheers,
Victor

On Thursday, 1 August 2013 09:45:51 UTC+10, Russell Keith-Magee wrote:
>
>
> On Wed, Jul 31, 2013 at 12:36 PM, Victor Hooi <victo...@gmail.com
> > wrote:
>
>> Hi,
>>
>> When you add a Django User through the admin, it presents you with a 
>> initial screen to enter a username and password  (/admin/auth/user/add/), 
>> and then handles hashing for you.
>>
>> Also, when you go to edit a User, it gives you a Change Password form 
>> (e.g. /admin/auth/user/2/password/)
>>
>> I'm using a custom user model in my Django app, by inheriting from 
>> AbstractCustomer.
>>
>> If I add this to the admin now, password is just a standard textbox, and 
>> obviously if I create a user through that, I can't login since I assume 
>> it's not hashing the password.
>>
>> Is there any way I can use the normal Django User admin forms with a 
>> custom User model?
>>
>> Secondly, I tried creating a user via the create_user() method on my 
>> custom User object - I still wasn't able to login to the admin using that 
>> username/password, which I thought was weird.
>>
>
> Have you read the documentation on this issue? 
>
>
> https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#custom-users-and-the-built-in-auth-forms
>
> The docs discuss what you have to do in order to get your User model 
> represented in the admin, and also provide a worked example.
>
> If you've got a specific question that isn't covered by the docs, or if 
> you're confused by what the docs say, let us know.
>
> Yours,
> Russ Magee %-)
>

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.




Using standard Django admin User forms for Custom User model?

2013-07-30 Thread Victor Hooi
Hi,

When you add a Django User through the admin, it presents you with a 
initial screen to enter a username and password  (/admin/auth/user/add/), 
and then handles hashing for you.

Also, when you go to edit a User, it gives you a Change Password form 
(e.g. /admin/auth/user/2/password/)

I'm using a custom user model in my Django app, by inheriting from 
AbstractCustomer.

If I add this to the admin now, password is just a standard textbox, and 
obviously if I create a user through that, I can't login since I assume 
it's not hashing the password.

Is there any way I can use the normal Django User admin forms with a custom 
User model?

Secondly, I tried creating a user via the create_user() method on my custom 
User object - I still wasn't able to login to the admin using that 
username/password, which I thought was weird.

Cheers,
Victor

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.




Re: Best practice - using Django model's in-built id field?

2013-07-19 Thread Victor Hooi
Hi,

Funny you guys should mention that =), after Mike's post, I ended up just 
using David Cramer's django-uuidfield 
(https://github.com/dcramer/django-uuidfield) package.

(There's also django-shortuuidfield 
- https://github.com/nebstrebor/django-shortuuidfield).

For Postgres, this uses the uuid type 
- http://www.postgresql.org/docs/9.1/static/datatype-uuid.html).

This also sets unique=True - not sure what happens if there's a collision, 
I assume it just won't create that one.

The only thing I was concerned about was a performance hit from calculating 
the UUID for each transaction, however, I suspect that's something I don't 
need to worry about until down the track.

Cheers,
Victor

On Friday, 19 July 2013 23:45:06 UTC+10, Javier Guerra wrote:
>
> On Fri, Jul 19, 2013 at 4:26 AM, Tom Evans 
>  
> wrote: 
> > Because of this, I usually add a uuid field as a unique key, but leave 
> > id as the primary key. 
>
> same here. 
>
> but only for those tables whose records would be seen by the public. 
> kinda like 'slugs for non-textual objects' 
>
> -- 
> Javier 
>

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.




Re: Design for storing likes/dislikes?

2013-07-19 Thread Victor Hooi
Hi,

Hmm, I'm thinking I might need to go for an enum/choices rather than a 
NullBooleanField.

There are actually four states (so far) that can exist in the relationship 
between a user and a widget.

   1. Like
   2. Unlike
   3. No vote (i.e. abstain).
   4. Not asked yet

I suppose I could still use NullBooleanField, but use Like=True, 
Unlike=False, No Vote = Null, and have that row not exist in the M2M if we 
haven't asked about that widget yet - however, not sure if that's a bit 
ambiguous? And it may close the door down the track to other states?

Also, it definitely is a M2M between Users and Widgets - since each user 
can like/unlike many widgets, and each widget can be liked/unliked by many 
users.

Cheers,
Victor

On Saturday, 20 July 2013 00:57:54 UTC+10, Steven Smith wrote:
>
> I've used NullBooleanField for this before, as well.  A lot quicker to 
> query on than a ManyToMany, also.
>
>
>
> On Tuesday, July 16, 2013 9:24:54 PM UTC-4, donarb wrote:
>>
>> On Tuesday, July 16, 2013 5:29:47 PM UTC-7, Victor Hooi wrote:
>>>
>>> Hi,
>>>
>>> We have a list of users, who are going to like/dislike various widgets.
>>>
>>> My question is regarding how to store the like/dislikes.
>>>
>>> Essentially, there can be three states between a user and a widget - 
>>> like, dislike, and unrated, so it's not just a straight Boolean.
>>>
>>> I'm thinking of just doing a M2M between user and widgets models, and 
>>> then storing an extra field on that M2M.
>>>
>>> I can either store a Boolean, for whether the item is liked/unliked - 
>>> and then an unrated item simply won't be exist in the table.
>>>
>>> Or I can store a integer (with a choice tupled defined), with say 
>>> 0=unrated, 1=like, 2 = unlike, and all possible combinations are listed.
>>>
>>> We'll be doing queries to compare users, and see if their likes/dislikes 
>>> intersect.
>>>
>>> Are there any pros/cons of the two approaches for this given query, or 
>>> is there perhaps a more efficient way of storing this data?
>>>
>>> Cheers,
>>> Victor
>>>
>>
>>
>>
>> Django has a NullBooleanField that allows 3 states, Unknown (null), True, 
>> False.
>>
>>  
>>
>

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.




Re: Best practice - using Django model's in-built id field?

2013-07-18 Thread Victor Hooi
Hi,

Actually, while we're there - is this a suitable use of AutoField? Or is 
there a better way to generate unique transactions IDs? python.uuid? Or 
something better?

Cheers,
Victor

On Friday, 19 July 2013 11:57:21 UTC+10, Victor Hooi wrote:
>
> Hi,
>
> Ok, thanks, I'll generate my own AutoField to track each transaction.
>
> Just to clarify - when you say they'll be issues with migration, what do 
> you mean? Is it because that field is also as a FK to other models? Or 
> something else?
>
> Cheers,
> Victor
>
> On Friday, 19 July 2013 11:50:25 UTC+10, Mike Dewhirst wrote:
>>
>> On 19/07/2013 11:31am, Victor Hooi wrote: 
>> > Hi, 
>> > 
>> > I'm just wondering - is it considered good or bad practice to use a 
>> > Django model's in-built ID field? 
>> > 
>> > Say for example you wanted a unique identifier for each transactio - 
>> > should you be generating your own, or can you use just self.id? 
>>
>> Don't go there. Generate your own. Consider what might happen if you 
>> needed to migrate to a different database or platform. The id integer 
>> will be a nightmare to manage so the unique transactions retain their 
>> original numbers. 
>>
>> Mike 
>>
>>
>> > 
>> > Cheers, 
>> > Victor 
>> > 
>> > -- 
>> > You received this message because you are subscribed to the Google 
>> > Groups "Django users" group. 
>> > To unsubscribe from this group and stop receiving emails from it, send 
>> > an email to django-users...@googlegroups.com. 
>> > To post to this group, send email to django...@googlegroups.com. 
>> > Visit this group at http://groups.google.com/group/django-users. 
>> > For more options, visit https://groups.google.com/groups/opt_out. 
>> > 
>> > 
>>
>>

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.




Re: Best practice - using Django model's in-built id field?

2013-07-18 Thread Victor Hooi
Hi,

Ok, thanks, I'll generate my own AutoField to track each transaction.

Just to clarify - when you say they'll be issues with migration, what do 
you mean? Is it because that field is also as a FK to other models? Or 
something else?

Cheers,
Victor

On Friday, 19 July 2013 11:50:25 UTC+10, Mike Dewhirst wrote:
>
> On 19/07/2013 11:31am, Victor Hooi wrote: 
> > Hi, 
> > 
> > I'm just wondering - is it considered good or bad practice to use a 
> > Django model's in-built ID field? 
> > 
> > Say for example you wanted a unique identifier for each transactio - 
> > should you be generating your own, or can you use just self.id? 
>
> Don't go there. Generate your own. Consider what might happen if you 
> needed to migrate to a different database or platform. The id integer 
> will be a nightmare to manage so the unique transactions retain their 
> original numbers. 
>
> Mike 
>
>
> > 
> > Cheers, 
> > Victor 
> > 
> > -- 
> > You received this message because you are subscribed to the Google 
> > Groups "Django users" group. 
> > To unsubscribe from this group and stop receiving emails from it, send 
> > an email to django-users...@googlegroups.com . 
> > To post to this group, send email to 
> > django...@googlegroups.com. 
>
> > Visit this group at http://groups.google.com/group/django-users. 
> > For more options, visit https://groups.google.com/groups/opt_out. 
> > 
> > 
>
>

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.




Best practice - using Django model's in-built id field?

2013-07-18 Thread Victor Hooi
Hi,

I'm just wondering - is it considered good or bad practice to use a Django 
model's in-built ID field?

Say for example you wanted a unique identifier for each transactio - should 
you be generating your own, or can you use just self.id?

Cheers,
Victor

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.




Re: Design for storing likes/dislikes?

2013-07-18 Thread Victor Hooi
Hi,

I'm leaning more towards NullBooleanField at the moment.

There's a number of reasons we're going for binary voting (like/dislike), 
versus say a star rating. Firstly, rating systems like that are ambiguous - 
a 2-star rating from me may not be the same as a 2-star rating from 
somebody else. I believe YouTube used to have star ratings, and then Google 
changed them to likes/dislike. General consensus seems to be that 
binary-voting systems are better.

http://onpon4.blogspot.com.au/2011/12/5-star-ratings-vs-likesdislikes-why.html
http://davidcel.is/blog/2012/02/01/why-i-hate-five-star-ratings/

Cheers,
Victor

On Thursday, 18 July 2013 06:31:15 UTC+10, arnonym wrote:
>
> On Tue, 16 Jul 2013 17:29:47 -0700 (PDT) Victor Hooi 
> <victo...@gmail.com > wrote: 
> > We have a list of users, who are going to like/dislike various 
> > widgets. 
> > 
> > My question is regarding how to store the like/dislikes. 
> > 
> > Essentially, there can be three states between a user and a widget - 
> > like, dislike, and unrated, so it's not just a straight Boolean. 
> > 
> > I'm thinking of just doing a M2M between user and widgets models, and 
> > then storing an extra field on that M2M. 
> > 
> > I can either store a Boolean, for whether the item is liked/unliked - 
> > and then an unrated item simply won't be exist in the table. 
> > 
> > Or I can store a integer (with a choice tupled defined), with say 
> > 0=unrated, 1=like, 2 = unlike, and all possible combinations are 
> > listed. 
> > 
> > We'll be doing queries to compare users, and see if their 
> > likes/dislikes intersect. 
> > 
> > Are there any pros/cons of the two approaches for this given query, 
> > or is there perhaps a more efficient way of storing this data? 
>
> I would probably do this with an explicit many to many relationship. 
> My first thought would be to use a boolean (true for like, false for 
> unlike, not a row in the table for unrated). On second thought I would 
> replace your integer-enum idea by using the integer for a real rating 
> for example from -5 to 5. While at first you might just map like/unlike 
> to 5/-5, for the future you could do rows of stars or rows of 
> thumbs-up/-downs. 
>
> Have fun, 
>
> Arnold 
>

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.




Re: Design for storing likes/dislikes?

2013-07-17 Thread Victor Hooi
Hi,

Cool, didn't know that - thanks =).

Performance wise, am I better off creating every single relationship 
between Users/Widgets as I add users/widgets, and defaulting them to Null 
then?

Or is it better to just add the entries as users like/unlike widgets, and 
infer the null state from the relationship not being there?

Cheers,
Victor

On Wednesday, 17 July 2013 11:24:54 UTC+10, donarb wrote:
>
> On Tuesday, July 16, 2013 5:29:47 PM UTC-7, Victor Hooi wrote:
>>
>> Hi,
>>
>> We have a list of users, who are going to like/dislike various widgets.
>>
>> My question is regarding how to store the like/dislikes.
>>
>> Essentially, there can be three states between a user and a widget - 
>> like, dislike, and unrated, so it's not just a straight Boolean.
>>
>> I'm thinking of just doing a M2M between user and widgets models, and 
>> then storing an extra field on that M2M.
>>
>> I can either store a Boolean, for whether the item is liked/unliked - and 
>> then an unrated item simply won't be exist in the table.
>>
>> Or I can store a integer (with a choice tupled defined), with say 
>> 0=unrated, 1=like, 2 = unlike, and all possible combinations are listed.
>>
>> We'll be doing queries to compare users, and see if their likes/dislikes 
>> intersect.
>>
>> Are there any pros/cons of the two approaches for this given query, or is 
>> there perhaps a more efficient way of storing this data?
>>
>> Cheers,
>> Victor
>>
>
>
>
> Django has a NullBooleanField that allows 3 states, Unknown (null), True, 
> False.
>
>  
>

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.




Design for storing likes/dislikes?

2013-07-16 Thread Victor Hooi
Hi,

We have a list of users, who are going to like/dislike various widgets.

My question is regarding how to store the like/dislikes.

Essentially, there can be three states between a user and a widget - like, 
dislike, and unrated, so it's not just a straight Boolean.

I'm thinking of just doing a M2M between user and widgets models, and then 
storing an extra field on that M2M.

I can either store a Boolean, for whether the item is liked/unliked - and 
then an unrated item simply won't be exist in the table.

Or I can store a integer (with a choice tupled defined), with say 
0=unrated, 1=like, 2 = unlike, and all possible combinations are listed.

We'll be doing queries to compare users, and see if their likes/dislikes 
intersect.

Are there any pros/cons of the two approaches for this given query, or is 
there perhaps a more efficient way of storing this data?

Cheers,
Victor

-- 
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.
For more options, visit https://groups.google.com/groups/opt_out.




Store arbitrary key-value pairs in model?

2013-04-29 Thread Victor Hooi
Hi,

I have a Django application that will need to store arbitraty

Basically, there are a series of "job scripts" that are submitted by users 
and then run.

Each of these jobs scripts may have an arbitrary number of key-value pairs 
attached to them (for example, output directory, or search term, or email 
address etc.).

There variables are then used by each script. The set of variables varies 
for each job script.

Is there an easy way to model this within Django?

We could store a serialised dict as a blob, but that sounds rather hackish.

I was thinking a document database (e.g. MongoDB, or Couch DB) might be 
more suitable, however, I'd like to keep it within Django, if possible 
(Django and relational DBs are widely used where I am, and there's good 
support for them).

Cheers,
Victor

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




Deployment best practices - reasons?

2013-04-29 Thread Victor Hooi
Hi,

I'm currently looking at tidying up deployment for a Django app we use 
internally.

There's a couple of things that I know are best-practices, or it's just how 
I normally deploy Django apps, but I need to come up with strong cases for 
all of them. As in any organisation, if it ain't broke, don't fix it - so 
there needs to be a compelling argument from me to put them in place.

For example:

Why use Gunicorn? (versus just Apache)
Gunicorn is lightweight, uses less memory, and is easier to configure. 
Anything else?

Why use Apache/Nginx in front of Gunicorn? (versus just hitting Gunicorn on 
it's own)
Gunicorn isn't designed to be front-facing - so for example, it doesn't 
handle slow clients well. Ideally you'd want something like Nginx or Apache 
to buffer requests. Anything else?

Why use Supervisord (versus just init.d scripts with say ./manage.py 
run_gunicorn in there)?
Supervisord will restart crashed processes. Anything else?

Why use Sentry?
Allows easier viewing of errors. Anything else?

Cheers,
Victor

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




Using django-devserver with Werzbeug to debug an app - interactive debugger not being trigged?

2013-03-14 Thread Victor Hooi
Hi,

I'm trying to use django-devserver 
(https://github.com/dcramer/django-devserver) to debug localshop 
(https://github.com/mvantellingen/localshop), a Django-based Pypi server.

I've installed django-devserver and werzbeug.

I then added 'devserver' to INSTALLED_APPS, and have started it up:

(temp)Victors-MacBook-Air:code victorhooi$ localshop runserver --werkzeug
> Validating models...
> 0 errors found
> Django version 1.4.3, using settings 'localshop.settings'
> Running django-devserver 0.4.0
> Threaded werkzeug server is running at http://127.0.0.1:8000/
> Quit the server with CONTROL-C.
>  * Running on http://127.0.0.1:8000/


I then try to access the view that triggers a 500 Internal Server Error (in 
this case from a file being in the wrong location).

On the console, I can see:

127.0.0.1 - - [14/Mar/2013 20:31:00] "GET /simple/yolk/ HTTP/1.1" 401 -
> 127.0.0.1 - - [14/Mar/2013 20:31:03] "GET /simple/yolk/ HTTP/1.1" 401 -
> 127.0.0.1 - - [14/Mar/2013 20:31:04] "GET /simple/yolk/ HTTP/1.1" 200 -
> Internal Server Error: /packages/yolk/download/1/yolk-0.4.3.tar.gz
> Traceback (most recent call last):
>   File 
> "/Users/victorhooi/.venvs/temp/lib/python2.7/site-packages/Django-1.4.3-py2.7.egg/django/core/handlers/base.py",
>  
> line 111, in get_response
> response = callback(request, *callback_args, **callback_kwargs)
>   File 
> "/Users/victorhooi/.venvs/temp/lib/python2.7/site-packages/localshop-0.4.1-py2.7.egg/localshop/apps/packages/views.py",
>  
> line 171, in download_file
> logger.info(release_file.distribution.file)
>   File 
> "/Users/victorhooi/.venvs/temp/lib/python2.7/site-packages/Django-1.4.3-py2.7.egg/django/db/models/fields/files.py",
>  
> line 46, in _get_file
> self._file = self.storage.open(self.name, 'rb')
>   File 
> "/Users/victorhooi/.venvs/temp/lib/python2.7/site-packages/Django-1.4.3-py2.7.egg/django/core/files/storage.py",
>  
> line 33, in open
> return self._open(name, mode)
>   File 
> "/Users/victorhooi/.venvs/temp/lib/python2.7/site-packages/Django-1.4.3-py2.7.egg/django/core/files/storage.py",
>  
> line 156, in _open
> return File(open(self.path(name), mode))
> IOError: [Errno 2] No such file or directory: 
> u'/Users/victorhooi/code/source/y/yolk/yolk-0.4.3.tar.gz'
> 127.0.0.1 - - [14/Mar/2013 20:31:04] "GET 
> /packages/yolk/download/1/yolk-0.4.3.tar.gz HTTP/1.1" 500 -


However, I don't seem to get any interactive prompt, or a debugger, or 
anything?

The server just keeps going, ready to receive the next request. Is 
something stopping the debugger from triggering here?

Cheers,
Victor 

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




Storing versioned maps of application connections?

2013-03-02 Thread Victor Hooi
Hi,

We have a legacy Django application that parses configuration files for 
several in-house applications, builds up a map of those applications, 
including any network connections between them (based on IP address and 
port), then stores them in Django models.

Each application object will store several things, such as a process name 
(which is unique), the application binary and version, as well as any 
network connections (listening or connecting).

For simplicity (I'm assuming), each day they blow away the existing model 
instances, then reparse all the configuration, and build up a new map with 
new model instances.

I'm looking at using similar to django-reversion to add version control to 
this application (It probably will be django-reversion - I'm not aware of 
any viable alternatives to django-reversion).

Now, obviously, the current blowing away approach isn't going to work with 
Django-reversion.

However, say we do a re-parse, what's the best way of integrating 
django-reversion into the workflow?

I assume we'd need some way of linking an existing application model with 
the new one from each daily re-parse.

We could use the process name (which is unique), do a lookup to see if that 
process name already exists, get it if it does, write our new values to the 
model, then save it.

My understanding is that django-reversion will only pickup on the changed 
fields.

We'd need to do a lookup on every single application and a save though - 
there's probably a smarter way to bulk these? (I know there's bulk create 
in Django, I'm not aware of any bulk updates?).

Are there any performance considerations we should be wary of? (There are 
probably between 100-200 applications).

Cheers,
Victor

-- 
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: Model method versus overriding save()

2012-12-09 Thread Victor Hooi
Hi,

Hmm, so are we saying that:

   - Using model methods uses less storage, but performs worse.
   - Overriding the model's save() method uses more storage, but performs 
   better.

I understand the storage part - but I'm a bit confused about the 
performance part - how does one perform better than the other?

Also - in terms of using them with QuerySets - there aren't any workarounds 
to use model methods with QuerySets are there? It seems like that would be 
a definite argument in favour of using the second method, right?

Finally - thanks for the tip about signals() - so should I be using 
something like django.db.models.signals.post_save in addition to overriding 
save(), or instead of it?

Cheers,
Victor

On Monday, 10 December 2012 10:49:22 UTC+11, Chris Cogdon wrote:
>
> Even though I'm a total database junkie (and where by that I mean 
> postgresql > mysql :) ), I have to agree with Mike. If you can keep it in 
> the model layer, do that. Once you start putting optimisations into the 
> database layer, you lose a lot of portability between databases: there is 
> no such thing as "standard SQL" for anything other than toy applications. 
> Optimisation tend to be very engine-specific.
>
> However, just remember that those optimisations are possible, and the 
> database is far more reliable for maintaining your invariants than the 
> client is.
>
>
>
> On Sunday, December 9, 2012 3:30:01 AM UTC-8, Mike Dewhirst wrote:
>>
>>
>>
>> For the sake of maintainability it might be better to keep all database 
>> manipulation in the model layer rather than split it betweem models and 
>> database. 
>>
>>
>>
>> and, well, that code is part of the 
>> > code base too. 
>>
>> Which means you need to keep pretty comprehensive documentation if you 
>> are doing database stuff in two areas. 
>>
>> Personally, I'd keep it all in the django ORM until the project is 
>> mature and requires the final molecule of optimisation. 
>>
>> Mike 
>>
>> > 
>> >- Tom 
>> > 
>> >> 
>> >> Derek 
>> >> 
>> >> [1] https://docs.djangoproject.com/en/dev/topics/signals/ 
>> >> 
>> >> On Saturday, 8 December 2012 04:27:50 UTC+2, Chris Cogdon wrote: 
>> >> 
>> >> It's a simple performance vs storage question. 
>> >> 
>> >> Storing a calculatable field also risks it getting out of sync 
>> >> with reality, but if you're doing the query on that _so_ much, 
>> >> then its usualyl worth it. 
>> >> 
>> >> Also, with the right database and a trigger, that's something the 
>> >> database can ensure for you. Ie, a field that the database updates 
>> >> for you. 
>> >> 
>> >> 
>> >> On Friday, December 7, 2012 5:54:37 PM UTC-8, Victor Hooi wrote: 
>> >> 
>> >> Hi, 
>> >> 
>> >> I have a "ranking" field for an item that returns an integer 
>> >> between 1 to 10 based on a number of criteria of each item. 
>> >> 
>> >> My question is - what are the pros and cons of using a model 
>> >> method to return this, versus overriding the save() method and 
>> >> saving it directly into a normal IntegerField on that item? 
>> >> 
>> >> I understand that model methods *won't* let me use them within 
>> >> QuerySet filters on that item - is there any way around that? 
>> >> 
>> >> If I just override the model's save() method to get it 
>> >> recalculate and save that field each time, I can use it within 
>> >> QuerySet filters. Any cons with that approach? 
>> >> 
>> >> What do you guys tend to use in your projects? 
>> >> 
>> >> Cheers, 
>> >> Victor 
>> >> 
>> >> -- 
>> >> 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/-/G7fp5OLkapgJ. 
>> >> 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. 
>

Model method versus overriding save()

2012-12-07 Thread Victor Hooi
Hi,

I have a "ranking" field for an item that returns an integer between 1 to 
10 based on a number of criteria of each item.

My question is - what are the pros and cons of using a model method to 
return this, versus overriding the save() method and saving it directly 
into a normal IntegerField on that item?

I understand that model methods *won't* let me use them within QuerySet 
filters on that item - is there any way around that?

If I just override the model's save() method to get it recalculate and save 
that field each time, I can use it within QuerySet filters. Any cons with 
that approach?

What do you guys tend to use in your projects?

Cheers,
Victor

-- 
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/-/rpb_ZNSMS_8J.
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: Python-requests seems to 404 with Django/Tasty-pie?

2012-10-02 Thread Victor Hooi
heya,

Thanks for the tips - you're probably right, I might need to whip out 
wireshark or something and see what exactly is going on.

However, one thing I did notice - I normally have the http_proxy 
environment variable set, as we use a HTTP proxy at work.

However, if I unset the http_proxy variable, Python requests suddenly seems 
to start working again.

I tried to set the no_proxy variable, and put in localhost and 127.0.0.1 in 
there - however, Python requests doesn't seem to respect that?

Cheers,
Victor

On Tuesday, 2 October 2012 22:48:26 UTC+10, Cal Leeming [Simplicity Media 
Ltd] wrote:
>
> Hi Victor,
>
> I've had my fair share of exposure with python requests - so thought I'd 
> chime in.
>
> On first glance, this looks to be an issue with specifying the port number 
> into python-requests, doing so seems to send the entire "
> http://localhost:8000/api/v1/host/?name__regex==json; as the 
> request. However, further analysis shows that might not be the case.
>
> Looking at the python requests code;
> https://github.com/kennethreitz/requests/blob/develop/requests/models.py
>
> >>> urlparse.urlparse("http://localhost:8080/test/url?with=params;)
> ParseResult(scheme='http', netloc='localhost:8080', path='/test/url', 
> params='', query='with=params', fragment='')
>
> It then sends this directly into urllib3 using connection_from_url();
> https://github.com/shazow/urllib3/blob/master/urllib3/connectionpool.py
>
> This then calls the following;
> scheme, host, port = get_host(url)
> if scheme == 'https':
> return HTTPSConnectionPool(host, port=port, **kw)
> else:
> return HTTPConnectionPool(host, port=port, **kw)
>
> get_host -> parse_url()
> https://github.com/shazow/urllib3/blob/master/urllib3/util.py
>
> Tracing through urllib3 finally gets to parse_url();
>
> >>> urllib3.util.parse_url("http://localhost:8080/test/url?with=params;)
> Url(scheme='http', auth=None, host='localhost', port=8080, 
> path='/test/url', query='with=params', fragment=None)
>
> So, lets look at path_url() instead;
> https://github.com/kennethreitz/requests/blob/develop/requests/models.py
>
> >>> lol = requests.get("
> http://localhost:8000/api/v1/host/?name__regex==json;)
> >>> lol.request.path_url
> '/api/v1/host/?name__regex==json'
>
> Performing a test connection shows;
>
>  foxx@test01.internal [~] > nc -p8000 -l
> GET /api/v1/host/?name__regex==json HTTP/1.1
> Host: localhost:8000
> Accept-Encoding: identity, deflate, compress, gzip
> Accept: */*
> User-Agent: python-requests/0.11.1
>
> So, from what I can tell, python requests is functioning normally.
>
> Personally, I'd say get wireshark running, or use the nc trick shown 
> above, perform 1 request using curl and 1 using python requests, then 
> compare the request headers.
>
> Can't throw much more time at this, but hope the above helps
>
> Cal
>
> On Tue, Oct 2, 2012 at 8:54 AM, Victor Hooi <victo...@gmail.com
> > wrote:
>
>> Hi,
>>
>> I have a Django app that's serving up a RESTful API using tasty-pie.
>>
>> I'm using Django's development runserver to test.
>>
>> When I access it via a browser it works fine, and using Curl also works 
>> fine:
>>
>> curl 
>> "http://localhost:8000/api/v1/host/?name__regex=format=json<http://localhost:8000/api/v1/host/?name__regex==json>
>>> "
>>
>>
>> On the console with runserver, I see:
>>
>> [02/Oct/2012 17:24:20] "GET /api/v1/host/?name__regex=format=json 
>>> HTTP/1.1" 200 2845
>>
>>
>> However, when I try to use the Python requests module (
>> http://docs.python-requests.org/en/latest/), I get a 404:
>>
>> >>> r = requests.get('
>>> http://localhost:8000/api/v1/host/?name__regex==json')
>>> >>> r
>>> 
>>
>>
>> or:
>>
>> >>> r = requests.get('
>>> http://localhost:8000/api/v1/host/?name__regex=format=json<http://localhost:8000/api/v1/host/?name__regex==json>
>>> ')
>>> >>> r
>>> 
>>
>>
>> or: 
>>
>> >>> payload = { 'format': 'json'}
>>> >>> r = requests.get('http://localhost:8000/api/v1', params=payload)
>>> >>> r
>>> 
>>> >>> r.url
>>> u'http://localhost:8000/api/v1?format=json'
>>
>>
>> Also, on the Django runserver console, I see:
>>
>> [02/Oct/2012 17:25:01] "GET 
>>> http://localhost:8000/api/v1/host/?name__regex==json HTTP/1.1" 
>>> 404 161072
>

Python-requests seems to 404 with Django/Tasty-pie?

2012-10-02 Thread Victor Hooi
Hi,

I have a Django app that's serving up a RESTful API using tasty-pie.

I'm using Django's development runserver to test.

When I access it via a browser it works fine, and using Curl also works 
fine:

curl "http://localhost:8000/api/v1/host/?name__regex=format=json;


On the console with runserver, I see:

[02/Oct/2012 17:24:20] "GET /api/v1/host/?name__regex=format=json 
> HTTP/1.1" 200 2845


However, when I try to use the Python requests module 
(http://docs.python-requests.org/en/latest/), I get a 404:

>>> r = 
> requests.get('http://localhost:8000/api/v1/host/?name__regex==json')
> >>> r
> 


or:

>>> r = 
> requests.get('http://localhost:8000/api/v1/host/?name__regex=format=json')
> >>> r
> 


or: 

>>> payload = { 'format': 'json'}
> >>> r = requests.get('http://localhost:8000/api/v1', params=payload)
> >>> r
> 
> >>> r.url
> u'http://localhost:8000/api/v1?format=json'


Also, on the Django runserver console, I see:

[02/Oct/2012 17:25:01] "GET 
> http://localhost:8000/api/v1/host/?name__regex==json HTTP/1.1" 404 
> 161072


For some reason, when I use requests, runserver prints out the whole 
request URL, including localhost - but when I use the browser, or curl, it 
only prints out the part *after* the hostname:port

I'm assuming this is something to do with the encoding, user-agent or 
request type it's sending? Why does runserver print out different URLs for 
requests versus browser/curl?

Cheers, 
Victor

-- 
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/-/ycLjP71ciAEJ.
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.



Bulk Creating Django Models from CSV File?

2012-04-01 Thread Victor Hooi
Hi,

I have several large CSV files that I'm hoping to parse, and use to create 
Django objects. Each line looks might look something like this:

"Server Hostname", "Classification", "Country", "Operating System"

"foo.bar.com", "Prod", "Australia", "Solaris"

"alex.john.com", "Dev", "UK", "Linux"

"bob.hope.com", "UAT, "Japan", "Windows


For performance reasons, it would be nice to use something like 1.4's 
bulk_create:

https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.bulk_create
 

However, I noticed the caveat about it not populating the auto-incrementing 
PK field. What's the recommended way to populate the PK field then? How do 
you use it?

Secondly, the models will have FK relationships to other models (for 
instance, Classification, Country and Operating System would be stored in a 
lookup table). What's the best way to look these up, and assign the 
appropriate FK, whilst still preserving good performance and using bulk 
inserts?

Cheers,
Victor

-- 
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/-/bP0RG4NXJjEJ.
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: Anyone want to take over maintaining Instant Django?

2012-02-26 Thread Victor Hooi
Hi,

Whatever happened to this?

@sidmitra - did you manage to take over maintainership of this project?

If not, @cjl - do you still have the scripts for this?

Cheers,
Victor

On Thursday, 15 July 2010 23:25:44 UTC+10, sidmitra wrote:
>
>
> I would be willing to take it on or we can also do it as a community 
> effort? 
> Instant Django is how i got started into web dev and now i'm a full 
> time django freelancer so would love to give some love back. 
>
> -Sid 
> http://sidmitra.com 
>
>

-- 
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/-/m3dY94ta3OgJ.
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.



Highlighting Active Navigation Link - correct approach?

2012-01-08 Thread Victor Hooi
hi,

I have a project where I'm using Bootstrap 
(www.github.com/twitter/bootstrap) with Django.

I need to add a CSS class ("active") to highlight the active navigation 
link.

Anyhow, I did some Googling:

http://www.turnkeylinux.org/blog/django-navbar
http://ilostmynotes.blogspot.com/2010/03/django-current-active-page-highlighting.html
http://gnuvince.wordpress.com/2007/09/14/a-django-template-tag-for-the-current-active-page/
http://stackoverflow.com/questions/340888/navigation-in-django
http://djangosnippets.org/snippets/1726/
http://stackoverflow.com/questions/7665514/django-highlight-navigation-based-on-current-page

The approach in the above seems to be to either use custom template tag, 
middleware or JS-hackery.

Is there a current consensus in the Django community in terms of what is 
the "correct" approach for this?

Is there a reason something like this isn't part of Django core, or an 
in-built templatetag?

Cheers,
Victor

-- 
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/-/Xx5Rk_rBuxIJ.
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.



Using STATIC_URL in CSS/JS files?

2012-01-02 Thread Victor Hooi
Hi,

In Django, you can use {{ STATIC_URL }} in your HTML templates to point to 
the correct path for static files, however I'm wondering if there's any way 
to use it inside of CSS/JS files?

E.g. I have a CSS file that points to a PNG sprite, and I'd like a way to 
get it to point to {{ STATIC_URL}} without hardcoding the URL/path - any 
way?

Cheers,
Victor

-- 
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/-/24ML6hwMPCAJ.
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 Forms and Twitter Bootstrap - Add fieldset, div wrapper and CSS labels to Django Forms?

2011-12-11 Thread Victor Hooi
Hi,

I'm attempting to use Django forms with Twitter's CSS library Bootstrap 
(http://twitter.github.com/bootstrap/):

The default form outputted by {{ form.as_p }} doesn't seem to be enough to 
be formatted nicely with Bootstrap.

You need to add a , as well as class="control-label" to each 
.

So for example, to output a single text field:


Text input


Help text here. Be sure to fill this out 
like so, or else!



Is there a way to easily get Django's form handling to produce a form like 
this? (I'd like to avoid hardcoding every form field in my template if 
possible).

Cheers,
Victor

-- 
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/-/BClad_qCrnEJ.
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: Bulk import of data

2011-12-05 Thread Victor Hooi
heya,

Hmm, I was previously under the impression that for these sorts of things 
(importing and instantiating models from CSV), the recommended way to 
create a ModelForm, and pass each line of the CSV through that, and have 
that handle model validation for you.

In our case, we have a CSV file, but quite a few of those lines are 
probably invalid/erroneous - we need to provide useful messages on those, 
and import the rest of the file.

Is the recommended way now to use bulk_create 
(https://docs.djangoproject.com/en/dev/ref/models/querysets/#bulk-create), 
process all the lines, and hit that in one call?

How would you handle invalid lines or validation errors for individual rows?

Cheers,
Victor

-- 
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/-/qYfAZWsydQoJ.
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

2011-12-02 Thread Victor Hooi
Hi,

The XML files are all configuration files, storing things like boolean 
configuration flags, timeout values, username/passwords, IP addresses and 
ports etc.

Some of them will maps somewhat logically to the relational model - for 
example, they'll be a configuration for an application, as well as each of 
it's sub-modules, as well as usernames/passwords linked to the application 
etc.

I've included three example XSD files - hopefully that will give you a 
better idea.

The reason we're using Django is I was hoping to leverage off the 
Django-admin, as well as Django forms, if need be, to provide an easy 
interface to edit the files, and enforce some validation rules (many of 
which aren't really contained in the XML/XSD files).

And the other issue is the configuration format may change over time, so 
we'll need to keep the models.py up-to-date, not sure of the best way to do 
that.

Cheers,
Victor

-- 
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/-/s3td-Oy5jG8J.
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.



CConfigRefData.xsd
Description: Binary data


CConfigFIXAA.xsd
Description: Binary data


CConfigXXX.xsd
Description: Binary data


Re: Django

2011-12-01 Thread Victor Hooi
heya,

Damn, I didn't edit the subject - apologies - if there's a moderator, can 
you change it to "Using Django to edit XML configuration files" please?

Thanks,
Victor

-- 
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/-/_7FYPrf30k0J.
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

2011-12-01 Thread Victor Hooi
Hi,

I'm writing a  Django application to mange some XML configuration files 
through the Django-admin.

Currently, I'm converting the XML values/hierarchies into Django models.

After this, we also need to code an import - to import in configuration 
files and populate Django models based on them, and also an export, to 
export from our Django models back into the finished XML configuration 
files.

However, another way might be just to inspect the XSD files we have, and 
try to create the models from that.

I know there's django-models-schemas 
(https://bitbucket.org/eegg/django-model-schemas/wiki/Home), that is meant 
to generate XSD files from Django models. I'm not aware of anything going 
the other way (introspecting XSD files to get Django models).

However, what are your thoughts on this?

Is there an easier way of achieving the main goal - editing XMl 
configuration files through a Django interface? Things I should be aware of?

Cheers,
Victor

-- 
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/-/iWVmPfYsrOQJ.
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: Changes to default project layout?

2011-11-08 Thread Victor Hooi
heya,

Also, I noticed that there's no models.py file in the first app that 
startproject 
creates - I assume this is by design, right?

Hmm, what's the rationale behind it?

Cheers,
Victor

-- 
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/-/nRLeLBLsde0J.
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.



Changes to default project layout?

2011-11-08 Thread Victor Hooi
heya,

*NB: Not sure if this belongs in dev or general, but I'm assuming here - 
please let me know if I'm wrong.*

I just noticed there was a change made to startproject/startapp, and the 
default Django layout in trunk (yes, I'm a bit behind the curve...haha).

https://code.djangoproject.com/changeset/16964
https://docs.djangoproject.com/en/dev/releases/1.4/#updated-default-project-layout-and-manage-py

Just a couple quick questions:

   1. Previously, we'd put the app name in INSTALLED_APPS in settings.py - 
   however, since settings.py now lives inside one of the Django apps, I 
   assume we don't need to put that app itself under INSTALLED_APPS? But we 
   should put any other apps in there, right?
   2. ./manage.py is setup with a default DJANGO_SETTINGS_MODULE - however, 
   what's the recommended practice if we want multiple settings.py files? 
   (e.g. development, testing and production environments). And I assume 
   having any other settings.py in other apps is a bad practice?
   3. I noticed there's a new wsgi.py file - anything we should be aware of 
   here? I suppose projects like gunicorn, django_extensions etc. will have to 
   be adapted to be aware of the changes? 

Cheers,
Victor

-- 
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/-/KW9CF_D0axoJ.
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.



Storing regex raw string literal in Django model?

2011-10-13 Thread Victor Hooi
Hi,

I have Django model and in one of the fields I need to store a regex string 
that I can later use.

class Foo(models.Model):
name = models.CharField(max_length=30, unique=True)
regex_string = models.TextField()


So for example, the regex_string field might be set to:

r'\d{2}'


I then try to retrieve this later, compile it as a regex expression and use 
it - however, it doesn't seem to work as planned:

>>> pattern = re.compile(ham.regex_string)
>>> print(pattern.match("22"))
None


Obviously if I pass the raw string literal in directly, it works fine:

>>> pattern = re.compile(r'\d{2}')
>>> pattern.match("22")
<_sre.SRE_Match object at 0x1505100>


If I actually print ham.regex_string, it returns:

u"r'\\d{2}'"


So it's a unicode string, but for some reason the backslashes are 
doubled-up?

What I actually need is a way to store a regex raw string literal, so that I 
can retrieve it later and use it in a regex.

Is there a better way of doing this?

Cheers,
Victor

-- 
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/-/k7i1EJD2fVwJ.
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 Victor Hooi
heya,

I might be misunderstanding your requriements, but could you use the 
@user_passes_test decorator with a has_perm check?

@user_passes_test(lambda u: u.has_perm('private_pages.foo'))

https://docs.djangoproject.com/en/dev/topics/auth/

You can probably make the lambda a bit smarter, instead of using has_perm, 
check if the pagename matches the username.

Cheers,
Victor

-- 
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/-/CxrZ-hFFD9QJ.
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.



Permission_require decorator, and redirecting to Login Page

2011-10-05 Thread Victor Hooi
heya,

I'm using the permission-required decorator with the inbuilt login view.

When I login as a user who has the appropriate permissions, it logs in fine, 
and all is good.

When I try to login as a user with valid credentials but lacking the 
appropriate permission, it simply keeps redirecting to the login page again 
- but doesn't display any error message at all.

I tried adding "{{ form.non_field_errors }}" to the form but it still 
doesn't display any error messages.

Is there any way to get it to display that your user lacks the appropriate 
permissions, as opposed to just redirecting to a blank login page again and 
again.

Cheers,
Victor

-- 
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/-/alIHHeQMVb4J.
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.



TemplateView compatible with permission_required decorator?

2011-10-05 Thread Victor Hooi
Hi,

I'm attempting to use one of the new class-based TemplateView with the 
permission_required decorator:

@permission_required('foo.count_peas')
class Pea(TemplateView):
template_name = "pea.html"

However, when I do that, I get an error:

Exception Type: AttributeError at /someurl/
Exception Value: 'function' object has no attribute 'as_view'


If I comment out the permission_required decorator, the view seems to work 
fine.

Are the new class-based views compatible with the permission_required 
decorator?

Or is there something I need to do to make them work together.

Cheers,
Victor

-- 
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/-/BLrtdUAyciYJ.
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: Import CSV to create multiple Models - Model Manager or in View?

2011-10-03 Thread Victor Hooi
heya,

@Shawn: Hmm, that looks like quite an interesting approach - so the 
ModelForm would handle the validation logic? =) Me likes! Haha.

I can parse the CSV and get the field names to match up (or just do a simple 
transform to get them to match).

However, how do I then pass this information into a ModelForm? Also, the CSV 
file is for creating multiple models - one model per CSV line - how will 
that work with a single ModelForm? Do I just call it repeatedly?

And how will I then capture the ValidationError and get them back in my 
form?

Cheers,
Victor

-- 
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/-/wT8cDUDW62IJ.
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.



Import CSV to create multiple Models - Model Manager or in View?

2011-10-03 Thread Victor Hooi
heya,

I'm coding up a Django form which will let the user upload a CSV file, then 
create and save multiple Model instances for each row in the CSV file.

At the moment, I'm trying to decide where to put the code that parses the 
CSV file and creates/saves the models.

I don't think it'd be an instance method on the Model itself, since that's 
for working on individual instances, and you'd need to pass a valid instance 
to the method.

Would it go in a custom Model Manager? Or should I have this logic in the 
View itself?

Also, I need to figure out a good way of passing ValidationErrors from the 
model.save() and passing them back to the view to display the user.

What would be a good way of hooking that up?

Cheers,
Victor

-- 
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/-/CiJuzj-Sh3wJ.
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 render() with Form?

2011-10-03 Thread Victor Hooi
heya,

Aha, thanks guys. I can confirm that works fine now.

That'll teach me to read the API docs a bit better...lol, I just assumed it 
was a 1-to-1 swap with render_to_response, didn't check the arguments =).

Cheers,
Victor

-- 
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/-/KYwa7jhg6IsJ.
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.



Using render() with Form?

2011-10-03 Thread Victor Hooi
heya,

I was previously using the following to render a form:

from django.shortcuts import render_to_response, RequestContext
...
def upload_file(request):
...
return render_to_response('upload_form.html', {'form': form}, 
context_instance=RequestContext(request))

I can confirm that this works fine, form was rendered perfectly fine.

However, I read that render() is now the bee-knees...lol 
(http://stackoverflow.com/questions/5154358/django-what-is-the-difference-between-render-render-to-response-and-direct),
 
so I thought I'd switch to that:

from django.shortcuts import render
...
def upload_file(request):
...
return render('upload_form.html', {'form': form})


However, when I try to do that, I get an error:

Environment:


Request Method: GET
Request URL: http://localhost:8000/upload/

Django Version: 1.4 pre-alpha SVN-16922
Python Version: 2.7.1
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'django.contrib.admindocs',
 'card']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File 
"/Users/victorhooi/.virtualenvs/appname/src/django/django/core/handlers/base.py"
 
in get_response
  111. response = callback(request, *callback_args, 
**callback_kwargs)
File "/Users/victorhooi/djangoProjects/appname/card/views.py" in upload_file
  18. return render('upload_form.html', {'form': form})
File 
"/Users/victorhooi/.virtualenvs/appname/src/django/django/shortcuts/__init__.py"
 
in render
  40. context_instance = RequestContext(request, 
current_app=current_app)
File 
"/Users/victorhooi/.virtualenvs/appname/src/django/django/template/context.py" 
in __init__
  172. self.update(processor(request))
File 
"/Users/victorhooi/.virtualenvs/appname/src/django/django/core/context_processors.py"
 
in debug
  35. if settings.DEBUG and request.META.get('REMOTE_ADDR') in 
settings.INTERNAL_IPS:

Exception Type: AttributeError at /upload/
Exception Value: 'str' object has no attribute 'META'


Any idea from the above why this might be happening?

Thanks,
Victor

-- 
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/-/f0sywLsLB28J.
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: View decorator for common navigation elements?

2011-10-02 Thread Victor Hooi
heya,

This SO post seems to suggest that data and template tags shouldn't mix...

http://stackoverflow.com/questions/5046046/where-put-database-interaction-in-django-templatetags

Not sure how I feel about that myself - I see the philosophical argument 
behind it, but I don't see another more efficiently creating common page 
elements (like my category dropdowns).

Also, if you look at James Bennett's posts here:

http://www.b-list.org/weblog/2006/jun/07/django-tips-write-better-template-tags/

His code actually *does* interact with the database, as does the blog post 
here 
(http://www.webmonkey.com/2010/02/use_templates_in_django/#Roll_your_own_template_tags).

Also, as an aside, each link on our category dropdown is bound to a JS click 
event - not sure how this would tie in with the custom template tag - 
separate tag for that part of it?

Cheers,
Victor

-- 
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/-/9cYeQwELEYsJ.
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.



__unicode__ and u'%s'?

2011-10-01 Thread Victor Hooi
heya,

What's the recommended best practice for printing model fields in 
__unicode__?

Currently, I'm using (simply because the Django docs do):

def __unicode__(self):
return u'%s' % (self.name)

What's the rationale behind using the unicode literal u'%s'? Is it always 
needed, versus just return self.name?

And should I be using .format() instead? Or using something else?

Cheers,
Victor

-- 
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/-/T1ENoBx4HooJ.
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: View decorator for common navigation elements?

2011-09-30 Thread Victor Hooi
heya,

I do like the idea of just including a custom template tag =).

Hmm, can custom template tags interact with models or query the database 
like that?

Firstly, Is it possible, and secondly, is it considered good practice? 

Cheers,
Victor

-- 
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/-/ScSr2-kGquYJ.
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: set_test_cookie() on every page?

2011-09-30 Thread Victor Hooi
heya,

John - thanks for the reply.

In this case, it's an JQuery .post() call linked to a dropdown menu 
(https://groups.google.com/d/topic/django-users/tw0lM-QkdGw/discussion).

The dropdown is a common navigation element on every page. It's used to set 
a session variable that stores which object a user is working on at the 
moment (see attached screenshot).

In my webpage:

  $('#dropdown_choice').click(function() {

$.post("/set_conference", {"current_conference": "conference_name"}, 
function(data) {alert(data)});

});


Then in my view:

# TODO: Set test cookies (although if we're logged in, we can assume cookies 
works)

def set_current_conference(request):

if not request.is_ajax() or not request.method == 'POST':

return HttpResponseNotAllowed(['POST'])
request.session['current_conference'] = 
request.POST.get("current_conference")
return HttpResponse('Set current_conference to ' + 
str(request.POST.get("current_conference")))

 
So it seems I would need to put the set_test_cookie() logic on every page, 
since they could make this call from any page with the dropdown. Or is there 
another way?

How would people normally handle having an AJAX POST call like this to set a 
session variable?

Or should I just (dangerously) assume that cookies will work automatically? 
Alternative?

Cheers,
Victor

-- 
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/-/OnnKcnL2oD0J.
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.

<>

View decorator for common navigation elements?

2011-09-29 Thread Victor Hooi
Hi,

We have a common navigation bar on nearly every page (view) that contains a 
dropdown - this dropdown is populated with items from a database table. This 
dropdown also has AJAX behaviour attached to it.

I'm thinking I can create a decorator that will retrieve the list from the 
database, and return a Python list

We can then wrap every single view in this decorator, and then pass the list 
to the template for rendering.

Firstly - is there a more elegant alternative, rather than wrapping every 
single view in this decorator? (Middleware? Or is that a poor fit here? 
Anything else?).

And secondly - are there are any performance issues here? We're making 
database calls with every single view, just to get a list for a navigation 
dropdown. Smarter way?

I know I can use the caching middleware to cache entire pages, or even 
template fragments - but how about caching a single list() like this? What 
are other methods people are using to tackle this?

Cheers,
Victor

-- 
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/-/8cKewo2DudcJ.
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.



set_test_cookie() on every page?

2011-09-29 Thread Victor Hooi
Hi,

I've read the Django docs on setting test cookies 
(https://docs.djangoproject.com/en/dev/topics/http/sessions/#setting-test-cookies),
 
and I'm still a bit confused.

One of our views sets a session variable to remember the object a user is 
currently viewing (we figured it wasn't worth storing in the database for 
this).

Should I put set_test_cookie() on every view? That seems a bit 
silly/redundant.

However, if I only put it on the view that sets the session variable, 
doesn't that mean the user has to visit that page twice - once to set the 
cookie, and (since the if test will fail that first time) again to verify it 
was set? How will the user even know to do that?

Do people actually check for the test cookie these days, or do they just 
assume it's set?

But then if we call delete_test_cookie(), doesn't that mean we have to set 
it all over again if the user needs to sets thesession variable again? Or 
should we not call delete_test_cookie()

Cheers,
Victor

-- 
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/-/VZwP7behBtAJ.
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: Importing file to Models - Temporary store to allow confirming?

2011-06-28 Thread Victor Hooi


Shawn,

Thanks for the quick reply =).

If we go with the third approach, what advantages are there to persisting 
the models in MongoDB (or something similar like Redid.or Cassandra), as 
opposed to a traditional RDBMS? (I just want to get a good handle on the 
issues).

Furthermore, is there a particular reason you picked MongoDB over the other 
NoSQL solutions?

Also, in terms of actually persisting the temporary models to MongoDB, I can 
just use PyMongo and store the dicts themselves - and just user a nested 
dict to represent all the model instances from a given import file. Any 
issues with that approach?

Thanks for the tip about using asynchronous processing for the import file - 
I didn't think the file would be that big/complex to process, but I suppose 
it's probably the better approach to do it all asynchronously, instead of 
just hoping it won't grow larger I the future. In this case, I suppose I can 
just use Ajax on the page itself to check on the status of the queue?

Cheers,
Victor

-- 
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/-/CvCjWNrV4pUJ.
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: Importing file to Models - Temporary store to allow confirming?

2011-06-27 Thread Victor Hooi
Shawn,

Thanks for the quick reply =).

If we go with the third approach, what advantages are there to persisting
the models in MongoDB (or something similar like Redid.or Cassandra), as
opposed to a traditional RDBMS? (I just want to get a good handle on the
issues).

Furthermore, is there a particular reason you picked MongoDB over the other
NoSQL solutions?

Also, in terms of actually persisting the temporary models to MongoDB, I can
just use PyMongo and store the dicts themselves - and just user a nested
dict to represent all the model instances from a given import file. Any
issues with that approach?

Thanks for the tip about using asynchronous processing for the import file -
I didn't think the file would be that big/complex to process, but I suppose
it's probably the better approach to do it all asynchronously, instead of
just hoping it won't grow larger I the future. In this case, I suppose I can
just use Ajax on the page itself to check on the status of the queue?

Cheers,
Victor
On Mon, Jun 27, 2011 at 04:36, Shawn Milochik  wrote:

> If you're using Django 1.2 or higher you can take advantage of the
> multi-database support by adding the 'using' kwarg to your model.save().
> This will allow you to ensure that the model saves successfully (is valid)
> in the 'holding' database, and move it to your 'live' database later.
>
> You could add a field to the model indicating whether it's 'live' or
> 'pending,' load all the temp models as pending, then just flip the flag as
> each one is "approved." That would front-load all the processing.
>
> You can use a ModelForm to accept the CSV data (preferably in dict form,
> from csv.DictReader) to validate the data, then just check for is_valid()
> without saving anything to the database. You could then store those
> dictionaries somewhere (such as MongoDB) for retrieval when you actually
> want to save them to the database.
>
> Each of these options has different advantages. I don't know about
> performance. In any case, you may have to use asynchronous processing (via
> ZeroMQ or django-celery) so the page can refresh before you Web server's
> timeout.
>
> Use whichever seems best for your needs, and maybe someone else has another
> option. I'd prefer option #3, because it keeps all the temporary data out of
> your production database and makes good use of the validation properties of
> the ModelForm class.
>
>
>
> --
> 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+unsubscribe@**
> 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 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.



Importing file to Models - Temporary store to allow confirming?

2011-06-26 Thread Victor Hooi
heya,

We have a CSV file that we are importing into a Django application, and then 
creating the appropriate models and relationships.

At the first page, we have a file upload form where the user selects a file.

We then parse the file, and return a second page showing them what would be 
created, any validation errors etc.

The user can then decide whether to proceed or not (or possibly to correct 
any areas on-screen).

What would be the best way of storing the temporary interim models, before 
it actually hits the database proper?

The CSV file will be fairly big, possibly around 200 Kb in size, and create 
several hundred models.

Should I store this in the database somewhere, and label those models 
"temporary"? It seems a bit heavy just for a confirm, and I'm not sure if 
it's appropriate use of the database. Or is there some way we could store it 
in Django sessions? Or any other way to do it?

Cheers,
Victor

-- 
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/-/zBHlA9Q2t7MJ.
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.



Templatetag - using date and join together?

2011-02-10 Thread Victor Hooi
Hi,

I have a list of Python date objects that I'd like to format and string 
together.

I can use the join templatetag to string them together:

{{ date_sequence|join: ", " }}

And I can also use the date templatetag to format them:

{{ date_sequence|date:" M j" }}

However, I can't see to pipe one into the other - I get the errors:

TemplateSyntaxError: Could not parse the remainder: ': "M j"' from 
'date_sequence|join:", "|date: "M j"'

or

TemplateSyntaxError: Could not parse some characters: date_sequence|date|: 
"M j"||join:", "

(My actual code for that second error is {{ date_sequence|date: "M 
j"|join:", " }}, I'm not sure why it looks that way in the error message).

Now, obviously I can just use a for loop and the date templatetag, but the 
above is much more compact, and I would like to understand what's going on 
as well, or how to get it to work (assuming there is a way).

Thoughts?

Thanks,
Victor

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



Configuration for Nginx and staticfiles

2011-01-31 Thread Victor Hooi
Hi,

I'm using Django 1.3 and the included staticfiles app to handle my static 
media, and Nginx as the webserver.

It's currently working, but I have a feeling my paths are more complex than 
they need to be. I was wondering if anybody could perhaps point out a better 
way to config this, or any improvements to the following.

My settings.py:

# Absolute path to the directory that holds static files.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = '/sites/example.com/static_media/static' 

# URL that handles the static files served from STATIC_ROOT.
# Example: "http://media.lawrence.com/static/;
STATIC_URL = '/static/' 

# URL prefix for admin media -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/;, "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/' 

# A list of locations of additional static files
STATICFILES_DIRS = ()

My /etc/nginx/sites-available/example.com file:

server {
  listen 80;
  server_name www.example.com;
  rewrite ^/(.*) http://example.com/$1 permanent;
}
server {
  listen 80;
  server_name example.com;
  access_log /sites/example.com/logs/access.log;
  error_log /sites/example.com/logs/error.log;
  location /static {
root /sites/example.com/static_media;
  }
  location / {
proxy_pass http://127.0.0.1:8000;
  }
}

My static media is collected inside of 
/sites/example.com/static_media/static - I'm not sure why I need two layers 
of static directories, but I couldn't see a way around this (although 
I'm undoubtedly missing something obvious here).

Also, any recommended changes to Nginx config?

Cheers,
Victor

-- 
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 Admin - list_display doesn't follow FK links?

2011-01-29 Thread Victor Hooi
Hi,

I'm trying to use list_display in the django-admin, and I can't seem to find 
a way to get list_display to follow FK links.

My models.py:

class Site(models.Model):
name = models.CharField(max_length=50, unique=True)
description = models.TextField()

def __unicode__(self):
return u'%s' % (self.name) 

class AccommodationFeature(models.Model):
name = models.CharField(max_length=50, unique=True)
description = models.TextField() 

class AccommodationRoom(models.Model):
name = models.CharField(max_length=50)
site = models.ForeignKey(Site)
features = models.ManyToManyField(AccommodationFeature, null=True, 
blank=True)

def __unicode__(self):
return u'%s' % (self.name) 

class BedAvailability(models.Model):
number_of_single_beds = models.IntegerField()
number_of_double_beds = models.IntegerField()
conference = models.ForeignKey(Conference)
accommodation_room = models.ForeignKey(AccommodationRoom)

class Meta:
verbose_name_plural = 'bed availabilities'

def __unicode__(self):
return u'Availability for %s at %s' % (self.accommodation_room, 
self.conference)
# Surely this isredundant? hmm, list_dispaly doesn't seem to follow 
foreignkey relationships?
def site_name(self):
return u'%s' % (self.accommodation_room.site.name)

Each "Site" has multiple "AccommodationRooms", which in turn have 
"BedAvailabilities".

In the BedAvailabilitiesAdmin, for list_display, I'm trying to follow 
self.accommodation_room.site. This doesn't work using either dot notation or 
double-underscore notation.

Other ModelAdmin options seem to allow following FK links, using the double 
underscore notation.

E.g. ModelAdmin.search_fields allows you to search across FK's using:

search_fields = ['foreign_key__related_fieldname']


list_filter also seems to allow the same behaviour.
 
At the moment, I'm just using a function on BedAvailabilities to follow the 
relationships and print the site name. However, this seems a bit silly when 
logic would dictate that list_display behaves the same as search_fields and 
list_filter.
 
Is there any reason this feature doesn't work for list_display?

There's some discussion of it on SO:

http://stackoverflow.com/questions/163823/can-list-display-in-a-django-modeladmin-display-attributes-of-foreignkey-fields

And a ticket for it her:

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

but discussion seems to have petered off. Is there a technical or design 
reason for this?

Cheers,
Victor

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



ON DELETE CASCADE behaviour on M2M?

2011-01-17 Thread Victor Hooi
Hi,

I know that Django's default behaviour on ForeignKey is ON DELETE CASCADE 
(unless you set on_delete to PROTECT). However, I wasn't sure how this 
extended to ManyToManyFields.

I've just tested with one of my own applications - I have an "Article" 
object, with m2m to a "Journalist" object. Deleting either end of the m2m 
didn't affect the other end.

I assume this is intended behaviour - since it simply cascades to the 
invisible join table in the middle, but through to the other actual end of 
the relatinoship?

However, the issue I see with this is that if the m2m can't be empty (as is 
default). You delete one end, and everything seems fine and dandy. But then 
you go into edit the other end of the relationship, and it now complains 
that the m2m field is empty. But during that period until you tried to 
open/edit it, it was fine with having a empty mandatory m2m field. Surely 
there's an integrity issue there?

Secondly, is there a way to tweak the ON DELETE behaviour for m2m. E.g. can 
you set it to PROTECT, just like you do for FK's, to prevent you deleting an 
object, if something else has a m2m link to it? Or can you set it to ON 
CASCADE DELETE, as it does for FK?

Cheers,
Victor

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



Migrating custom view to class-based generic views ; Using staticfiles assets in CSS files?

2011-01-17 Thread Victor Hooi
Hi,

I'm currently migrating one of my apps to use the new contrib.staticfiles 
module in Django 1.3.

>From the documentation I can see there's two ways of referring to static 
files:

http://docs.djangoproject.com/en/dev/howto/static-files/

   1. Use {{ STATIC_URL}}
   2. Use {% load static %}, then {% get_static_prefix %}

However, option 1 seems to only work if you're using RequestContext - the 
easiest way of doing this seems to be using Generic (Class-based) Views.

Currently, I'm using a fairly simple custom view that returns a QuerySet of 
"Article" objects matching certain date/filtering criteria, then passes it 
to render_to_response. The start-date and entry-date are passed as part of 
the URL ie.. http://server.com/report_foo/2011-01-01/to/2010-01-05

def report_foo(request, start_date, end_date=None):
if end_date:
article_list = 
Article.objects.filter(in_daily_briefing=True).filter(entry_date__gte=start_date).filter(entry_date__lte=end_date).order_by('category',
 
'headline')
end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
else:
article_list = 
Article.objects.filter(in_daily_briefing=True).filter(entry_date=start_date).order_by('category',
 
'headline')
return render_to_response('report_foo.html', {'article_list': 
article_list, 'start_date': datetime.datetime.strptime(start_date, 
'%Y-%m-%d'), 'end_date': end_date})

First question - what is the best way to migrate this to a generic view? I 
was thinking:

from django.views.generic improt TemplateView
class ReportFooView(TemplateView):
if end_date:
article_list = 
Article.objects.filter(in_daily_briefing=True).filter(entry_date__gte=start_date).filter(entry_date__lte=end_date).order_by('category',
 
'headline')
end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
else:
article_list = 
Article.objects.filter(in_daily_briefing=True).filter(entry_date=start_date).order_by('category',
 
'headline')
params = {'article_list': article_list, 'start_date': 
datetime.datetime.strptime(start_date, '%Y-%m-%d'), 'end_date': end_date}
template_name = "report_foo.html"

Or is there a smarter way of doing this with the provided mixins/generics 
views?

And now my second question - I can use STATIC_URL or get_static_url in my 
template files - but how do I use these values in my CSS files? I.e. my CSS 
files need to reference assets stored as part of staticfiles.

Cheers,
Victor

-- 
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: Hyphens in Django app/project names?

2011-01-17 Thread Victor Hooi
Russ,

Aha, excellent, thanks for clearing that up =).

I can see you point - django-registration has a module called 
"registration", django-extensions has a module called "django_extensions", 
and django-staticfiles has one called "staticfiles". So it seems like I 
either go for a single-word module name, or replace hyphens with 
underscores.

Is there any recommendation from the Django team? Is sing underscores as 
faux-hyphens considered bad practice?

Cheers,
Victor

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



Hyphens in Django app/project names?

2011-01-14 Thread Victor Hooi
heya,

I'm just wondering whether you are allowed to use hyphens in Django 
app/project names?

When I try to create either an app or a project with hyphens in the name, I 
get an error:

Error: 'django-library' is not a valid app name. Please use only numbers, 
letters and underscores.

However, I know of several other apps which seem to have hyphens in their 
name.

https://bitbucket.org/ubernostrum/django-registration
https://github.com/django-extensions/django-extensions
https://github.com/jezdez/django-staticfiles

In fact, if you look at Django Pluggables (did they get renamed to Django 
Packages?), every mult-word app seems to use hyphens:

http://djangoplugables.com/

Did they just create the Django directory structure by hand, instead of 
using manage.py? Is it considered bad practice to use hyphens in names? Are 
they any good standards documents on Django app/project naming conventions? 
(I could only find an outdated one at 
http://homepage.mac.com/s_lott/iblog/architecture/C1597055042/E20070622152523/index.html
).

Cheers,
Victor

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



Re: django-extensions - "Error: no module named django_extensions"

2010-12-08 Thread Victor Hooi
heya,


Thanks for the reply. I'm fairly sure it is in the PYTHONPATH.


I'm using virtualenvs and pip to install, so it should be there in the
system-wide Python directory for that environment.


Also, as per my first post, I can import it fine from a Python shell,
it's just it seems to act up within Django...*confused*.


Cheers,
Victor

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



django-extensions - "Error: no module named django_extensions"

2010-12-08 Thread Victor Hooi
heya,


I original thought to post this in the django-extensions group, however
that seems like a fairly low-traffic group, so I thought I'd post here
in the hopes somebody here might be able to figure it out.


Basically, I've installed django-extensions via Pip
pip install django-extensions
Whenever I try to run any manage.py commands in my project, I get an
error:
Error: No module named django_extensions
In my settings.py, I have:
INSTALLED_APPS = (

'django_extensions',
In the Python shell,I can do a "import django_extensions" and it
imports fine with no error messages.


Not sure what's going on here?


I also tried with django-extensions from Github, same error.


Cheers,
Victor

-- 
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: Issues importing models in between apps

2010-11-30 Thread Victor Hooi
heya,

Sorry to reply to myself, but I seem to have the split worked out,
using string syntax as suggested by Daniel, as you would for a FK to a
model not yet defined (http://docs.djangoproject.com/en/dev/ref/models/
fields/#foreignkey).

It seems to work now, however, it is a bit messier than directly
referring to models by their name alone.

So the design question from my previous message still stands - is this
a candidate for splitting up across apps like this, or am I better off
going for a single app, and splitting up the models.py within there?
Or any other techniques you might recommend, to make the design more
logical and the models.py less unwieldly/large?

Cheers,
Victor

On Nov 30, 10:44 pm, bruno desthuilliers
<bruno.desthuilli...@gmail.com> wrote:
> On 30 nov, 07:01, Victor Hooi <victorh...@gmail.com> wrote:
>
> > Hi,
>
> > I had an application with a fairly large models.py file, which I split
> > up into separate apps to make it easier to manage.
>
> This won't address your problem but FWIW, you don't have to use
> separate apps just to split a models.py file - you can turn it into a
> models package, with the package's __init__.py used as a "facade" for
> the submodules (usual pythonic solution).
>
> But anyway:
>
> > Two of the apps are called "conferences" and "people", each with their
> > own models.py.
>
> > These two are fairly tightly entwined, they each refer to each other.
>
> If both models really depend that much on each other then they ought
> te live in a same module. Or perhaps there's room for improvement in
> your design but you don't give enough context.
>
> (snip typical circular deps symptom)
>
> > I'm not sure why this is happening - from the looks of it, it's
> > opening up conferences/models.py, then importing people.models.Person
> > from there, which inside of that tries to import Conference
>
> In Python almost everything happens at runtime. The import, class and
> def statements are executable statements, and they are executed - with
> every other top-level statement - when the module is first loaded.
>
> > Or is there a better way of creating multiple apps that all share
> > models?
>
> Put the interdependent models in a same app. The you can have other
> apps using these models too as long as there's no circular
> dependencies.
>
> A Django app doesn't have to define models or views or urls or
> whatever - you can have one app with models, and another vwith views
> and forms and whatnot depending on the first app's models.
>
> > The main reason I split it up was for logically separating all
> > the different models, they still all need to import/relate to each
> > other.
>
> Once again: if your models are tightly coupled, they ought to live in
> a same module.

-- 
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: Issues importing models in between apps

2010-11-30 Thread Victor Hooi
heya,

Thanks to both for your advice.

Yeah, you're right, it's a somewhat unwanted circular dependency. It
was just the only way I could think of to deal with a somewhat
unwieldy/large models.py file.

Even using the string syntax, I hit a bunch of other issues, due to
how tightly the two models are coupled ('Accessor clashes with related
field...', the 'through' table for m2m needs to be imported etc.). So
it might be better to try and sort out the design issue first.

To give some context - it's a simple application for managing people's
attendance at conferences, and allocating accomodation to them.

 * I have a 'People' app that has a models 'Person', along with models
for all their required information (allergies, special requirements,
spouse/children, contact numbers and addresses etc.).

 * I have a 'Conferences' app that imports Person, and stores things
about their attendance, accommodation requests, what workshop they're
assigned to etc.

 * I have a 'Facilities' app that manages all the various accomodation
sites and workshop rooms, and what they each provide. (e.g. how many
beds, how many seats etc.)

There's a few others, but those are the main ones.

Previously, I had this all in a single models.py inside Conferences.
However, it got a bit unwieldy, hence the split. However, they're all
still tightly coupled.

With the above information, would you still recommend putting it all
in a single app - or should I try and work out the issues from this
split? It did seem cleaner in separate apps.

Anyhow, from my understanding, I can split up the models.py file

http://code.djangoproject.com/ticket/4470
http://andrewwilkinson.wordpress.com/2009/01/20/placing-django-models-in-separate-files/

However, I'll need to add a Meta/app_label to each and every single
model in that file - is that right? Or is there a better way of
splitting up a models.py file across multiple files, or of somehow
organising this?

Cheers,
Victor

On Nov 30, 10:44 pm, bruno desthuilliers
<bruno.desthuilli...@gmail.com> wrote:
> On 30 nov, 07:01, Victor Hooi <victorh...@gmail.com> wrote:
>
> > Hi,
>
> > I had an application with a fairly large models.py file, which I split
> > up into separate apps to make it easier to manage.
>
> This won't address your problem but FWIW, you don't have to use
> separate apps just to split a models.py file - you can turn it into a
> models package, with the package's __init__.py used as a "facade" for
> the submodules (usual pythonic solution).
>
> But anyway:
>
> > Two of the apps are called "conferences" and "people", each with their
> > own models.py.
>
> > These two are fairly tightly entwined, they each refer to each other.
>
> If both models really depend that much on each other then they ought
> te live in a same module. Or perhaps there's room for improvement in
> your design but you don't give enough context.
>
> (snip typical circular deps symptom)
>
> > I'm not sure why this is happening - from the looks of it, it's
> > opening up conferences/models.py, then importing people.models.Person
> > from there, which inside of that tries to import Conference
>
> In Python almost everything happens at runtime. The import, class and
> def statements are executable statements, and they are executed - with
> every other top-level statement - when the module is first loaded.
>
> > Or is there a better way of creating multiple apps that all share
> > models?
>
> Put the interdependent models in a same app. The you can have other
> apps using these models too as long as there's no circular
> dependencies.
>
> A Django app doesn't have to define models or views or urls or
> whatever - you can have one app with models, and another vwith views
> and forms and whatnot depending on the first app's models.
>
> > The main reason I split it up was for logically separating all
> > the different models, they still all need to import/relate to each
> > other.
>
> Once again: if your models are tightly coupled, they ought to live in
> a same module.

-- 
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 - Alternative to using NULLs? (for integer and FK fields).

2010-11-29 Thread Victor Hooi
Mike,

Hmm, I'm currently using a recursive ('self') Many2Many and ForeignKey
for Children and Spouse, respectively (see source in the first post).

Is that what you meant?

Or perhaps I'm not quite getting what you mean - any chance you could
paste a models.py example so I can make sure I'm on the same page?

Cheers,
Victor

On Nov 30, 5:02 pm, Mike Dewhirst <mi...@dewhirst.com.au> wrote:
> On 30/11/2010 4:26pm, Victor Hooi wrote:
>
> > heya,
>
> > Phone Number - Yup, you're both right, I'll be using CharField now,
> > and model validation to make sure they're digits.
>
> > Spouse/Children:
>
> Victor
>
> I'm coming in late on this and don't have the context for your design
> but I think there might be a better (perhaps more flexible) way to
> handle spouses and children without worrying about NULLs.
>
> I really like a single table for everyone. After all spouses and
> children are persons too. You can use a separate table to hold named
> many-to-many relationships between the person table and itself.
>
> If the relationship is "Spouse" then that relationship speaks for
> itself. Children can simultaneously have relationships with "Father",
> "Mother", "Step-mother" etc. Other persons can have "Ex-spouse"
> relationships when divorced etc.
>
> If you can find any person then you can navigate through all the
> relationships to find all connected persons.
>
> Finally, if someone has multiple spouses then they probably need
> counselling but at least you can represent it with multiple relationship
> records :)
>
> Mike
>
>
>
>
>
>
>
>
>
> > With children, a M2M field, there's a link table, and if you don't
> > have a spouse, then there won't be any lines in that table. So no need
> > for NULLs there. I've just tested it with just blank=True, and no
> > null=True - seems to do what I want (optional children).
>
> > With ForeignKeyField though, I thought this was simply an FK field,
> > with the ID number of the object we're relating/pointing stored in
> > that field? Isn't that how it works in a normal DB? Why is there a
> > separate Person_spouse table?
>
> > Is there any way to make this optional without using NULLs, or should
> > I make it a m2m field? (I suppose in theory you can have multiple
> > spouses...well, not under my jurisdiction, I guess...lol).
>
> > Cheers,
> > Victor
>
> > On Nov 30, 3:11 pm, Lachlan Musicman<data...@gmail.com>  wrote:
> >> On Tue, Nov 30, 2010 at 12:28, Victor Hooi<victorh...@gmail.com>  wrote:
> >>> Hi,
>
> >>> I'm wondering what the community's stance on using NULL in Django is?
>
> >>> Say for example you have:
>
> >>>     class Person(models.Model):
> >>>         street_address = models.CharField(max_length=50, blank=True)
> >>>         suburb = models.CharField(max_length=30)
> >>>         postcode = models.IntegerField()
> >>>         state = models.CharField(max_length=3)
> >>>         email = models.EmailField()
> >>>         mobile_phone_number = models.IntegerField(max_length=12)
> >>>         home_phone_number = models.IntegerField(max_length=10,
> >>> null=True, blank=True)
> >>>         work_phone_number = models.IntegerField(max_length=8,
> >>> null=True, blank=True)
>
> >>>        spouse = models.ForeignKey('self', null=True, blank=True)
> >>>        children = models.ManyToManyField('self', null=True,
> >>> blank=True)
>
> >>> For string fields like street_address, I can make these "blank=True",
> >>> and Django will store an empty string if the user leaves it blank.
>
> >>> However, for integer fields like home_phone_number and
> >>> work_phone_number, I've had to make these "null=True" for the case
> >>> where somebody doesn't supply them (i.e. they're meant to be optional,
> >>> mobile is required).
>
> >>> However, is there a better way of handling this case? (assuming I want
> >>> to keep these fields as integers).
>
> >> Is it possible to know why you would want to keep them as integers?
> >> Given that there are no mathematical functions that you would want to
> >> apply to them
>
> >>> What about in the case of optional foreign keys (spouse and children)
> >>> - is there a better way of handling these, without using NULLs?
>
> >> As I understand it, foreign keys are kept in the db as follows:
>
> >> 1. table_Person
> &

Issues importing models in between apps

2010-11-29 Thread Victor Hooi
Hi,

I had an application with a fairly large models.py file, which I split
up into separate apps to make it easier to manage.

Two of the apps are called "conferences" and "people", each with their
own models.py.

These two are fairly tightly entwined, they each refer to each other.

At the top of project_name/conferences/models.py, I have:

from django.db import models
from nextgen.people.models import Person

At the top of project_name/people/models.py, I have:

from django.db import models
from project_name.conferences.models import Conference

However, when I try to run ./manage.py validate, it gives me an error:

  File "/sites/.virtualenvs/project_name/src/django/django/utils/
importlib.py", line 35, in import_module
__import__(name)
  File "/home/victorhooi/djangoProjects/project_name/../
project_name/conferences/models.py", line 2, in 
from project_name.people.models import Person
  File "/home/victorhooi/djangoProjects/project_name/../
project_name/people/models.py", line 3, in 
from project_name.conferences.models import Conference
ImportError: cannot import name Conference

I'm not sure why this is happening - from the looks of it, it's
opening up conferences/models.py, then importing people.models.Person
from there, which inside of that tries to import Conference - is it
somehow clashing?

Or is there a better way of creating multiple apps that all share
models? The main reason I split it up was for logically separating all
the different models, they still all need to import/relate to each
other.

Cheers,
Victor

-- 
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 - Alternative to using NULLs? (for integer and FK fields).

2010-11-29 Thread Victor Hooi
heya,

Phone Number - Yup, you're both right, I'll be using CharField now,
and model validation to make sure they're digits.

Spouse/Children:

With children, a M2M field, there's a link table, and if you don't
have a spouse, then there won't be any lines in that table. So no need
for NULLs there. I've just tested it with just blank=True, and no
null=True - seems to do what I want (optional children).

With ForeignKeyField though, I thought this was simply an FK field,
with the ID number of the object we're relating/pointing stored in
that field? Isn't that how it works in a normal DB? Why is there a
separate Person_spouse table?

Is there any way to make this optional without using NULLs, or should
I make it a m2m field? (I suppose in theory you can have multiple
spouses...well, not under my jurisdiction, I guess...lol).

Cheers,
Victor

On Nov 30, 3:11 pm, Lachlan Musicman <data...@gmail.com> wrote:
> On Tue, Nov 30, 2010 at 12:28, Victor Hooi <victorh...@gmail.com> wrote:
> > Hi,
>
> > I'm wondering what the community's stance on using NULL in Django is?
>
> > Say for example you have:
>
> >    class Person(models.Model):
> >        street_address = models.CharField(max_length=50, blank=True)
> >        suburb = models.CharField(max_length=30)
> >        postcode = models.IntegerField()
> >        state = models.CharField(max_length=3)
> >        email = models.EmailField()
> >        mobile_phone_number = models.IntegerField(max_length=12)
> >        home_phone_number = models.IntegerField(max_length=10,
> > null=True, blank=True)
> >        work_phone_number = models.IntegerField(max_length=8,
> > null=True, blank=True)
>
> >       spouse = models.ForeignKey('self', null=True, blank=True)
> >       children = models.ManyToManyField('self', null=True,
> > blank=True)
>
> > For string fields like street_address, I can make these "blank=True",
> > and Django will store an empty string if the user leaves it blank.
>
> > However, for integer fields like home_phone_number and
> > work_phone_number, I've had to make these "null=True" for the case
> > where somebody doesn't supply them (i.e. they're meant to be optional,
> > mobile is required).
>
> > However, is there a better way of handling this case? (assuming I want
> > to keep these fields as integers).
>
> Is it possible to know why you would want to keep them as integers?
> Given that there are no mathematical functions that you would want to
> apply to them
>
> > What about in the case of optional foreign keys (spouse and children)
> > - is there a better way of handling these, without using NULLs?
>
> As I understand it, foreign keys are kept in the db as follows:
>
> 1. table_Person
> 2. table_Person_children
> 3. table_Person_spouse
>
> table 2 has three columns: id, Person, Children
> table 3 has three columns: id, Person, Spouse
>
> or something to that effect.
>
> Therefore, if there is no Spouse or Child, there is no entry for
> Person in tables 2 or 3.
>
>
>
>
>
>
>
> > Cheers,
> > Victor
>
> > --
> > 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.



Django - Alternative to using NULLs? (for integer and FK fields).

2010-11-29 Thread Victor Hooi
Hi,

I'm wondering what the community's stance on using NULL in Django is?

Say for example you have:

class Person(models.Model):
street_address = models.CharField(max_length=50, blank=True)
suburb = models.CharField(max_length=30)
postcode = models.IntegerField()
state = models.CharField(max_length=3)
email = models.EmailField()
mobile_phone_number = models.IntegerField(max_length=12)
home_phone_number = models.IntegerField(max_length=10,
null=True, blank=True)
work_phone_number = models.IntegerField(max_length=8,
null=True, blank=True)

   spouse = models.ForeignKey('self', null=True, blank=True)
   children = models.ManyToManyField('self', null=True,
blank=True)

For string fields like street_address, I can make these "blank=True",
and Django will store an empty string if the user leaves it blank.

However, for integer fields like home_phone_number and
work_phone_number, I've had to make these "null=True" for the case
where somebody doesn't supply them (i.e. they're meant to be optional,
mobile is required).

However, is there a better way of handling this case? (assuming I want
to keep these fields as integers).

What about in the case of optional foreign keys (spouse and children)
- is there a better way of handling these, without using NULLs?

Cheers,
Victor

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



Serve different page to IE7/8?

2010-11-21 Thread Victor Hooi
Hi,

We're currently development a small Django webapp for use internally.

The page renders fine on Firefox and Webkit-based browsers.

However, many of our users are still on Internet Explorer 7, and the
CSS/HTML we're using seems to bork really badly on that. I'm
definitely not a web-designer by trade, and I'm not really not on top
of all the quirks of the different browser.

I know this is a bit of a hack, but what's the best way to serve up a
different template to those IE7 users? Hopefully it'll be less of an
issue when IE9 eventually rolls out (although I suspect it'll still be
an issue), but something like this would be a good stopgap for us, and
the site/templates itself it fairly simple.

What's the most Django-ish way of doing it?

We'd probably actually like something similar for our BlackBerry users
as well - same view code, but serving up a different template, based
on user-agent - recommended way?

Cheers,
Victor

-- 
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: ReportLab and Django - templates? ; FK object has no attribute split

2010-11-18 Thread Victor Hooi
Hi:

natebeacham: Yup, using item.category.name works fine =).

Using string interpolation on item.category also works - I was silly,
forgot to restart the gunicorn process (I suppose you have to restart
it after any changes to views.py, right? Or does it pick it up
automatically after a while?).

So between the two approaches, using item.category.name, and using
string interpolation is one preferable to the other?

Jikra: Thanks for the tip =). I did try Pisa for a bit, but for some
reason, it was just timing out when I tried to integrate it into
Django.

The reason I didn't push harder to investigate the issue was that
firstly, the command-line utility seemed to have pretty poor
performance anyway.

And secondly, Pisa itself seems to have been discontinued:

http://groups.google.com/group/xhtml2pdf/browse_thread/thread/32dcee769245fc8f

Finally, Pisa (and other approaches wkhtmltopdf) seem to require a lot
more dependencies installed/setup - reportlab is just a single package
to compile.

But  yeah, I'd still love if there was a separate template I could use
to generate the PDF. It just feels very weird building up the PDF line
by line in views.py.

Cheers,
Victor

On Nov 18, 8:14 pm, Jirka Vejrazka <jirka.vejra...@gmail.com> wrote:
> Hi Victor,
>
>   It really depends on complexity of your PDF. I needed to do
> something similar some time ago and used ReportLab addon called "pisa"
> and used standard Django template language to define the PDF contents.
>
>   You might want to take a look, it worked well enough for simple PDF pages.
>
>   Cheers
>
>     Jirka
>
> On 18/11/2010, Victor Hooi <victorh...@gmail.com> wrote:
>
>
>
>
>
>
>
> > Hi,
>
> > I'm trying to use ReportLab to produce a PDF output for one of my
> > views.
>
> > My first question is - at the moment, I'm building up the PDF inside
> > my view. Is this really the recommended way of doing it? It's like
> > I've got presentation code inside my view (controller). Isn't there a
> > cleaner way of doing it, or going from a template to PDF somehow? (I
> > know ReportLab offers a commercial package using RML templates,
> > however I was hoping for an opensource/free method).
>
> > Second question, I have a model with several FK fields. E.g.
>
> >     class Article(models.Model):
> >         category = models.ForeignKey(Category)
> >         subject = models.ForeignKey(Subject)
>
> > Both the category and subject classes have fields called "name", and
> > __unicode__ methods defined which return name.
>
> > I'm trying to refer to these fields in my PDF output. I have a list of
> > items in article_list (i.e. queryset):
>
> >     for item in article_list:
> >         text = item.category
> >         category = Paragraph(text, styles['Heading2'])
> >         story.append(category)
>
> >         text = '%s' % item.subject
> >         subject = Paragraph(text, styles['Heading3'])
> >         story.append(subject)
>
> > When I try to run this code, I get:
>
> >     'Category' object has no attribute 'split'
>
> > and the same error with subject, obviously, once it gets to that bit
> > of the code.
>
> > Any idea why this might be, or how to fix it? Any help is much
> > appreciated.
>
> > Cheers,
> > Victor
>
> > --
> > 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.

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



ReportLab and Django - templates? ; FK object has no attribute split

2010-11-17 Thread Victor Hooi
Hi,

I'm trying to use ReportLab to produce a PDF output for one of my
views.

My first question is - at the moment, I'm building up the PDF inside
my view. Is this really the recommended way of doing it? It's like
I've got presentation code inside my view (controller). Isn't there a
cleaner way of doing it, or going from a template to PDF somehow? (I
know ReportLab offers a commercial package using RML templates,
however I was hoping for an opensource/free method).

Second question, I have a model with several FK fields. E.g.

class Article(models.Model):
category = models.ForeignKey(Category)
subject = models.ForeignKey(Subject)

Both the category and subject classes have fields called "name", and
__unicode__ methods defined which return name.

I'm trying to refer to these fields in my PDF output. I have a list of
items in article_list (i.e. queryset):

for item in article_list:
text = item.category
category = Paragraph(text, styles['Heading2'])
story.append(category)

text = '%s' % item.subject
subject = Paragraph(text, styles['Heading3'])
story.append(subject)

When I try to run this code, I get:

'Category' object has no attribute 'split'

and the same error with subject, obviously, once it gets to that bit
of the code.

Any idea why this might be, or how to fix it? Any help is much
appreciated.

Cheers,
Victor

-- 
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: Using localflavor with admin?

2010-11-01 Thread Victor Hooi
heya,

Thanks for your answer - I posted a reply (doesn't seem to work for
non-US), however, it doesn't seem to have appeared on the web-version
of Groups, so I thought I'd email you directly, just in case you
missed it and happened to know.

Thanks,
Victor

Hmm, I'm actually trying this Australian localisation.
However, the weird thing is, there's a US models.py:
http://code.djangoproject.com/browser/django/trunk/django/contrib/localflavor/us/models.py
But there's no such models.py for other countries. E.g., for
Australia:
http://code.djangoproject.com/browser/django/trunk/django/contrib/localflavor/au
Is there a particular reason for this? Or any way of achieving the
same effect?

On Oct 29, 5:48 am, Frank Wiles <fr...@wiles.org> wrote:
> On Thu, Oct 28, 2010 at 12:23 AM, Victor Hooi <victorh...@gmail.com> wrote:
> > Hi,
>
> > Is there any way to combine the localflavor module (http://
> > docs.djangoproject.com/en/dev/ref/contrib/localflavor/) with Django's
> > in-built admin module?
>
> > For example, I'd like to create a model with say, a Postcode and phone-
> > number field, and have these validated in the admin, as per the rules
> > setup in localflavor?
>
> Hi Victor,
>
> You just need to use the the model fields to achieve this.  So for
> example, if I was going to do a US Phone Number field I would do:
>
> from django.db import models
> from django.contrib.localflavor.us.models import PhoneNumberField
>
> class Test(models.Model):
>     phone = PhoneNumberField()
>
> You'd obviously need to reference the exact field you're looking for,
> but then it just automagically works in the admin.
>
> --
> Frank Wiles
> Revolution Systems |http://www.revsys.com/
> fr...@revsys.com   | (800) 647-6298

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



Reverse Query Name Clash?

2010-11-01 Thread Victor Hooi
Hi,

I'm getting a error about reverse query name clashes with my models.

We have a Django app to manage conferences and conference attendees.

In our models.py, two of the models we have are:

1. Person, representing people attending people attending a
conference. Each person also has a "church" field, which represents
the main church they attend.

class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
gender = models.CharField(max_length=1,
choices=GENDER_CHOICES)
spouse = models.ForeignKey('self', null=True, blank=True)
date_of_birth = models.DateField()
church = models.ForeignKey('Church')
...

The "church" FK is in quotation marks, since the Church object is
defined below Person.

2. "Church", which defines a church, and includes an optional field
for the main minister at that church. The minister field is a FK to a
Person.

class Church(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=50)
suburb = models.CharField(max_length=30)
postcode = models.IntegerField()
state = models.CharField(max_length=3, choices=AUSTRALIAN_STATES)
minister = models.ForeignKey(Person, null=True, blank=True)

So a person has a church, and a church also has a minister (in most
cases the two will be different, except for the case where the
minister themselves is attending a conference, which should of course
be valid).

The issue here is that the model doesn't validate:

Error: One or more models did not validate:
conferences.church: Reverse query name for field 'minister'
clashes with field 'Person.church'. Add a related_name argument to the
definition for 'minister'.

Now, if I change the name of the "church" field under Person, it will
validate - however, I'm still curious as to why this doesn't work? Any
way to fix it? (I assume I could add a related_name argument, I'm just
trying to figure out what's going on, and gain more understanding for
Django).

Cheers,
Victor

-- 
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: Using localflavor with admin?

2010-11-01 Thread Victor Hooi
heya,

Hmm, I'm actually trying this Australian localisation.

However, the weird thing is, there's a US models.py:

http://code.djangoproject.com/browser/django/trunk/django/contrib/localflavor/us/models.py

But there's no such models.py for other countries. E.g., for
Australia:

http://code.djangoproject.com/browser/django/trunk/django/contrib/localflavor/au

Is there a particular reason for this? Or any way of achieving the
same effect?

Cheers,
Victor

On Oct 29, 5:48 am, Frank Wiles <fr...@wiles.org> wrote:
> On Thu, Oct 28, 2010 at 12:23 AM, Victor Hooi <victorh...@gmail.com> wrote:
> > Hi,
>
> > Is there any way to combine the localflavor module (http://
> > docs.djangoproject.com/en/dev/ref/contrib/localflavor/) with Django's
> > in-built admin module?
>
> > For example, I'd like to create a model with say, a Postcode and phone-
> > number field, and have these validated in the admin, as per the rules
> > setup in localflavor?
>
> Hi Victor,
>
> You just need to use the the model fields to achieve this.  So for
> example, if I was going to do a US Phone Number field I would do:
>
> from django.db import models
> from django.contrib.localflavor.us.models import PhoneNumberField
>
> class Test(models.Model):
>     phone = PhoneNumberField()
>
> You'd obviously need to reference the exact field you're looking for,
> but then it just automagically works in the admin.
>
> --
> Frank Wiles
> Revolution Systems |http://www.revsys.com/
> fr...@revsys.com   | (800) 647-6298

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



Converting Django to Desktop App? (Multiple Instances)

2010-10-29 Thread Victor Hooi
Hi,

This is a bit of a strange scenario.

We have a simple Django application used to maintain a database of
newspaper/journal articles. We're extensively using the django-admin
as part of this app.

Currently, we're having issues getting a production environment with
Python provisioned (corporate environment, locked technology roadmap
etc.), however, we will have access to a Oracle database instance.

One possibility raised was that for each of the clients (fairly small,
under 5), we install a local instance of Django and Apache, which they
access with their browser, and each of these instances communicates
with a single Oracle DB instance.

I know on the Rails side, there was a product by Joyent called
Slingshot (http://joyeur.com/2007/03/22/joyent-slingshot/), which
allegedly did something similar (packaged up a RoR app into a desktop
application).

Are there any particular issues we need to be aware of if we decided
to go down this path?

In particular, I wasn't sure how multiple instances of Django would
handle concurrency if they were communicating with a single database.
Any advice there?

Any other possible drawbacks/roadblocks?

Cheers,
Victor

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



Using localflavor with admin?

2010-10-27 Thread Victor Hooi
Hi,

Is there any way to combine the localflavor module (http://
docs.djangoproject.com/en/dev/ref/contrib/localflavor/) with Django's
in-built admin module?

For example, I'd like to create a model with say, a Postcode and phone-
number field, and have these validated in the admin, as per the rules
setup in localflavor?

Cheers,
Victor

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



Model Validation - Prevent Datetimefield overlaps?

2010-08-30 Thread Victor Hooi
heya,

I have a model that contains a whole bunch of bytes in/out for
datetime ranges. I.e.:

class BandwidthUsageEntry(models.Model):
start_of_usage_block = models.DateTimeField()
end_of_usage_block = models.DateTimeField()
bytes_in = models.IntegerField()
bytes_out = models.IntegerField()

I need to ensure that each entry doesn't overlap with any others
entries.

Just playing around - I noticed that setting "unique=True" on a
DateTimeField() doesn't seem to work? As in, I was able to do
something like:

b1 =
BandwidthUsageEntry(start_of_usage_block=datetime.datetime(2007,05,05,12,05),
end_of_usage_block=datetime.datetime(2007,05,12,12,10),bytes_in=10,bytes_out=10)
b1.save()
b2 =
BandwidthUsageEntry(start_of_usage_block=datetime.datetime(2007,05,05,12,05),
end_of_usage_block=datetime.datetime(2007,05,12,12,10),bytes_in=20,bytes_out=20)
b2.save()

Is this expected behaviour, or do I have something wrong with my
setup?

Anyhow, in terms of how to actually prevent overlaps, I assume that
the best way is to use a custom model validator, and check each start/
end against a query against all the entries?

(I saw this 
http://stackoverflow.com/questions/2243490/django-unique-time-interval-for-the-admin-panel,
but it seems to be going a different way that I don't follow).

How would I go about structuring this? Any particular tips here, or
any algorithms that could work well?

Cheers,
Victor

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



Error in Admin - can't seem to chain __unicode__'s for ForeignKeys

2010-07-08 Thread Victor Hooi
heya,

I have a small Django app that contains a list of Df (disk-free)
reports.

"DfReport" has a ForeignKey to "Filesystem" model, which has a
ForeignKey to "Device". (i.e. Devices has filesystems, each filesystem
has a DfReport).

I'm getting an error in the admin when I attempt to display the
list_display page for a "DfReport" model.

TemplateSyntaxError at /admin/report/dfreport/add/
Caught TypeError while rendering: coercing to Unicode: need string
or buffer, Device found

I've traced the error to the __unicode__ method for one of the
ForeignKey fields on DfReport being displayed.

The issue is, Filesystem has __unicode__ set to print the server on
which it's reporting. Using the following causes the
TemplateSyntaxError:

class Filesystem(models.Model):
name = models.CharField(max_length=50)
#description = models.CharField(max_length=100)
description = models.TextField()
server = models.ForeignKey(Device)

def __unicode__(self):
return self.name + ' on device ' + self.server

However, if I change self.server to "self.server.name", it works. The
weird thing is - Device (which server points to), has a __unicode__
method defined as well. Shouldn't calling self.server just use the
__unicode__ method on Device, instead of needing me to explicitly call
self.server.name?

class Device(models.Model):
name = models.CharField(max_length=50)
#description = models.CharField(max_length=100)
description = models.TextField()
location = models.ForeignKey(Location)

def __unicode__(self):
return self.name

class Meta:
ordering = ['name']

Or have I got a wrong understanding of how this works?

Cheers,
Victor

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



Newbie Question - django-jython - how to "run" the app?

2010-07-01 Thread Victor Hooi
heya,

I've trying to get my Django app to run on a Tomcat 5.x server, using
django-jython. I'm a bit of a newbie in the Java/Tomcat world though.

Firstly, I'm currently using PostgreSQL. However, to make things
easier on the target server, I was just going to use SQLite3 - the app
will only be used by two users, and getting a database in this
deployment environment is a bit tricky. However, I read on the django-
jython pages that SQlite3 support is experimental and considered
risky:

http://packages.python.org/django-jython/database-backends.html

Is that still true? Should I try and push hard to get a database setup
for me? The only one they offer is MySQL, there's a few hoops to get
that though.

Secondly, apparently this Tomcat server doesn't take WAR archives
files, you need to explode them first. Anyhow, I've unzipped the WAR
archive to the directory, now I'm not exactly sure how to get it to
actually run.

Under my app context directory, my structure looks like (where
application is called chair, just for example's sake)

\chair
 - application.py
 - application$py.class
 \WEB-INF
   web.xml
   \lib
- jruby-extras-fileservlet.jar
- jython.jar
   \lib-python
 - Lib.pth
 - README
 \chair
 \django
 \doj
 \Lib

etc.

Is this right, or am I missing any files/directories in the WAR
creation?

Apart from setting up the context, what exactly do I need to do (or
get the web server administrator) to do to get the application to run?
Do I need to get them to import the web.xml file? I had a look in
there, didn't seem to find anything that seems to "run" my app, or
point to anything to get it to run?

Cheers,
Victor

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



Django-Admin - radio_fields with add/change pages, but not list_display page?

2010-06-29 Thread Victor Hooi
Hi,

I have a Django application with an "Article" model. I'm using the
radio_fields in django-admin with two of the ForeignKey fields that
are linked to Article.

Currently the related tables have five and twenty entries each, so
this UI works quite well on the Add/Change pages.

However, I'm also using list_display with this model - and in the
list_display, it also displays radio boxes, which look quite ugly -
the HTML select box worked much better on list_display. In fact, I
can't really think of many cases, unless the number of possible
entries was quite small, where a radio_box would work well with
list_display.

Anyhow, is there any way to use radio_fields on the Add/Change field,
but not with the list_display page?

Cheers,
Victor

-- 
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: m2m with intermediary - model design? Disappears from Django-Admin?

2010-06-24 Thread Victor Hooi
heya,

Ok, scratch all that, I'm an idiot.

A simple restart of my Apache process, and the m2m intermediary inline
works *grins*.

Thanks anyhow to the awesome Django community for an awesome tool =).

I do have a final question though. I can now edit "Firms" as inlines
from the "Article" page, which is good.

However, to be honest, the filter_horizontal widget was a much better
interface. I suppose there's no way to somehow use the
filter_horizontal widget within the inline, and then tack on a
"Rating" field as part of the inline?

Also, I notice that in my inline, it says "FirmRating object" right
above the select box:'

http://twitpic.com/1zo4im/full

Any way to hide/tweak that text?

Cheers,
Victor

On Jun 25, 10:09 am, Victor Hooi <victorh...@gmail.com> wrote:
> heya,
>
> Also, I should add I did try using the inlines as described in the
> docs
>
> http://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-...
>
> In my admin.py, I've imported "FirmRating" at the top.
>
> I've then created an inline for it:
>
> class FirmRatingInline(admin.TabularInline):
>     model = FirmRating
>     extra = 1
>
> then used this in ArticleAdmin:
>
> class ArticleAdmin(admin.ModelAdmin):
>     #inlines = [
>     #    CategoryInline,
>     #]
>     date_hierarchy = 'publication_date'
>     filter_horizontal = ('firm', 'spokesperson')
>     list_display = ('title', 'publication_date', 'entry_date',
> 'category', 'subject', 'source_publication', 'weekly_summary')
>     list_editable = ('publication_date', 'category', 'subject',
> 'source_publication')
>     list_filter = ('publication_date', 'entry_date', 'category',
> 'subject', 'source_publication')
>     search_fields = ('title', 'publication_date', 'abstract',
> 'category__name', 'subject__name', 'source_publication__name',
> 'page_number', 'url')
>
> However, there's still no visible widget for "FirmRating" on the "Add
> Article" page.
>
> I can't tell just from the docs, but is this inline only for use on
> the main Article list page, but not on the Add Article page? Or is the
> above admin code meant to make the widget visible on the "Add Article"
> page as well?
>
> Cheers,
> Victor
>
> On Jun 25, 10:01 am, Victor Hooi <victorh...@gmail.com> wrote:
>
>
>
> > heya,
>
> > NB: This is a followup to this:
>
> >http://groups.google.com/group/django-users/browse_thread/thread/0fdc...
>
> > but I thought I'd also ask about the model design.
>
> > To provide some background, we have a Django app that contains a list
> > of journal articles.
>
> > Each "Article" also has a m2m relationship to "Firm" as well as
> > "Spokesperson"
>
> > class Article(models.Model):
> >     title = models.CharField(max_length=100)
> >     publication_date = models.DateField()
> >     abstract = models.TextField() # Can we restrict this to 450
> > characters?
> >     ...fields ommited for brevity...
> >     firm = models.ManyToManyField(Firm, null=True, blank=True,
> > through='FirmRating')
> >     spokesperson = models.ManyToManyField(Spokeperson, null=True,
> > blank=True, through='SpokespersonRating')
>
> > The intermediary models, FirmRating and SpokespersonRating look like
> > this:
>
> > class FirmRating(models.Model):
> >     firm = models.ForeignKey(Firm)
> >     article = models.ForeignKey(Article)
> >     rating = models.IntegerField()
>
> > Basically, we use it to store the m2m link, as well as a "rating"
> > assigned to each relationship.
>
> > The issue is, as soon as I change it from a normal m2m relationship to
> > one with a "through" attribute, it seems to completely disappear in
> > the Django Admin from the "Add Article" page. Before, I had a nice
> > little filter_horizontal widget to create the relationships. No,
> > zippo...that's not a bug, is it?
>
> > Anyhow, Firstly, am I doing this the right way? Or is there another
> > way to create an Article, have it m2m with Firms/Spokesperson, and
> > assign an individual rating to each relationship?
>
> > Secondly, is there some way of making a m2m with intermediary visibile
> > in the admin - is it intended behaviour for it to disappear? In an
> > ideal world, I'd like to have the filter_horizontal, as well as an
> > inline widget to set the rating, all on the "Add Article" page.
> > However, I'm prepared to have just the filter_horizontal for the m2m,
> > and set the rating separately, on a separate page just for FirmRating/
> > SpokespersonRating (it obviously breaks the workflow a bit there).
>
> > How do people normally deal with editing m2m intermediary models in
> > Django?
>
> > Cheers,
> > Victor- Hide quoted text -
>
> - Show quoted text -

-- 
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: m2m with intermediary - model design? Disappears from Django-Admin?

2010-06-24 Thread Victor Hooi
heya,

Also, I should add I did try using the inlines as described in the
docs

http://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-many-to-many-intermediary-models

In my admin.py, I've imported "FirmRating" at the top.

I've then created an inline for it:

class FirmRatingInline(admin.TabularInline):
model = FirmRating
extra = 1

then used this in ArticleAdmin:

class ArticleAdmin(admin.ModelAdmin):
#inlines = [
#CategoryInline,
#]
date_hierarchy = 'publication_date'
filter_horizontal = ('firm', 'spokesperson')
list_display = ('title', 'publication_date', 'entry_date',
'category', 'subject', 'source_publication', 'weekly_summary')
list_editable = ('publication_date', 'category', 'subject',
'source_publication')
list_filter = ('publication_date', 'entry_date', 'category',
'subject', 'source_publication')
search_fields = ('title', 'publication_date', 'abstract',
'category__name', 'subject__name', 'source_publication__name',
'page_number', 'url')

However, there's still no visible widget for "FirmRating" on the "Add
Article" page.

I can't tell just from the docs, but is this inline only for use on
the main Article list page, but not on the Add Article page? Or is the
above admin code meant to make the widget visible on the "Add Article"
page as well?

Cheers,
Victor

On Jun 25, 10:01 am, Victor Hooi <victorh...@gmail.com> wrote:
> heya,
>
> NB: This is a followup to this:
>
> http://groups.google.com/group/django-users/browse_thread/thread/0fdc...
>
> but I thought I'd also ask about the model design.
>
> To provide some background, we have a Django app that contains a list
> of journal articles.
>
> Each "Article" also has a m2m relationship to "Firm" as well as
> "Spokesperson"
>
> class Article(models.Model):
>     title = models.CharField(max_length=100)
>     publication_date = models.DateField()
>     abstract = models.TextField() # Can we restrict this to 450
> characters?
>     ...fields ommited for brevity...
>     firm = models.ManyToManyField(Firm, null=True, blank=True,
> through='FirmRating')
>     spokesperson = models.ManyToManyField(Spokeperson, null=True,
> blank=True, through='SpokespersonRating')
>
> The intermediary models, FirmRating and SpokespersonRating look like
> this:
>
> class FirmRating(models.Model):
>     firm = models.ForeignKey(Firm)
>     article = models.ForeignKey(Article)
>     rating = models.IntegerField()
>
> Basically, we use it to store the m2m link, as well as a "rating"
> assigned to each relationship.
>
> The issue is, as soon as I change it from a normal m2m relationship to
> one with a "through" attribute, it seems to completely disappear in
> the Django Admin from the "Add Article" page. Before, I had a nice
> little filter_horizontal widget to create the relationships. No,
> zippo...that's not a bug, is it?
>
> Anyhow, Firstly, am I doing this the right way? Or is there another
> way to create an Article, have it m2m with Firms/Spokesperson, and
> assign an individual rating to each relationship?
>
> Secondly, is there some way of making a m2m with intermediary visibile
> in the admin - is it intended behaviour for it to disappear? In an
> ideal world, I'd like to have the filter_horizontal, as well as an
> inline widget to set the rating, all on the "Add Article" page.
> However, I'm prepared to have just the filter_horizontal for the m2m,
> and set the rating separately, on a separate page just for FirmRating/
> SpokespersonRating (it obviously breaks the workflow a bit there).
>
> How do people normally deal with editing m2m intermediary models in
> Django?
>
> Cheers,
> Victor

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



m2m with intermediary - model design? Disappears from Django-Admin?

2010-06-24 Thread Victor Hooi
heya,

NB: This is a followup to this:

http://groups.google.com/group/django-users/browse_thread/thread/0fdc1dfb1fddb97b/6b559dc4abf5d4ea

but I thought I'd also ask about the model design.

To provide some background, we have a Django app that contains a list
of journal articles.

Each "Article" also has a m2m relationship to "Firm" as well as
"Spokesperson"

class Article(models.Model):
title = models.CharField(max_length=100)
publication_date = models.DateField()
abstract = models.TextField() # Can we restrict this to 450
characters?
...fields ommited for brevity...
firm = models.ManyToManyField(Firm, null=True, blank=True,
through='FirmRating')
spokesperson = models.ManyToManyField(Spokeperson, null=True,
blank=True, through='SpokespersonRating')

The intermediary models, FirmRating and SpokespersonRating look like
this:

class FirmRating(models.Model):
firm = models.ForeignKey(Firm)
article = models.ForeignKey(Article)
rating = models.IntegerField()

Basically, we use it to store the m2m link, as well as a "rating"
assigned to each relationship.

The issue is, as soon as I change it from a normal m2m relationship to
one with a "through" attribute, it seems to completely disappear in
the Django Admin from the "Add Article" page. Before, I had a nice
little filter_horizontal widget to create the relationships. No,
zippo...that's not a bug, is it?

Anyhow, Firstly, am I doing this the right way? Or is there another
way to create an Article, have it m2m with Firms/Spokesperson, and
assign an individual rating to each relationship?

Secondly, is there some way of making a m2m with intermediary visibile
in the admin - is it intended behaviour for it to disappear? In an
ideal world, I'd like to have the filter_horizontal, as well as an
inline widget to set the rating, all on the "Add Article" page.
However, I'm prepared to have just the filter_horizontal for the m2m,
and set the rating separately, on a separate page just for FirmRating/
SpokespersonRating (it obviously breaks the workflow a bit there).

How do people normally deal with editing m2m intermediary models in
Django?

Cheers,
Victor

-- 
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: M2M with Intermediary - Django Admin Support - Doesn't appear?

2010-06-24 Thread Victor Hooi
heya,

Nuno: Thanks for the advice.

I know how to add normal inlines to the home page for a model, via the
"inlines" list in admin.py. However, how exactly do I add an inline
formset to the Add Article page?

I can override the template for the Add Article page, however, I don't
think that's what needs to be done here.

Is there a clean way of using the existing "Add Article" page, but
just swapping in an inline for the intermediary? Also, I'd like to
leverage off the exisiting "filter_horizontal" widget, if possible.
Basically, I just want it exactly as it was, without the intermediary,
with a filter_horizontal for settings the m2m relationship, but then
with just an additional widget for setting the intermediary "rating"
field.

(I found this write-up http://www.fictitiousnonsense.com/archives/22
however, it seems geared towards replacing a single field on a single
model, not sure how it'd handle the intermediary model here. Also is
this method still valid/best practice?).

Cheers,
Victor

On May 15, 2:29 am, Nuno Maltez  wrote:
> Hmmm ... you should have an inline formset at the bottom to add firms
> to your Article, with an associated input box forthe rating.
>
> If I understand correctly, each relation Article-Firm now needs a
> rating (mandatory), sou you can't just select Firms from a
> filter_horizontal widget - you need a way to input the rating as well.
>
> Nuno
>
> --
> 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.



Apache + Gunicorn + Django? Sample Configs?

2010-06-21 Thread Victor Hooi
Hi,

I'm currently deploying Django on Apache with WSGI.

Anyhow, I've heard really good things about the Gunicorn (http://
gunicorn.org/) WSGI server, so I was hoping to try it out.

I'm running Ubuntu 10.04, so I've installed the packages from the
official PPA (https://launchpad.net/~bchesneau/+archive/gunicorn)

However, I'm having trouble finding detailed instructions for Gunicorn
+ Django in English. E.g.:

http://blog.exirel.me/technique/apache-proxy-gunicorn-runit-django
http://blog.sietch-tabr.com/index.php/post/2010/04/04/Heberger-des-projets-Django-avec-Nginx-et-Gunicorn

Nor can I seem to find anything on how to deploy Apache + Django +
Gunicorn in English either.

Has anybody had success with getting it properly setup in production
with Django, and if so, would it be possible to post up your sample
config scripts?

Many of the guides refer to using Nginx - however, I need Apache
running on this server (other sites), and I only have a single IP
address on this system. And I'm not aware of any way of passing only
specific virtual-hosts through to Nginx, to then pass onto Gunicorn.
But if there's an easy way of doing that, I'm open to using Nginx +
Django + Gunicorn as an alternative.

Cheers,
Victor

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



  1   2   >