Re: Auto increase number number

2012-05-16 Thread Scott Gould
What is the purpose of the "no" field? If it's for display, it may be
that you don't need to store it in the database at all. Something
like:

no, obj = enumerate(UserProfile.objects.all())

Even if it does need to be stored in the database, it's a calculated
value that must be based upon the entire set of sorted objects, by the
look of it. In which case you'll probably need a manager method to
make changes to all the objects that are offset upon a delete of one
in the middle of the pack. That could make deletes quite expensive.

On May 16, 6:38 am, yillkid  wrote:
> Hi all .
>
> I want to add a Field "no" for assign numbers to user.
> The content what I need as below ( user change page):
>
> no            user name
> ---
> 1              root
> 2              user_1
> 3              user_2
>
> But "no" is different with "pk" of the user, because it's a variable value,
> for example, if I delete the user "user_1", the output will changed as
> below:
>
> no            user name
> ---
> 1              root
> 2              user_2
>
> So paste my model.py: (segment only),
> how to implement the "no"? thanks.
>
> class UserAdmin(UserAdmin):
>         inlines = [UserProfileInline,]
>         list_display = ('no', 'username', 'nickname', 'credit', 'leave',
> 'is_active', 'timestamp', 'ipaddress')
>
>         def credit(self, instance):
>                 return instance.get_profile().credit
>
>         def timestamp(self, instance):
>                 return instance.get_profile().timestamp
>
>         def ipaddress(self, instance):
>                 return instance.get_profile().ipaddress
>
>         def nickname(self, instance):
>                 return  instance.get_profile().nickname
>
>         def leave(self, instance):
>                 return instance.get_profile().credit - 1

-- 
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: a very simple beginners question

2012-05-02 Thread Scott Gould
Are you looking for custom management commands?

https://docs.djangoproject.com/en/dev/howto/custom-management-commands/

On May 2, 8:59 am, alon  wrote:
> running
>
> $python manager.py shell
>
> opens a python shell
> is there any way (a parameter) to make the manager run a python file
> with my commands??
>
> thanks

-- 
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 log lines spamming syslog

2012-03-23 Thread Scott Gould
Nail, meet head.

Thanks! I was thinking along similar lines but stupidly checked
everywhere (my code, apache confs, etc.) except the django source on
the server itself.

On Mar 23, 11:36 am, Reinout van Rees <rein...@vanrees.org> wrote:
> On 23-03-12 14:49, Scott Gould wrote:
>
>
>
> > Our syslog has been filling up for some time with this stuff and we
> > only just noticed due to logrotate breaking on us. For what appears to
> > be every django request across all virtual hosts, we are getting a
> > pair of lines, like so (blank lines inserted by me):
>
> > Jan 27 14:48:52 cloweb01 apache2: SessionMiddleware.process_request -
> > id 0x7f6dabfb35d0 - cookie None - session
> > 915ffaa7831b5de78876abb7746dfc1f - path /serverstatus/api/v1/status/
> > Jan 27 14:48:52 cloweb01 apache2: WSGIHandler.__call__ - id
> > 0x7f6dabfb35d0 - cookie None - session
> > 879f844cb6ea0213b445f60e11b22978 - path /serverstatus/api/v1/status/
>
> I looked at django/contrib/sessions/middleware.py and there's no logging
> or printing happening there.
>
> That the syslog ends up with this info probably means that django prints
> it out on the console, which would normally end up in your apache's
> error log. Probably you configured apache to send it to the syslog instead.
>
> Printing on the console means "print ..." or a logger that's configured
> to print to the console. Did you do the latter?
>
> My guess: someone put a print statement in
> django/contrib/sessions/middleware.py for debug purposes. So check the
> django that your site is using and see if you have to beat someone with
> a stout stick.
>
> Reinout
>
> --
> Reinout van Rees                    http://reinout.vanrees.org/
> rein...@vanrees.org            http://www.nelen-schuurmans.nl/
> "If you're not sure what to do, make something. -- Paul Graham"

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To 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 log lines spamming syslog

2012-03-23 Thread Scott Gould
Hi folks,

Our syslog has been filling up for some time with this stuff and we
only just noticed due to logrotate breaking on us. For what appears to
be every django request across all virtual hosts, we are getting a
pair of lines, like so (blank lines inserted by me):

Jan 27 14:48:52 cloweb01 apache2: SessionMiddleware.process_request -
id 0x7f6dabfb35d0 - cookie None - session
915ffaa7831b5de78876abb7746dfc1f - path /serverstatus/api/v1/status/
Jan 27 14:48:52 cloweb01 apache2: WSGIHandler.__call__ - id
0x7f6dabfb35d0 - cookie None - session
879f844cb6ea0213b445f60e11b22978 - path /serverstatus/api/v1/status/

Jan 27 14:48:54 cloweb01 apache2: SessionMiddleware.process_request -
id 0x7f6dab5abb10 - cookie 3f7dc260e50d4da7a6168627f087fa96 - session
3f7dc260e50d4da7a6168627f087fa96 - path /
Jan 27 14:48:55 cloweb01 apache2: WSGIHandler.__call__ - id
0x7f6dab5abb10 - cookie 3f7dc260e50d4da7a6168627f087fa96 - session
3f7dc260e50d4da7a6168627f087fa96 - path /

Jan 27 14:48:55 cloweb01 apache2: SessionMiddleware.process_request -
id 0x7f6dac318950 - cookie ad94336c4f21abd813f52d5a6f8d3f42 - session
ad94336c4f21abd813f52d5a6f8d3f42 - path /
Jan 27 14:48:55 cloweb01 apache2: WSGIHandler.__call__ - id
0x7f6dac318950 - cookie ad94336c4f21abd813f52d5a6f8d3f42 - session
ad94336c4f21abd813f52d5a6f8d3f42 - path /

There's nothing I'm aware of in my own code that's creating these
lines, and my knowledge about the inner workings of the various
components in play decreases as you move further away from Django.
Could anyone hazard a guess as to where this might be coming from? We
don't explicitly/knowlingly send anything to syslog from apache. The
vitals: Ubuntu 10.04, Apache/2.2.14, mod_wsgi 2.8, Python 2.6.5,
Django 1.2.

Thanks all.

-- 
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: Time duration in django models

2011-08-09 Thread Scott Gould
Nothing native. I'd store it in seconds, as an int, and let the model
convert to and from a timedelta. Looks like there's a snippet all
ready to go:

http://djangosnippets.org/snippets/1060/

On Aug 9, 6:32 am, Mohamed Ghoneim  wrote:
> Hey guys,
>
> I am just wondering if there is a time duration field in django models.
>
> what I want to do is a field that takes a time duration in days, hours,
> mins, seconds and store it into the database.
>
> --
> Mohamed Sayed Ghoneim

-- 
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: Accessing "request" from within an authentication backend

2011-07-26 Thread Scott Gould
I'd raise a custom exception (e.g. "PasswordExpiredError") and handle
the message creation in the view.

On Jul 26, 3:59 pm, Steven Smith  wrote:
> Is there a way to access the HttpResponse, or issue a redirect from
> within a custom authentication backend? I have Django hooked up to our
> Active Directory server, and it works perfectly except when the user's
> password expires or they have "User must change password at next
> login" set on their account. In these circumstances, I'd like to be
> able to spit out a message (using contrib.messages) stating that they
> are required to change their password, and then (ideally) issue an
> HttpResponseRedirect over to our "change password" website, which is,
> coincidentally, on the same Django system, so the message would carry
> over and stuff... but I need to be able to set it in the first place.

-- 
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: Selecting distinct months from a QuerySet

2011-05-19 Thread Scott Gould
I'd either add a manager with a method that did the query you describe
in SQL, or (if you're wanting the whole queryset anyway) just
calculate it via:

months = list(set(x.datetime_field.month for x in queryset))
months.sort()

On May 19, 1:03 am, Ian Turner  wrote:
> Hi,
>
> I would like to get a distinct list of months from a datetime field on an
> already defined QuerySet.
>
> SQL that I would use manually to get distinct from all records on the model.
> SELECT DISTINCT MONTH(`some_datetime_field`) as `month` FROM `some_model`
> ORDER BY `month`
>
> I don't need the year so .dates() gives me too much information to loop
> over.  Any ideas?

-- 
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: forms.ChoiceField get displayed value

2011-01-20 Thread Scott Gould
Try something like this:

field = form.fields['property']
data = form.cleaned_data['property']
if isinstance(data, (list, tuple)):
# for multi-selects
friendly_name = [x[1] for x in field.field.choices if x[0] in 
data]
else:
# for single selects
friendly_name = [x[1] for x in field.field.choices if x[0] == 
data]


On Jan 20, 9:25 am, Dan  wrote:
> If have a ChoiceField in a form (sometimes dynamically changed with
> javascript) when getting the cleaned_data for that field it will
> always return the value.
>
> i.e:
>
> 
> Property1
> 
>
> self.cleaned_data.get('property') will always return '1'
>
> How can i access the displayed value 'Property1' ?
>
> Thanks
>
> -Dan

-- 
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: A few beginner questions

2011-01-05 Thread Scott Gould
On Jan 4, 9:38 pm, Shawn Milochik  wrote:
> Hi Ondřej.
>
> ...
> #2: The validation should all be done during form validation[2], prior to 
> save. Using a Form or ModelForm. That way, the user can get friendly, useful 
> errors.

Further to this, look into model validation if the logic is integral
to the model:

http://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs#validating-objects

I tend to put the low-level logic in there, and have the forms handle
the errors raised from the model validation, rather than packing it
all into the form (if for no other reason than sometimes objects are
not created from forms!).

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



Re: auth_user first_name and last_name editing

2010-11-24 Thread Scott Gould
A simple custom ModelForm should do the trick:

from django.contrib.auth.models import User

class UserChangeForm(forms.ModelForm):
class Meta:
fields = ('first_name', 'last_name',)
model = User


On Nov 24, 1:33 pm, BozoJoe  wrote:
> HI,
>
> I'm using django-registration and django-profiles to handle user
> creation and adding additional profile fields.  However I'm at a lost
> as to how to allow the user to create/edit their first_name and
> last__name in the auth_user table?
>
> Do I need to do custom work to get a form for the user to create/edit
> their first/last name?   Obviously the admin panels allow this, but
> thats not acceptable for the common user of the website.
>
> Thanks

-- 
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: table namespace hygiene: should I try to rename auth_* tables, or should I use a separate database?

2010-11-01 Thread Scott Gould
> If not, I could create a new database, and devote it to the django
> stuff. Is that a good solution? Are there significant disadvantages to
> using a separate mysql database just for the django stuff? Is there
> maintenance overhead for the dba? (I don't know.) Are there any
> disadvantages, say, to doing trans-database joins, or having trans-
> database key constraints, vs. within a single database?

I am not a database expert -- only know enough to get by -- but as far
as I am aware MySQL does not support foreign keys across databases.
That is, you can put the auth system anywhere you like, but anything
that references the auth models will need to be in the same database,
directly or indirectly. Very likely a road you don't want to walk down.

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



Re: How to aggregate values by month

2010-10-28 Thread Scott Gould
Personally I hate writing raw SQL so I would probably try something
like this (untested):

sales = Sale.objects.filter(date_created__range=(init_date,ends_date))
.values(date_ created__month)
.aggregate(total_sales=Sum('total_value'))

sales_by_month = [(x.year, x.month, [y for y in sales if y.year ==
x.year and y.month == x.month])
for x in set([z.year, z.month for z in sales])]

Should give you a list of (year, month, subqueryset) tuples. Of
course, there might be performance issues with nested list
comprehensions like that depending on the size of the initial
queryset, but at least it's a one-line, SQL-free solution!

On Oct 28, 9:31 am, Rogério Carrasqueira
 wrote:
> Hello!
>
> I'm having an issue to make complex queries in django. My problem is, I have
> a model where I have the sales and I need to make a report showing the sales
> amount per month, by the way I made this query:
>
> init_date = datetime.date(datetime.now()-timedelta(days=365))
> ends_date = datetime.date(datetime.now())
> sales =
> Sale.objects.filter(date_created__range=(init_date,ends_date)).values(date_ 
> created__month).aggregate(total_sales=Sum('total_value'))
>
> At the first line I get the today's date past one year
> after this I got the today date
>
> at sales I'm trying to between a range get the sales amount grouped by
> month, but unfortunatelly I was unhappy on this, because this error
> appeared:
>
> global name 'date_created__month' is not defined
>
> At date_created is the field where I store the information about when the
> sale was done., the __moth was a tentative to group by this by month.
>
> So, my question: how to do that thing without using a raw sql query and not
> touching on database independence?
>
> Thanks so much!
>
> Rogério Carrasqueira
>
> ---
> e-mail: rogerio.carrasque...@gmail.com
> skype: rgcarrasqueira
> MSN: rcarrasque...@hotmail.com
> ICQ: 50525616
> Tel.: (11) 7805-0074

-- 
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: Access to field name in upload_to?

2010-10-26 Thread Scott Gould
> One idea would be to put 'fieldname' as the first parameter to the
> function, then use functools.partial [1] to create partial functions
> for each file field with the value set appropriately:
>
>         thumbnail_image = FileField(upload_to=partial(get_upload_path,
> 'thumbnail_image'))

Outstanding, thanks. I actually thought to myself "I need a decorator
type thing that I can pass a value with but still have it behave like
a callable" but didn't know about functools.partial.

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



Access to field name in upload_to?

2010-10-26 Thread Scott Gould
Hi folks,

I've got all my file uploads (that go to S3 as it happens, but I don't
think that's overly important) taking their path from one upload_to
delegate:

def get_upload_path(instance, filename=None):
"""
Defaults to appname/modelname/uuid.
"""
return "%s/%s/%s" % (
instance.__class__._meta.app_label,
instance.__class__.__name__.lower(),
instance.uuid)

That's obviously predicated on a field called "uuid" on any model that
uses this method for calculating the upload path. This works fine, but
I now want to deploy the same system on models with multiple
FieldFields. The way I'd like to extend this is by appending the field
name onto the existing file structure:

def get_upload_path(instance, filename=None):
return "%s/%s/%s/%s" % (
instance.__class__._meta.app_label,
instance.__class__.__name__.lower(),
instance.uuid,
APPROPRIATE_FIELD_NAME_HERE)

Which should result in something like "myapp/mymodel//
pdf_file" and "myapp/mymodel//thumbnail_image" given this
model:

class MyModel(models.Model):
pdf_file = FileField(upload_to=get_upload_path)
thumbnail_image = FileField(upload_to=get_upload_path)

Any ideas how I can get that field name inside the upload_to function?
Thanks!

-- 
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: Query field across multiple django models

2010-10-26 Thread Scott Gould
> Second, I'm not sure I understood the last part about getting the
> field within each model.

Sorry, I misread, thinking you were talking about having different
parameters of each model being responsible for what counted as
"latest". Bruno's solution looks good to me.

-- 
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: Query field across multiple django models

2010-10-26 Thread Scott Gould
Maybe -- in fact, almost certainly not -- the best way, but this is
how I do that kind of thing:

a_queryset = ModelA.objects.all()
another_queryset = ModelB.objects.filter.(by_something=True)
yet_another_queryset =
ModelC.objects.exclude(by_something_else=False)

from itertools import chain
big_honking_list = list(chain(a_queryset, another_queryset,
yet_another_queryset))
big_honking_list.sort(key=lambda x: x.updated)
big_honking_list.reverse()

As to your last question, that is easy if you're doing a list.sort()
-- just expose a method on each model that returns a sortable value
that is consistent across all the models. (Or write a dedicated
function to use instead of the lambda above, whichever makes more
sense.)

On Oct 26, 7:25 am, Ed  wrote:
> I want to create a "What's New" section that lists all of the database
> changes in the last day. I've added an "updated" field to my models:
>
> class Film(models.Model):
>    .
>    .
>    .
>    updated = models.DateTimeField(auto_now=True)
>
> class Actor(models.Model):
>    .
>    .
>    .
>    updated = models.DateTimeField(auto_now=True)
>
> Now I want to query across all of my models to get a date-sorted list
> of the most recent changes. How do I query the "updated" field across
> multiple models? Is this the most efficient way to achieve the primary
> purpose?
>
> What if I wanted to be more specific and list the actual field that
> was altered within each model?

-- 
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: call more than one view action from an uri path?

2010-10-21 Thread Scott Gould
What's your use case? Are "nest, pest and rest" always "nest, pest and
rest" -- or could they be "rest, pest and nest", or "nest, best, and
rest"?

If they're set in stone; that is, it's always nest, followed by pest,
followed by rest, then it's easy enough to just parameterize the url:

'/nest/(\d+)/pest/(\d+)/rest/(\d+)/'

and have your view delegate like so:

#using session
def myview(request, x, y, z):
nest(x)
pest(y)
rest(z)

#using return values
def myview(request, x, y, z):
nest(x, pest(y, rest(z)))

Even if the functions are variable, it should be easy to enough to
extend this approach accordingly.

On Oct 20, 6:51 pm, Phlip  wrote:
> Djangoistas:
>
> We want to call this URL:
>
>    http://www.server.com/nest/5/pest/6/rest/7
>
> We want each handler to call, with its argument, in order:
>
>   def nest(request, x):
>       ...
>   def pest(request, y):
>       ...
>   def rest(request, z):
>       ...
>
> (Internally, at rest() time, we want x and y to be available on some
> session or file-scope variable.)
>
> How to write an url() call in urls.py that handles part of a path, and
> then dispatches to the next part of the path, if any?
>
> --
>   Phlip
>  http://bit.ly/ZeekLand

-- 
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: Best way to change pk field type

2010-10-11 Thread Scott Gould
With a huge whopping disclaimer that I've never done this before:

Wouldn't you simply be abe to add an explicit "id =
BigIntegerField(primary_key=True)" to the model and change the column
type accordingly in mysql?

On Oct 7, 4:16 pm, indymike  wrote:
> Here's my issue - I'm going to run out of integers for my primary key
> in one of my tables.  I'm using MySQL, which has been absolutely
> fantastic, and will for at least a few more decades if I can make a
> change from INT to BIGINT.
>
> What's the right way to switch from INT to BIGINT so the PK works
> correctly?
>
> / First thought was a big, fat south migration, but I I wonder if
> there's anything in Django's code that this will break?

-- 
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 regroup not working as expected

2010-10-07 Thread Scott Gould
Your .list is in the wrong place:


{% for date in sale_list%}
{{ date.grouper }}

{% for sale in date.list %}
 {{ sale.item }} - {{ sale.qty }} 
{% endfor %}


{% endfor %}


Regards
Scott

On Oct 5, 2:28 pm, Gath  wrote:
> Guys
>
> I have the following view in my django application
>
> def ViewSale( request ):
>     salecur = Sale.objects.filter(user=2).order_by('sale_date')
>     return render_to_response('myapp/sale.html',{'salecur':salecur})
> my template looks like this
>
> {% regroup salecur by sale_date as sale_list %}
>
> 
>     {% for sale_date in sale_list.list %}
>     {{ sale_date.grouper }}
>     
>         {% for sale in sale_list %}
>          {{ sale.item }} - {{ sale.qty }} 
>         {% endfor %}
>     
>     
>     {% endfor %}
> 
>
> When i render the page i get the grouper sale_date.grouper printed,
> but {{ sale.item }} and {{ sale.qty }} in the inner loop shows
> nothing! Blank.
>
> What am i missing?
>
> Gath

-- 
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: convert list into a comma separated string

2010-10-04 Thread Scott Gould
Python has you covered:

my_string = ",".join(my_list)

HTH,
Scott

On Oct 4, 7:41 am, ashy  wrote:
> Hi All,
>
> I am writing a django function in which I have a following list:
> li = ['a','b','c']
> I want to create a string from the list which should look like
> str = 'a,b,c'
>
> I plan to pass this string to not in () function of my sql query.
>
> Any Ideas?
>
> thanks
>     ashy

-- 
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: Python unexpectedly quit

2010-09-24 Thread Scott Gould

> def logout(request):
>     logout(request)

Infinite loop, no?

-- 
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: Possible to have dynamic drop down list in ModelForm?

2010-09-20 Thread Scott Gould
Two ways, both requiring javascript:

1. Populate the city dropdown via ajax on country change.
2. Have your template write javascript to do country->city lookups and
alter the contents of the city dropdown on country change.

On Sep 19, 2:42 am, Andy  wrote:
> I have a model FieldReport that has, among other fields, these two
> fields:
>
> -country
> -city
>
> Both "country" and "city" are lists of choices.
>
> I want to have a form FieldReportForm as a ModelfForm based on the
> model FieldReport. I want to have "country" and "city" represented as
> drop down lists. Moreover, "city" should be a dynamic list based on
> the selected value of "country".
>
> For example, if someone selects the value "US" for "country", then
> "city" should be a list of US cities only, all cities in other
> countries shouldn't be loaded onto that list.
>
> Is this something that would work with Django's ModelForm? How would
> you implement something like this?
>
> Thanks.

-- 
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 IDs for upload_to path

2010-09-14 Thread Scott Gould
Your ID: if it's a new object, you can't.

Another field in the model: if it's calculated instead of database-
provided, sure. I use UUIDs for this:

def get_uuid():
import uuid
return str(uuid.uuid4())

class UploadedFileModel(models.Model):
physical_file = FileField(verbose_name='Physical File',
max_length=200, upload_to=get_upload_path)
uuid = models.CharField(max_length=36, default=get_uuid,
editable=False)


On Sep 13, 8:27 am, Tereno  wrote:
> Hi there, I've an ImageField and it requires a upload_to path or a
> callable. From what I read in the docs, the callable takes two
> arguments, one of which is the instance of model. It is stated that
> the model may not have been saved in the database at this point and
> thus, we cannot assume to obtain a valid id number. How would I be
> able to save an image in a path that is related to my id or another
> field within the model?
>
> Thanks!

-- 
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: Alternative to passing request object to every object/function?

2010-09-02 Thread Scott Gould
Have a read through this article, Dan:

http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/

On Sep 2, 11:19 am, Dan Klaffenbach 
wrote:
> On 2 Sep., 16:48, Daniel Roseman  wrote:> It's not 
> clear exactly what you want. Using RequestContext and the
> > request context processor will ensure that the request is present in
> > all your templates. Is that enough?
>
> No. I'll give an example:
>
> I use a custom Acl class for checking the user's permissions (main
> idea: RBAC-like, with role and permission inheritance). Let's say I
> have a form model:
>
> I need the request.user e.g in my application's form models, because I
> need to create an Acl instance in the model in order to check if the
> user can edit fields or not. There are three cases:
> * user can edit form field
> * user can view value (form widget attribute = readonly)
> * user is not allowed to view field at all (do not add element to the
> form at all)
>
> Isn't there any other way to get at least the currently logged in user
> ('REMOTE_USER') in models? Passing the request parameter to models
> doesn't seem like good style to me, it bloats the code and makes it
> harder to read. I do not need the request object in my templates (I
> know this is possible), just in e.g. form models.
>
> Regards,
> Dan

-- 
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: Prepopulate some fields in a admin add form

2010-08-23 Thread Scott Gould
First, just to make absolutely clear you understand, the "user's name"
isn't the foreign key itself -- that would be the user's ID. The
user's name is what would be displayed to help you *select* the
correct ID, under the hood.

To the question at hand, it's quite simple to add a method to your
ModelAdmin class that will act on the foreign key field for your user:

http://docs.djangoproject.com/en/1.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey

On Aug 21, 2:59 am, gondor  wrote:
> I have a simple admin model for inputting a note with a date into the
> database.  In addition to that I want to prepopulate with the users
> name when the add new entry button is clicked.  The users name is a
> foreign key to the user table.
>
> Does anyone know how to do that?
>
> Any help is appreciated.
>
> Thank you

-- 
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: What is the best way to manually create an HTML form from a ModelForm

2010-08-23 Thread Scott Gould
You can refer to individual fields by name, for example:

> 
>     {% form.first_name %}
> 

Looping through them works fine for simple forms but as you say, if
you want something more elaborate in your template, you sometimes need
to go field-by-field.

What I do is write an inclusion tag with all the markup I want for my
fields, automatic outputting of css classes matching the widget type
so I can style them, etc. and then pass the field as the argument:

{% my_inclusion_tag form.first_name %}

On Aug 22, 10:47 pm, orokusaki  wrote:
> Normally, I would do something like this:
>
> {% for field in form.fields %}
> 
>     {% field %}
> 
> {% endfor %}
>
> What if I need:
>
> 
>     {% one field %}
> 
>
> 
>     Some Title
>     
>     {% another field %}
>     
> 
>
> I want to be able to still use model forms and I don't want to hard
> code {% if field == "email" %}Custom Stuff{% endif %}. Is there a good
> way to do this, or a convention that I can use to ensure that my HTML
> won't stop working when I update Django (I know that there is the
> id_field_name convention, but I'm looking for a little more insight if
> anyone out there does this alot.

-- 
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: multiple forms for same model

2010-08-16 Thread Scott Gould
You'll want to call is_valid() only if the request.method is "POST",
plus your code leaves the possibility of an error if none of those
permissions is found (your elif should probably simply be an else?).

On Aug 16, 6:49 am, Mess  wrote:
> Hi,
>
> I have a model where different users should have different
> possibilities to edit, i.e. admin should be able to edit everything,
> but users should only be able to edit certain fields.
>
> My problem is that the user form doesn't validate when submitting
> update as a user. But I get the error that the fields are missing even
> though I can see them redisplayed.
>
> I am looking at this 
> tutorial:http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#using-a...
> And I don't get what is different in my example since I pass "instance
> = c" which contains the missing fields.
>
> def update_contract(request,c):
>         if request.user.has_perm("contracts.is_admin") or
> request.user.has_perm("contracts.is_internal"):
>             contract_form = ContractForm(request.POST, instance = c)
>         elif
> request.user.has_perm("contracts.is_external"):
>               contract_form = ContractFormExternal(request.POST,
> instance = c)
>         if contract_form.is_valid():
>             contract_form.save()
>             return view_contract_details(request, c.pk, True)
>         else:
>             return render_to_response('contracts/
> view_contract_details.html', {
>                 'info_message' : 'Please correct the data in the
> form',
>                 'contract_form': contract_form,
>                 'contract_id' : c.pk,
>             },context_instance=RequestContext(request))
>
> Anyone can hint as to where it goes wrong or a hint to how to better
> accomplish this?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-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: ManyToManyField limiting choices

2010-08-10 Thread Scott Gould
Define a custom ModelForm for your model that sets the appropriate
queryset parameter (either altering the field in __init__, or just
defining the field in the class as a ModelMultipleChoiceField). Then
register that ModelForm for use in the admin (via a ModelAdmin class).

On Aug 9, 7:51 pm, Martin Tiršel  wrote:
> Hello,
>
> I have a gallery model and an image model. First, I create some galleries,  
> then I insert images into them. But now, I want to add multiple thumbnails  
> feature for galleries (thumbnails representing the gallery, not thumbnails  
> for images inside gallery), so I added ManyToManyField and I can select  
> some images, which will be used as thumbnails. But is there a way, how can  
> I limit these images only to images belonging to the currently editing  
> gallery?
>
> There is the limit_choices_to option, but I would need to point to 'self',  
> what is not possible on this place. Second problem would be that I have to  
> create gallery first, then insert images and then select thumbnails, so  
> there is another problem, that if there would be a solution in limiting  
> the image list, I can not use it in create gallery page in admin.
>
> What is the best way to solve this problem?
>
> Thanks,
> Martin

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



Re: How to get the model name of an object in template?

2010-08-04 Thread Scott Gould
Not that I'm aware of, in which case I'd say a tag (or even a filter)
*is* the "built-in way". No great hardship:

@register.filter
def class_name(value):
return value.__class__.__name__


On Aug 4, 11:13 am, "David.D" <dengyuanzh...@gmail.com> wrote:
> There's no django's built-in way?
>
> On Aug 4, 10:37 pm, Scott Gould <zinck...@gmail.com> wrote:
>
>
>
> > How about writing a simple template tag that takes an object and
> > returns object.__class__.__name__?
>
> > On Aug 4, 10:20 am, "David.D" <dengyuanzh...@gmail.com> wrote:
>
> > >  I did it by adding this to my models:
> > >         def get_model_name(self):
> > >                 return self.__class__.__name__
>
> > > And it works
>
> > > But I don't want to define the 'get_model_name' method in my model.
>
> > > Is there a built-in way?
>
> > > Thanks.

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



Re: How to get the model name of an object in template?

2010-08-04 Thread Scott Gould
How about writing a simple template tag that takes an object and
returns object.__class__.__name__?

On Aug 4, 10:20 am, "David.D"  wrote:
>  I did it by adding this to my models:
>         def get_model_name(self):
>                 return self.__class__.__name__
>
> And it works
>
> But I don't want to define the 'get_model_name' method in my model.
>
> Is there a built-in way?
>
> Thanks.

-- 
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: values with distinct not working as expected

2010-07-30 Thread Scott Gould
You don't need order_by to get distinct values per se, but in this
case you need to put it in to override whatever default ordering you
have on your model (since any order_by fields will be included in the
query and thwart your distinct()).

On Jul 30, 3:52 am, tuxcanfly  wrote:
> Thanks, that works!
>
> But I don't understand why I should order_by to get distinct values.
>
> On Jul 29, 3:59 pm, Subhranath Chunder  wrote:
>
>
>
> > If you don't want to uniquify yourself, then why not simply do:
> > User.objects.values('username').order_by('username').distinct()
>
> > or, going the way that were already heading, it would be:
> > Visitor.objects.values('user__username').order_by('user__username'').distin 
> > ct()
>
> > Thanks,
> > Subhranath Chunder.
>
> > On Thu, Jul 29, 2010 at 2:29 PM, tuxcanfly  wrote:
> > > I have this:
>
> > > class Visitor(models.Model):
> > >    user = models.ForeignKey(User)
> > >    ..
> > >    ..
>
> > > I'm trying to get the distinct usernames, so I did this:
>
> > >    Visitor.objects.values("user__username").distinct()
>
> > > But this stil gives me duplicate usernames. Of course I could use a
> > > flat values_list  and uniquify the result, but...
>
> > > --
> > > 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 > >  groups.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.



Re: single point of entry to a webpage

2010-07-26 Thread Scott Gould
I often cringe it when people trot out the "read the docs" line, but
that's honestly what it comes down to in this case. An app isn't some
sacred walled city. Just write a template tag, import whatever you
need from whichever apps they belong to, and stick it on the page.

But before you do that, read the following:

http://docs.djangoproject.com/en/1.2/howto/custom-template-tags/#howto-custom-template-tags

On Jul 26, 12:00 pm, owidjaya  wrote:
> how do i write custom template tag that is available to all my apps.
> not tied to a particular app?
>
> On Jul 26, 7:05 am, bruno desthuilliers
>
>
>
>  wrote:
> > On 25 juil, 00:25, owidjaya  wrote:
>
> > > if i have a page with sections say the home page. It has section for
> > > news, it has section for blog, comments and etc.
> > > I have apps for every one of those section. Now how do i add the
> > > output of the view for each of those apps on the same page?
>
> > You don't. A Django "view" is just a callable that takes an HTTP
> > request and returns an HTTP response. The solution to your problem is
> > to write custom templatetags for news, blog, comments etc and call
> > these templatetags from the templates that needs them.
>
> > HTH

-- 
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: filter users by full name

2010-07-22 Thread Scott Gould
It won't work because there's no database column that corresponds to
the full name.

A simple but limited alternative would be to split the string on " "
and use the result as first_name and last_name, but you would probably
want to take into account first_names and/or last_names with
legitimate spaces in them (e.g. "Mary Ann" or "van der Waal", perhaps
by compiling a list of each possible configuration and using that to
filter on with first_name__in and last_name__in.


On Jul 22, 2:06 pm, Matias  wrote:
> Hi,
>
> What is the recommended way to get all the users whose full_name matches
> a given string?
>
> I need to do something like:
>
> User.objects.filter(get_full_name="John Test")
>
> But that doesn't seem to work.
>
> Is list comprehensions the only way to go?

-- 
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: distinct() ?

2010-07-21 Thread Scott Gould
Does your model refer to any other fields for its default ordering?

http://docs.djangoproject.com/en/1.2/ref/models/querysets/#distinct


On Jul 21, 1:06 pm, rmschne  wrote:
> I'm trying to use the distinct() and it's giving me unexpected
> results.  Surely it's something simple, but I can't spot it.
>
> I've referred 
> tohttp://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct
>
> In SQL, it would be:
> select distinct status from members;
>
> in Django I am using:
> statuscodes=Member.objects.values('status').distinct()
>
> With SQL I get the four distinct values of status from the database I
> expect.
>
> In Django, I get back a dictionary with every record.  I'm expecting
> only the four distinct records.
>
> Any thoughts on what i'm doing wrong?
>
> Thanks!

-- 
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: best practice for widget that edits multiple model fields

2010-07-21 Thread Scott Gould
I'd definitely go that route (I think the "serialized data" bit in
your first post made me think you wanted to just wrap it up and be
done with it).

I'd probably even make it a OneToOneField instead of a ForeignKey to
reinforce the concept that an EventDateRange is a dedicated satellite
bit of data to a discrete Event, and just include it in the Event's
form structure as an inline. You also get an in-built interface of
"event.eventdaterange" instead of mucking around with, or aliasing,
"event.eventdaterange_set.all[0]".

On Jul 21, 9:38 am, Brad Buran <bbu...@alum.mit.edu> wrote:
> <<Sorry, last post was incomplete.  Accidentally hit send while composing.>>
>
> Hi Scott:
>
> Thank you for the suggestion.  I reviewed the docs, and it appears like it
> could work but would restrict the functionality.  For example, I would have
> to somehow serialize two datetime types plus a boolean type into a single
> database column.  This would take away a lot of advantages (such as being
> able to filter based on only one of the datetimes).
>
> One other option I am exploring is simply doing:
>
> class DateRange(Model):
>     start = DateTimeField()
>     end = DateTimeField()
>     all_day = BooleanField()
>
> # subclass DateRange so we can reuse it in various models
> class EventDateRange(DateRange):
>     date = ForeignKey(Event)
>
> class Event(Model):
>     #various other fields required for event
>
> Does this seem like it would make more sense?
>
> Thanks,
> Brad
>
>
>
> On Wed, Jul 21, 2010 at 8:03 AM, Scott Gould <zinck...@gmail.com> wrote:
> > My immediate thought upon reading your post was that you should build
> > an accompanying custom model field. Having said that, I haven't had
> > cause to do one that involved (only extend -- simply -- the stock
> > fields) so can't provide any specifics.
>
> >http://docs.djangoproject.com/en/1.2/howto/custom-model-fields/#howto...
>
> > On Jul 20, 10:00 pm, Brad Buran <bbu...@alum.mit.edu> wrote:
> > > I have a group of fields (date_start, date_end, all_day) that I would
> > like
> > > to reuse in several models.  I've defined a MultiWidget that displays two
> > > split datetime fields plus a checkbox (for the all_day toggle).  However,
> > > I'm not sure how to get the MultiWidget to set the value of these three
> > > fields in the model.  If I understand correctly, a MultiWidget can only
> > set
> > > the value of a single model field.  Hence, I would need to create some
> > sort
> > > of field (e.g. "combined_date_info") that MultiWidget saves the
> > serialized
> > > data from these three form fields.  Once I have done this, then I would
> > use
> > > model.save() to deserialize the data in the combined_date_info field and
> > > save it to the appropriate model fields.
>
> > > This solution seems a bit hackish and not very DRY.  Are there better
> > > approaches?
>
> > > Brad
>
> > --
> > 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<django-users%2bunsubscr...@google 
> > groups.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.



Re: best practice for widget that edits multiple model fields

2010-07-21 Thread Scott Gould
My immediate thought upon reading your post was that you should build
an accompanying custom model field. Having said that, I haven't had
cause to do one that involved (only extend -- simply -- the stock
fields) so can't provide any specifics.

http://docs.djangoproject.com/en/1.2/howto/custom-model-fields/#howto-custom-model-fields

On Jul 20, 10:00 pm, Brad Buran  wrote:
> I have a group of fields (date_start, date_end, all_day) that I would like
> to reuse in several models.  I've defined a MultiWidget that displays two
> split datetime fields plus a checkbox (for the all_day toggle).  However,
> I'm not sure how to get the MultiWidget to set the value of these three
> fields in the model.  If I understand correctly, a MultiWidget can only set
> the value of a single model field.  Hence, I would need to create some sort
> of field (e.g. "combined_date_info") that MultiWidget saves the serialized
> data from these three form fields.  Once I have done this, then I would use
> model.save() to deserialize the data in the combined_date_info field and
> save it to the appropriate model fields.
>
> This solution seems a bit hackish and not very DRY.  Are there better
> approaches?
>
> Brad

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



Re: forms

2010-07-20 Thread Scott Gould
First things first:

1. Do you have a Model for your data?
2. Is your form a ModelForm attached to this Model?

On Jul 20, 2:14 pm, commonzenpython  wrote:
> VolunteerForm is the name of my form class in forms.py, i put the code
> you gave me :
>
> if request.POST:
>         form = VolunteerForm(request.POST)
>         if form.is_valid():
>             fm = form.save()
>
> in my views.py
>
> when i visit the url, i get the form , but when i submit information,
> i get a 500 error, and django sends me a message that says
>  AttributeError: 'VolunteerForm' object has no attribute 'save'

-- 
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: ordering a model on multiple fields?

2010-07-15 Thread Scott Gould
The Django *admin* only uses one field, ever.

Bit of an irritating limitation, I grant you, but with the use of date
hierarchies and list filters it's not too bad.

On Jul 14, 7:40 pm, hjebbers  wrote:
> is there a way to have a model class sorted on multiple fields?
> in the meta class of my models I set the ordering, but django uses
> only the first field for ordering;
> a second field is just ignored.
>
> (I am aware that if a users starts to sort using table headers in the
> admin interface only one field will be used. It would just be great to
> have the initial ordering on 2 fields.)
>
> kind regards, henk-jan ebbers

-- 
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: Silly Question? Mulitple Checkbox Processing

2010-07-13 Thread Scott Gould
Try it and see :)

If the checkboxes share the same name (as in the name attribute of the
input tag), then the checked ones' values form a comma-delimited list.

On Jul 13, 11:19 am, zippzom  wrote:
> Maybe this is a silly question, but if I have a form with multiple
> checkboxes that are outputted by a for loop, how is the data passed in
> the POST?
>
> Is it like a dictionary?

-- 
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: __init__ custom form validation

2010-07-13 Thread Scott Gould
Your init is expecting a value for field3_type, so you need to provide
it when you create the form in your view (prior to request.POST in the
postback instance).

On Jul 12, 2:44 pm, Nick  wrote:
> I am working on a validation that will require a field be filled in if
> it is another field enters on of three values:
>
> For example:
>
> I have a form
>
> class myform(forms.Modelform):
>     field1 = forms.CharField
>     field2 = forms.Charfield
>     field3_type = forms.CharField(choices=choices)
>     field3 = forms.DateTimeField(required=True)
>
>     def __init__(self, field3_type, *args, **kwargs):
>         super(myform, self_.__init__(*args, **kwargs)
>         if field3_type in ('option 1', 'option 2', 'option 3'):
>             self.field['field3'] = forms.DateTiemField(required=False)
>
> The view:
> if request.method == 'POST':
>             form = myform(request.POST)
>             field3_type = form.cleaned_data['field3_type']
>             if form.is_valid():
>             # some form processing
> else:
>            form = myform()
>
> When i try to use the form I get an error at the myform() line stating
> that __init__ takes exactyl 2 arguments and only 1 is given.
>
> Any thoughts?

-- 
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: Deployment Permissions

2010-06-28 Thread Scott Gould
As long as the last number is 4 or greater (at least read access for
all) you should be fine.

Regards
Scott

On Jun 27, 5:50 am, Rusty Shackleford 
wrote:
> Hi,
>
> I'm about to deploy my first Django app, but I have a few questions
> about permissions.
>
> The project container is at '/usr/local/sites' with '775 root www-
> data'.
>
> I have the project stored at '/usr/local/sites/project'  with '755 www-
> data www-data'.
>
> I have NGINX aliased to '/usr/local/sites/project/static' with '755
> www-data www-data' for static content.
>
> Are these permissions reasonable?
>
> Rusty

-- 
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: outer join in orm

2010-06-21 Thread Scott Gould
There may well be a better way to do this, especially since it's been
a good year since I was struggling with this myself. (Very similar
case to yours, different subject matter of course.)

The way I ended up doing it was to use a template tag and some list
comprehensions to whittle things down. E.g.:

questions = Questions.objects.all()
answers = Answers.objects.filter(candidate=my_candidate)

questions_and_answers = [(q, [a for a in answers if a.question = q])
for q in questions]

...which should give you a list of (question, )
tuples.


On Jun 21, 10:00 am, JeffH  wrote:
> To clarify: Each race has a set of questions. The candidate may have
> responded to none, some, or all. The answers are linked to the
> candidate (and to the question). For each candidate, I want to display
> all the questions, with or without answer. The way it works currently,
> only the questions with answers get displayed.
>
> On Jun 21, 8:41 am, Daniel Roseman  wrote:
>
>
>
> > On Jun 21, 12:51 pm, JeffH  wrote:
>
> > > I have some models that (simplified) look like the following.
>
> > > class Answer(models.Model):
> > >     id = models.CharField(max_length=32, primary_key=True)
> > >     text = models.TextField(blank=False)
> > >     question = models.ForeignKey(Question)
> > >     candidate = models.ForeignKey(Candidate)
>
> > > class Question(models.Model):
> > >     id = models.CharField(max_length=32, primary_key=True)
> > >     text = models.TextField(blank=False)
>
> > > class Candidate(models.Model):
> > >     id = models.CharField(max_length=32, primary_key=True)
> > >     name = models.CharField(max_length=32, blank=False)
>
> > > class Race(models.Model):
> > >     id = models.CharField(max_length=32, primary_key=True)
> > >     name = models.CharField(max_length=128, blank=False)
> > >     questions = models.ManyToManyField(Question)
> > >     candidates = models.ManyToManyField(Candidate)
>
> > > So, a Race has Candidates and Questions, and a Candidate has Answers.
> > > Each answer is associated with a Question and a Candidate. Displaying
> > > the question associated with an answer is easy:
>
> > > # context variable in view
> > >     answers = Answer.objects.filter(candidate=candidate)
>
> > > # template code
> > >     
> > >     {% for answer in answers %}
> > >     
> > >         {{answer.question.text}}
> > >         {{answer.text}}
> > >     
> > >     {% endfor %}
> > >     
>
> > > From the point of view of the Candidate, I need to display all the
> > > questions, including the ones without Answers. I know how to to do
> > > this using raw sql and an outer join. How to do it in the orm?
>
> > > Thanks in advance for any ideas.
>
> > > --Jeff
>
> > Not quite enough information here to answer. What are you wanting to
> > join? If you just want to display all the questions, why do you need a
> > join at all?
> > --
> > DR.

-- 
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: not able to recognize non-default python files in app + project directory

2010-06-11 Thread Scott Gould
Apologies for the "__initial__" stuff -- damn iPhone autocomplete!

On Jun 11, 11:15 am, rahul jain  wrote:
> It was rw-r--r-- . I also modified it to 777 by" chmod -R 777". But
> did not fix my problem.
>
> This is the error which I am getting
> ImportError: cannot import name 
>
> --RJ
>
>
>
> On Fri, Jun 11, 2010 at 7:59 AM, Tom Evans  wrote:
> > On Fri, Jun 11, 2010 at 3:47 PM, rahul jain  wrote:
> >> Hi Tim,
>
> >> Here is my structure
>
> >> app
> >> |-- __init__.py
> >> |-- models.py (all  my models)
> >> |-- auth.py  (python functions referencing models defined in models.py)
> >> |-- blogs.py (python functions referencing models defined in models.py)
> >> |-- views.py (python functions referencing models defined in models.py)
>
> >> for auth.py and blogs.py referencing is giving import error.
>
> >> Again in these files. If I do import like
>
> >> from app.models import User then I get import error.
>
> >> For views.py I am able to easily import @above.
>
> >> --RJ
>
> > That all looks correct. Are the file permissions correct?
>
> > Can you show 'ls -l /path/to/app/' please.
>
> > Cheers
>
> > Tom
>
> > --
> > You received this message because you are subscribed to the Google Groups 
> > "Django users" group.
> > To post to this group, send email to django-us...@googlegroups.com.
> > To unsubscribe from this group, send email to 
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group 
> > athttp://groups.google.com/group/django-users?hl=en.

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



Re: annotate with query set for distinct values

2010-06-11 Thread Scott Gould
It's not really a matter of "working around" it. Your .xxx method/
property is an attribute of the object. What you evidently want from
the database is *not* a list of those objects, but rather a summary
representation of them. Trying to apply your .xxx is meaningless as
you don't have a discrete object to apply it to. If it *is* supposed
to be meaningful in that context, then it's probably the sort of thing
that belongs in a manager.

If you can tell us a bit more about what .xxx actually is, or is
supposed to do, then we might be able to come up with an alternate
solution.

Regards
Scott


On Jun 10, 5:42 pm, SlafS  wrote:
> Yes, I'm aware of the background of the problem but i was wondering if
> I can somehow "workaround" it.
>
> Thanks for Your help
>
> On 10 Cze, 23:34, Dan Harris  wrote:
>
>
>
> > The problem is the GROUP BY you are looking to get. The problem with
> > doing a group by you don't get the whole object which is what the
> > Django queryset is trying to return:
>
> > res = queryset.annotate(Count("name"))
>
> > This will give you a result set that you want and you can iterate over
> > like:
>
> > {% for r in res %}
> >    {{ r.name }} - {{ r.name__count}}
> > {% endfor %}
>
> > however there may be duplicated {{ r.name }}
>
> > Dan Harris
> > dih0...@gmail.com
>
> > On Jun 10, 5:24 pm, SlafS  wrote:
>
> > > Thanks.
>
> > > I've already tried that but this isn't quite what i'm looking for. As
> > > u wrote this returns a list, but I would like to obtain my calculated
> > > property when I'm iterating over this. Like so (let's say the result
> > > is in res variable) :
>
> > > {% for r in res %}
> > >    {{r.xxx}} - {{r.name__count}}
> > > {% endfor %}
>
> > > I'm starting to think that there's no such nice way to acheive that :/
>
> > > On 10 Cze, 23:06, Dan Harris  wrote:
>
> > > > Here is an example:
>
> > > > # In models.py
> > > > class TestModel(models.Model):
> > > >    name = models.CharField()
>
> > > > # Get a listing of unique names and their counts
> > > > # In some view
> > > > from django.db.models import Count
>
> > > > TestModel.objects.values("name").annotate(Count("name"))
>
> > > > This will return a list of the form:
>
> > > > [{'name__count': 2, 'name': u''}, {'name__count': 1, 'name':
> > > > u'bbb'}]
>
> > > > Hope this helps!
>
> > > > Dan Harris
> > > > dih0...@gmail.com
>
> > > > On Jun 10, 5:01 pm, SlafS  wrote:
>
> > > > > Hi there!
> > > > > I have a question. If i have a model with some fields (let's say all
> > > > > CharFields named aaa,bbb,ccc etc. and some calculated properties named
> > > > > xxx and zzz) how can I obtain something similar to
>
> > > > > "SELECT aaa, count(aaa) FROM my_model_table GROUP BY aaa;"
> > > > > i.e. a list of - lazy loaded - objects with distinct aaa values and an
> > > > > extra column which indicates how many entries of a specific aaa are in
> > > > > the table.
>
> > > > > I would like to acheive that with QuerySet and annotate so that I can
> > > > > get a list of objects to use their other properties (xxx or zzz) e.g.
> > > > > in my template
>
> > > > > Regards

-- 
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: not able to recognize non-default python files in app + project directory

2010-06-11 Thread Scott Gould
Did you put Test1.py and Test2.py into a "models" directory where
models.py would normally be, and add an __initial__.py file to it?

On Jun 10, 5:18 pm, rahul jain  wrote:
> HI Dan,
>
> Thanks for your response but that will not solve my problem.
>
> I am not splitting models. I am splitting actions defined in the
> models  across multiple files.
>
> So suppose
>
> one of my model actions is calling which in turn calls the constructor
> or simple functions defined in normal python files
>
> for ex:
>
> def action (self, request, queryset):
>
>     Test1()     //calls default constructor of the class
>     Test2()
>
> Now each of these are separate class files names as Test1.py Test2.py.
>
> In each of these files i want to do this
>
> from ..models import 
>
> But I get this error
>
> ImportError: cannot import name 
>
> I tired various other variotions like just
>
> from models import 
>
> from .models import 
>
> or without from
>
> but none of them are working.
>
> Also, in order to call this Test1() I thought if  I import
> Test1 in models then it will just work but again not
>
> --RJ
>
>
>
> On Thu, Jun 10, 2010 at 1:57 PM, Dan Harris  wrote:
> > When you split things out into multiple files or directories you have
> > to remember to import them into the models.py file or the __init__.py
> > file (if using a directory).
>
> > So if i had some models in a new file "extraModels.py" for example
>
> > # In extraModels.py
> > class ExtraModel(models.Model):
> >    pass
>
> > Then in the regular "models.py"
>
> > # In models.py
> > from extraModels import ExtraModel
>
> > class RegularModels(model.Model):
> >   pass
>
> > The key is that you ahve to import any models in your split files into
> > your normal models.py file. This is because Django looks for models in
> > the models.py file only. If you make a models directory, you have to
> > import all models you want Django to recognize into your __init__.py
> > file within the models directory.
>
> > Hopefully this makes sense, if not I can try to be more clear.
>
> > Dan Harris
> > dih0...@gmail.com
>
> > On Jun 10, 4:46 pm, rahul jain  wrote:
> >> anyone on this ??
>
> >> --RJ
>
> >> On Thu, Jun 10, 2010 at 11:34 AM, rahul jain  
> >> wrote:
> >> > Hi Django,
>
> >> > In my app directory, I splitted my models and views.py into multiple
> >> > files since they start becoming very long but django is not able to
> >> > recognize those files .
> >> > It only recognizes models.py, views.py, tests.py (default ones).
>
> >> > So In my other files If i do this
>
> >> > from ..models import 
>
> >> > I get this error
>
> >> > ImportError: cannot import name 
>
> >> > If I do the same on views.py, it just works fine.
>
> >> > Even on Eclipse I can see Django default files with different symbol
> >> > and python files with different symbols.
>
> >> > How to solve this problem ?
>
> >> > --RJ
>
> > --
> > You received this message because you are subscribed to the Google Groups 
> > "Django users" group.
> > To post to this group, send email to django-us...@googlegroups.com.
> > To unsubscribe from this group, send email to 
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group 
> > athttp://groups.google.com/group/django-users?hl=en.

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



Re: ordering integers with regroup

2010-06-09 Thread Scott Gould
If you're ordering on "District 1", "District 2", etc. then the number
is part of a string and will be sorted alphabetically. I image your
only recourse will be to use the numeric field directly, and deal with
prepending "District " to it in some other fashion.

On Jun 9, 10:38 am, Nick  wrote:
> Has anyone come across an ordering issue with the regroup tag whereby
> if the field that is being ordered is an integer you get the following
> problem:
>
> say you have the grouped field "District" and the following groupings
>
> District 1
> District 2
> District 3
> District 10
> District 14
> District 20
> District 29
> District 30
>
> Their ordering will come out:
>
> District 1
> District 10
> District 14
> District 2
> District 20
> District 29
> District 3
> District 30
>
> I can see why this is happening, but how do I tell the regroup tag to
> sort as though 1 were 01, etc. Adding a 0 to the front isn't really an
> option as their are thousands of records that reach from 1 - 250
>
> Thanks in advance.

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



Ensuring a single file in storage, per FileField

2010-06-04 Thread Scott Gould
Hi folks,

I have various models with File and Image fields. I want to keep the
filesystem storage clean, removing any orphaned file upon a new one
being uploaded. To date I've been overriding save() in each model,
which isn't terribly robust:

class MyModel
def save(self, **kwargs):
# remove old file if new one is uploaded
old_obj = MyModel.objects.get(pk=self.pk) if self.pk else None
if old_obj and self.image != old_obj.image:
old_obj.image.storage.delete(old_obj.image.name)

super(MyModel, self).save(**kwargs)

For obvious reasons I'd like to refactor this into a custom FileField/
ImageField. The logic that I would like is even simpler and more
reliable than the above:

1. If a new file was provided, delete the old one.
2. Save.

The trouble is I can't figure out how, at the Model or Field level, to
figure out if a new physical file was *really actually provided*, in
order to decide whether I should delete the underlying old one.

Thanks for any help on this one.

Regards
Scott

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



Re: How to dynamically set limit_choices_to for ManyToManyField using values from an instance?

2010-06-04 Thread Scott Gould
Create a ModelForm for your model (A), set the queryset to what you
want on the appropriate field (n), and then register that ModelForm
for admin use in your admins.py.

Regards
Scott


On Jun 4, 6:14 am, Massimiliano della Rovere
 wrote:
> When displayed in the Admin interfaces, I'd like to filter the values
> of n, so that instances of N already linked to other instances of A
> sharing the same instance of o are not shown:
> so when you edit an instance of A (let's call it "a"), you see only
> the instances of n in use by a and the unsed ones (in the context of
> o).
>
> The problem is that I am not allowd to write self.choices_for_n()
>
> Does anybody know any solution for this?
>
> class A(models.Model):
>         o = models.ForeignKey(O)
>         p = models.ManyToManyField(P)
>         n = models.ManyToManyField(N, limit_choices_to=self.choices_for_n())
>
>         def choices_for_n(self):
>                 unwanted = []
>                 for z in self.o.z_set.all():
>                         if z.id == self.id:
>                                 continue
>                         unwanted += [z.id for z in z.n]
>                 for n in N.objects.exclude(id__in=unwanted):
>                         yield n.id

-- 
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: Multitable inheritance - reverse relation

2010-05-27 Thread Scott Gould
Try:

myB = B.objects.get(pk=1)
myCs = C.objects.filter(a__b=myB)

Regards
Scott

> I have model A in which there is field ForeignKey(B). I also have
> model C which inherits from model A. None of these models is abstract.
> Having B object, can I find all C objects pointing to it? When I use
> something like this: Bobject.C_set.all() there appears an error:
> 'AttributeError: B object has no attribute C_set'. Adding related_name
> to this foreignKey field in base class, for example "%(class)s", also
> doesn't help. I tried override this foreignKey field in subclass but I
> get clash error.
> I'm quite new to django and python. Any ideas what I am doing wrong?

-- 
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: making this app re-usable

2010-05-27 Thread Scott Gould
You're after get_model in django.db.models:

model_class = get_model(*model_string.split('.'))

See James Bennet's post in this topic:

http://www.b-list.org/weblog/2007/nov/03/working-models/

Regards
Scott


On May 27, 12:13 am, Jeffrey Taggarty  wrote:
> Hey Guys,
>
> I am trying to build this app so we ca re-use it throughout all of the
> projects we build.
>
> The re-usable app has it's own model and a FK to a specific model that
> it is related to, this is required. Right now I have a setting in my
> project settings.py that uses the re-usable that has this:
> APP_RELATED_MODEL = 'officesupplies.Supply' where officesupplies is
> the appname and Supply is the model it is related to, then in my re-
> usable app I just have ForeignKey(settings.APP_RELATED_MODEL) which
> works fine.
>
> The real problem lies in my import statements in the reusable app, I
> have right now this:
>
> from officesupplies.models import Supply # this is hardcoded, need to
> dynamically load the app/model from the settings.APP_RELATED_MODEL
>
> How can I load up the APP_RELATED_MODEL settings into my import so I
> can do my DB queries etc?
>
> Jeff

-- 
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: Post and Comment with the same Model.

2010-05-25 Thread Scott Gould
>From your description thus far I'd probably try to use
django.contrib.comments and be done with it. Build the specific models
you need for your app, but don't reinvent the wheel when there's a
perfectly good generic commenting app out there already.

On May 25, 12:01 pm, nameless  wrote:
> mmm so I could use Post model with a foreign key to blog and a Comment
> model with a generic foreign key ( because I could comment post,
> images, videos, ecc ). Is this a wrong ? What is the better solution
> in your opinion ? Thanks ^_^

-- 
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: ordering inside regroup

2010-05-25 Thread Scott Gould
On May 25, 3:57 am, maciekjbl  wrote:
> Thank you, for your answer.
>
> I didn't have time to check this because of flood in my company.
>
> I thought that 'regroup' can't be order by any other sorting beside
> it's own.
>
> So I have to order it right and then use 'regroup' or 'regroup' then
> ordering, this is what I don't get.

It's not quite appropriate to say that regroup has a sort order of
"its own". It simply pulls one of the parameters out, and unless all
the objects that share that parameter are together, you probably won't
get the result you're after. See the docs, especially the last part
where it demonstrates a set that isn't ordered properly:

http://docs.djangoproject.com/en/1.2/ref/templates/builtins/#regroup

Regards
Scott

-- 
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: Post and Comment with the same Model.

2010-05-25 Thread Scott Gould
Presumably you want the same object to be able to be a comment on
someone else's post as well as a post in it's own right, that others
could comment on? Looks straightforward enough, though I can't see why
you'd need the generic fields in the model.

Regards
Scott

On May 25, 5:54 am, nameless  wrote:
> I have created a simple project where everyone can create one or more
> Blog. I want to use this models for Post and for Comment:
>
> class Post_comment(models.Model):
>     content_type = models.ForeignKey(ContentType)
>     object_id = models.PositiveIntegerField(_('object ID'))
>     content_object = generic.GenericForeignKey()
>
>     # Hierarchy Field
>     parent = models.ForeignKey('self', null=True, blank=True,
> default=None, related_name='children')
>
>     # User Field
>     user = models.ForeignKey(User)
>
>     # Date Fields
>     date_submitted = models.DateTimeField(_('date/time submitted'),
> default = datetime.now)
>     date_modified = models.DateTimeField(_('date/time modified'),
> default = datetime.now)
>
>     title = models.CharField(_('title'), max_length=60, blank=True,
> null=True)
>     post_comment = models.TextField(_('post_comment'))
>
> if it is a comment the parent is not null. So in most case the text
> field will contain a little bit of text. Can I use this model for both
> Post and Comment ? Is it a good solution ?

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



Re: inclusion tag variable resolving

2010-05-24 Thread Scott Gould
Can you not simply pass foo:

{% make_button 'click me' foo %}

... resolve it, and then use either its .get_absolute_url() or
something other url, depending on what foo is? The inclusion tag's
python code is far more equipped to deal with logic decisions, special
cases, etc. than the template is.

On May 24, 4:49 pm, christian verkerk 
wrote:
> i made an inclusion tag for making an image button of varying widths,
> which i call through:
>
> {% make_button 'click me' item.get_absolute_url %}
>
> i then resolve the second param in context for the button link,
> however i would like to be able to do something along the lines of:
>
> {% make_button 'click me' '/specific/url/with/{{foo}}' %}
>
> in specific cases. resolving that whole second string into context to
> get something like '/specific/url/with/bar/'
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group 
> athttp://groups.google.com/group/django-users?hl=en.

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



Re: Items from multiple tables on one form?

2010-05-24 Thread Scott Gould
> Recall I'd like to make a table with each row in the table being a
> "form" for a paired Author-Book item (recall my book-author is 1-1).
> If I make an Author formset and a Books formset and then render them
> in the template it's not clear to me that the book part of the form
> would in fact correspond to the author part of the form. Actually... I
> expect I'd need to have nested for loops to loop over both formsets
> and that is not what I want...
> {% for AuthorForm in AuthorFormset.forms %}
> {% for BookForm in BookFormset.forms %}
>  {% endfor %}
> {% endfor %}
> will not give the desired result.

Not nested loops no, but a loop that renders each AuthorForm and its
twin BookForm. You'd probably want a template tag for that.

> Regarding the one form idea... I'm new enough to django that it's not
> clear to me how to "pre-populate" the formset in that case with the
> data from the database. While I'm aware of the "initial" parameter in
> the formset constructor it doesn't appear that was meant to initialize
> a form with rows from a database. So it seems that I'd lose the
> information that my initial data actually corresponds to items that
> already exist in the database.

That part is easy: just pass in a list of dictionaries that comprise
the existing data, which you can get from a query.

http://docs.djangoproject.com/en/1.2/topics/forms/formsets/#using-initial-data-with-a-formset

Regards
Scott

-- 
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: Unicode Error when Saving Django Model

2010-05-24 Thread Scott Gould
Point taken, three times.

On May 24, 9:40 am, Karen Tracey <kmtra...@gmail.com> wrote:
> On Mon, May 24, 2010 at 8:27 AM, Scott Gould <zinck...@gmail.com> wrote:
> > > My database and all of its tables are UTF8 encoded with UTF8 collation
> > > (DEFAULT CHARSET=utf8;)
> > > The data I am inputting is unicode
> > > (u'Save up to 25% on your online order of select HP LaserJet\x92s')
> > > 
>
> > > But when I try to save this data I get an error
> > > Incorrect string value: '\\xC2\\x92s' for column 'title' at row 1
>
> > > I assume I am missing something, but not sure what I am missing.
>
> > Your string is a unicode string (u'...') but you have UTF-8 encoded
> > text inside it.
>
> No, that is just the way Python displays unicode repr. The value shown is a
> valid unicode string with a character \x92 in it. This is encoded to utf-8
> as \xC2\x92 for storage in the database, and the database is reporting an
> error with that uf8 encoded value, likely because the table actually has a
> non-utf8 charset that has no mapping for unicode u+0092.
>
> > Unicode is not UTF-8; UTF-8 is a way to represent
> > unicode in ASCII. You should be able to fix it by either casting that
> > string to str(),
>
> Casting to str() would raise a UnicodeEncodeError, because the unicode
> character \x92 cannot be encoded in ASCII:
>
> >>> u
> u'LaserJet\x92'
> >>> type(u)
> 
> >>> str(u)
>
> Traceback (most recent call last):
>   File "", line 1, in 
> UnicodeEncodeError: 'ascii' codec can't encode character u'\x92' in position
> 8: ordinal not in range(128)
>
> > or by having "real" unicode inside it (difficult to
> > say which is better without knowing how you're obtaining that string
> > to begin with).
>
> It is real unicode as it is, though rather odd (it's a "private use"
> character).
>
> Karen
> --http://tracey.org/kmt/
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group 
> athttp://groups.google.com/group/django-users?hl=en.

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



Re: Unicode Error when Saving Django Model

2010-05-24 Thread Scott Gould
> My database and all of its tables are UTF8 encoded with UTF8 collation
> (DEFAULT CHARSET=utf8;)
> The data I am inputting is unicode
> (u'Save up to 25% on your online order of select HP LaserJet\x92s')
> 
>
> But when I try to save this data I get an error
> Incorrect string value: '\\xC2\\x92s' for column 'title' at row 1
>
> I assume I am missing something, but not sure what I am missing.

Your string is a unicode string (u'...') but you have UTF-8 encoded
text inside it. Unicode is not UTF-8; UTF-8 is a way to represent
unicode in ASCII. You should be able to fix it by either casting that
string to str(), or by having "real" unicode inside it (difficult to
say which is better without knowing how you're obtaining that string
to begin with).

Regards
Scott

-- 
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: Items from multiple tables on one form?

2010-05-24 Thread Scott Gould
> # Models
> class Author(models.Model):
>     name = models.CharField(max_length=100)
>     address = models.CharField(max_length=100)
>
> class Book(models.Model):
>     author_id = models.OneToOneField(Author)
>     title = models.CharField(max_length=100)
>
> I'd like to have a form that allowed me to edit both the title of the
> book belonging to a particular author AND also edit his address (and
> possibly name). Even better, I'd like to do this in a formset_factory
> type situation, not just a single book/author combo at a time, but one
> form with multiple entries.

Two main ways to do this:

  - two ModelForms, one for each model, and display/process them both
together
  - one Form, with a custom save() that creates the two objects

I haven't done formsets with multiple forms before, so I don't know
how easy/possible that is. The second option should certainly work
fine in a formset setting, though.

Regards
Scott

-- 
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: Multiple apps in one view

2010-05-24 Thread Scott Gould
> Can you run multiple apps in one view, and what would be the best way
> to do that.

Firstly you can't "run an app" as such. Think of apps as folders on
your desktop -- they organise and compartmentalise in Django.

> Let's say I have two apps and I want to display some items from app1
> and some from app2 in the same view. I understand that it would be a
> good idea to create a third app, but I don't want to violate the dry
> principals. Now I've seen the template tag pass, and the context
> processor, but I can't really find a conclusive way as to how to do
> this the right way.

Pick which app the view "belongs" to most, and put it there. Then just
"from  import ". If you can't decide,
then that's probably an indicator it shouldn't be in either.

There's nothing about creating a third app that violates DRY; don't
repeat yourself refers to duplicating knowledge, not code per se. I
often have apps who don't really do much other than amalgamate
smaller, more tightly-focused apps.

Template tags and context processors are just tools -- you're talking
architecture and organisation at this point.

Regards
Scott

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