using the ImageField with the API

2009-02-09 Thread redmonkey

Hey everyone,

I've got an interesting problem concerning file uploads.

I'm building an online auction and my `Lot` links to a thin
`LotImage` so that I can store multiple images of the lots:

class Lot(models.Model):
...
lot_number = models.PositiveIntegerField("Lot number")

Class LotImage(models.Model)
...
lot = models.ForeignKey(Lot, related_name="images")
main_image = models.ImageField(upload_to=get_main_image_path)

you can see I've written a callable for the `upload_to` parameter
because I want to store the images in a particular place:

def get_thumbnail_path(instance, filename):
return os.path.join(
LotImage.BASE_PATH,
instance.lot.catalogue.__unicode__(),
filename
)

This is all good and works a treat in the admin UI, but how can I keep
this `upload_to` functionality when working with the API by hand?

Django's Documentation on the subject talks about the `File` class
(http://docs.djangoproject.com/en/dev/topics/files/#the-file-object)
which works fine when you explicitly create LotImages:

f = open('/tmp/hello.world', 'w')
myfile = File(f)
f.close()

LotImage.create(
lot_id = 1,
main_image = myfile
)

But by doing so, I loose the `upload_to` functionality. How can I keep
it without physically moving the file to the right place, then
creating a File object and attaching to a new LotImage?

I basically want to create exactly what the admin UI does with
uploaded files.

Can anyone help?

Thanks,

RM
--~--~-~--~~~---~--~~
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: external non-ascii character is breaking my script

2009-02-07 Thread redmonkey

Thank you very much. That solved it, gave me all the information I
needed to not make the same mistake again, and taught me a quick way
to check the encoding of strings in python.

As it happen, in this case, the script that generates the external
file is some commercial software, so I can't touch it. It all seems to
work though.

Thanks again,

RM

On Feb 8, 12:57 am, Karen Tracey <kmtra...@gmail.com> wrote:
> On Sat, Feb 7, 2009 at 7:27 PM, redmonkey 
> <michele.mem...@googlemail.com>wrote:
>
>
>
>
>
> > Sure, here's a bit more info.
>
> > The external data is generated by a script and it describes a
> > catalogue of lot items for an auction site I'm building. The format
> > includes a lot number, a brief description of the lot for sale, and an
> > estimate for the item. Each lot is separated in the file by a '$' with
> > some whitespace. Here's a snippet:
>
> > $
> >  292 A collection of wine bottle and trinket boxes
> >     Est. 30-60
> > $
> >  293 A paper maché letter rack with painted foliate decoration and a
> > C19th papier mache side chair and one other (a/f)
> >     Est. 20-30
> > $
> >  294 A wall mirror with bevelled plate within gilt frame
> >     Est. 40-60
>
> And this file is encoded in...?  It doesn't appear to be utf-8.  It may be
> iso8859-1.
>
>  [snip]
>
>
>
>
>
> > And here's that handle_data_upload function (it's passed the uploaded
> > file object):
>
> > def handle_data_upload(f, cat):
> >    """
> >    Creates and Adds lots to catalogue.
>
> >    """
>
> >    lot = re.compile(r'\s*(?P\d*) (?P.*)
> > \s*Est. (?P\d*)-(?P\d*)')
> >    iterator = lot.finditer(f.read())
> >    f.close()
>
> >    for item in iterator:
> >        if not item.group('description') == "end":
> >            Lot.objects.create(
> >                lot_number=int(item.group('lot_number')),
> >                description=item.group('description').strip(),
>
> Here you are setting description to a bytestring read from your file.  When
> you don't pass Unicode to Django, Django will convert to unicode assuming a
> utf-8 encoding, which will cause the error you are getting if the file is
> not in fact using utf-8 as the encoding.  I suspect your file is encoded in
> iso8859-1, in which case changing this line to:
>
> description=unicode(item.group('description').strip(), 'iso8859-1')
>
> Will probably fix the problem.  But, you should verify that that is the
> encoding used by whatever is creating the file, and if possible you might
> want to change whatever is creating the file to use utf-8 for the encoding,
> if possible (and if these files aren't fed into other processes that might
> get confused by changing their encoding).
>
> [snip]
>
> File "/Library/Python/2.5/site-packages/django/utils/encoding.py" in
>
> > force_unicode
> >  70.         raise DjangoUnicodeDecodeError(s, *e.args)
>
> > Exception Type: DjangoUnicodeDecodeError at /admin/catalogue/catalogue/
> > add/
> > Exception Value: 'utf8' codec can't decode bytes in position 12-14:
> > invalid data. You passed in 'A paper mach\xe9 letter rack with painted
> > foliate decoration and a C19th papier mache side chair and one other
> > (a/f)' ()
>
> This is why I think your file is using iso889-1:
>
> Python 2.5.1 (r251:54863, Jul 31 2008, 23:17:40)
> [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> s = 
> 'A paper mach\xe9 letter rack'
> >>> print unicode(s, 'utf-8')
>
> Traceback (most recent call last):
>   File "", line 1, in 
> UnicodeDecodeError: 'utf8' codec can't decode bytes in position 12-14:
> invalid data>>> print unicode(s, 'iso8859-1')
>
> A paper maché letter rack
>
>
>
> The one that causes the error is what Django does when handed a bytestring,
> and matches what you are seeing.  Using iso8859-1 as the encoding makes the
> value convert and print properly (plus it's a popular encoding).
>
>
>
> > I hope that clears a few things up.
>
> > Is this an admin thing? (http://www.factory-h.com/blog/?p=56)
>
> No, in that blog post the user had a broken __unicode__ method in their
> model, it wasn't actually an admin problem.
>
> Karen
--~--~-~--~~~---~--~~
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: external non-ascii character is breaking my script

2009-02-07 Thread redmonkey
=force_update)
File "/Library/Python/2.5/site-packages/django/db/models/base.py" in
save_base
  400. result = manager._insert(values,
return_id=update_pk)
File "/Library/Python/2.5/site-packages/django/db/models/manager.py"
in _insert
  138. return insert_query(self.model, values, **kwargs)
File "/Library/Python/2.5/site-packages/django/db/models/query.py" in
insert_query
  894. return query.execute_sql(return_id)
File "/Library/Python/2.5/site-packages/django/db/models/sql/
subqueries.py" in execute_sql
  309. cursor = super(InsertQuery, self).execute_sql(None)
File "/Library/Python/2.5/site-packages/django/db/models/sql/query.py"
in execute_sql
  1756. cursor.execute(sql, params)
File "/Library/Python/2.5/site-packages/django/db/backends/util.py" in
execute
  22. sql = self.db.ops.last_executed_query(self.cursor,
sql, params)
File "/Library/Python/2.5/site-packages/django/db/backends/
__init__.py" in last_executed_query
  177. u_params = tuple([to_unicode(val) for val in
params])
File "/Library/Python/2.5/site-packages/django/db/backends/
__init__.py" in 
  175. to_unicode = lambda s: force_unicode(s,
strings_only=True)
File "/Library/Python/2.5/site-packages/django/utils/encoding.py" in
force_unicode
  70. raise DjangoUnicodeDecodeError(s, *e.args)

Exception Type: DjangoUnicodeDecodeError at /admin/catalogue/catalogue/
add/
Exception Value: 'utf8' codec can't decode bytes in position 12-14:
invalid data. You passed in 'A paper mach\xe9 letter rack with painted
foliate decoration and a C19th papier mache side chair and one other
(a/f)' ()

I hope that clears a few things up.

Is this an admin thing? (http://www.factory-h.com/blog/?p=56)

RM

On Feb 8, 12:00 am, Karen Tracey <kmtra...@gmail.com> wrote:
> On Sat, Feb 7, 2009 at 11:56 AM, redmonkey 
> <michele.mem...@googlemail.com>wrote:
>
>
>
> > Hey everyone,
>
> > I'm trying to create django model instances from data stored in a flat
> > text file but I get `force_unicode` errors when the script comes
> > across one of the data items containing the "é" character.
>
> > Can anyone explain to me what this problem is and now I can fix it? I
> > can't really get my head around unicode, ascii and UTF-8 stuff.
>
> If you expect anyone on the list to help, you really need to share some
> snippets of the code you are using to read the data from the file and create
> Django model instances, plus the full traceback you get when it runs into
> trouble.  Django certainly handles unicode data in models, so there's
> something specific about what you are doing that is causing a problem.
>
> Karen
--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



external non-ascii character is breaking my script

2009-02-07 Thread redmonkey

Hey everyone,

I'm trying to create django model instances from data stored in a flat
text file but I get `force_unicode` errors when the script comes
across one of the data items containing the "é" character.

Can anyone explain to me what this problem is and now I can fix it? I
can't really get my head around unicode, ascii and UTF-8 stuff.

Thanks,

RedMonkey
--~--~-~--~~~---~--~~
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: PDF creation!!!

2008-12-19 Thread redmonkey

If you just want images of data, Google charts might be useful:

http://code.google.com/apis/chart/

I imagine you could get Google to generate a .jpg for you and put the
in a .pdf if you need to print it.

Furthermore, if it is fancy grphs you want, Google Visualisations
could work even better:

http://code.google.com/apis/visualization/


On Dec 19, 2:08 pm, panta  wrote:
> On Dec 19, 2:21 pm, Abdel Bolanos Martinez 
> wrote:
>
> > Please can any one give me good references about tools for create PDF
> > reports, graphs in Django besides RepoLab
>
> > thanks
>
> Hi Abdel,
> give a look at XHTML2PDF:
>
> http://www.htmltopdf.org/
>
> See also:
>
> http://docs.djangoproject.com/en/dev/howto/outputting-pdf/?from=olddocs
>
> Ciao,
> Marco
>
>
>
> > Abdel Bolaños Martínez
> > Ing. Infórmatico
> > Telf. 266-8562
> > 5to piso, oficina 526, Edificio Beijing, Miramar Trade Center. ETECSA
>
>
--~--~-~--~~~---~--~~
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: Add fields to another app model

2008-12-04 Thread redmonkey

Hey Bojan

There is a few ways you could do this (certainly more that what I'm
about to tell you). It depends on the effect you want to create.

Perhaps the simplest way is to inherit from the existing class. But
inheriting classes should only strictly be used as an `is a`
relationship. So perhaps you could justify it by thinking of your
Contact model as just a different, specialised version of the satchmo
Contact model. It's worth baring in mind the DB joins this type of
thing could add though, and the consequences these joins bring with
them. In a recent project I was working on, I imported the model I
needed, changed `abstract = True` and then inherited from it in one of
my models to do a similar sort of thing to what you're trying to
create:

from voting.models import Vote as VoteBase
VoteBase._meta.abstract = True

class SpecialVote(VoteBase):
pass

There's a good TWiD article on inheriting models so you could take a
look at that to find out more about it
http://thisweekindjango.com/articles/2008/jun/17/abstract-base-classes-vs-model-tab/

The other option is to use a registering paradigm like that used in
Django-MPTT. You basically call a function with a bunch of models and
this function adds some properties to them. You can see it here in the
DJango-MPTT __init__.py file:
http://code.google.com/p/django-mptt/source/browse/trunk/mptt/__init__.py

If you read the docs for Django-MPTT you see that you have to add a
call to ``mptt.register`` with every model you want to have this
functionality. This function just adds a tonne of fields and
properties to your models using _meta. You can read more about that by
James Bennett:

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

Have a poke around in loads of the project on Google Code though, see
what other people are doing, and how they're tackling problems like
you'll soon start having your own ideas about how to do stuff.

Hope all that helps.

RM

On Dec 4, 8:45 am, Bojan Mihelac <[EMAIL PROTECTED]> wrote:
> Hi all!
>
> I am looking for right way to add fields to model that is in another
> app. At first I created mysite application and in models.py put
>
> from satchmo.contact.models import Contact
> Contact.add_to_class("company_name", models.CharField(max_length =
> 200))
>
> that raises exception ProgrammingError sometimes:
> ProgrammingError: (1110, "Column 'company_name' specified twice")
>
> So now I check before if field is already in model:
>
> if 'company_name' not in Contact._meta.get_all_field_names():
>     Contact.add_to_class("company_name", models.CharField(max_length =
> 200))
>
> I have feeling that this is not right way to do. I'd appreciate any
> help, hint or thought on this.
> I also wonder how models are loaded in django.
>
> Bojan
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Add fields to another app model

2008-12-04 Thread redmonkey

Hey Bojan

There is a few ways you could do this (certainly more that what I'm
about to tell you). It depends on the effect you want to create.

Perhaps the simplest way is to inherit from the existing class. But
inheriting classes should only strictly be used as an `is a`
relationship. So perhaps you could justify it by thinking of your
Contact model as just a different, specialised version of the satchmo
Contact model. It's worth baring in mind the DB joins this type of
thing could add though, and the consequences these joins bring with
them. In a recent project I was working on, I imported the model I
needed, changed `abstract = True` and then inherited from it in one of
my models to do a similar sort of thing to what you're trying to
create:

from voting.models import Vote as VoteBase
VoteBase._meta.abstract = True

class SpecialVote(VoteBase):
pass

There's a good TWiD article on inheriting models so you could take a
look at that to find out more about it
http://thisweekindjango.com/articles/2008/jun/17/abstract-base-classes-vs-model-tab/

The other option is to use a registering paradigm like that used in
Django-MPTT. You basically call a function with a bunch of models and
this function adds some properties to them. You can see it here in the
DJango-MPTT __init__.py file:
http://code.google.com/p/django-mptt/source/browse/trunk/mptt/__init__.py

If you read the docs for Django-MPTT you see that you have to add a
call to ``mptt.register`` with every model you want to have this
functionality. This function just adds a tonne of fields and
properties to your models using _meta. You can read more about that by
James Bennett:

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

Have a poke around in loads of the project on Google Code though, see
what other people are doing, and how they're tackling problems like
you'll soon start having your own ideas about how to do stuff.

Hope all that helps.

RM

On Dec 4, 8:45 am, Bojan Mihelac <[EMAIL PROTECTED]> wrote:
> Hi all!
>
> I am looking for right way to add fields to model that is in another
> app. At first I created mysite application and in models.py put
>
> from satchmo.contact.models import Contact
> Contact.add_to_class("company_name", models.CharField(max_length =
> 200))
>
> that raises exception ProgrammingError sometimes:
> ProgrammingError: (1110, "Column 'company_name' specified twice")
>
> So now I check before if field is already in model:
>
> if 'company_name' not in Contact._meta.get_all_field_names():
>     Contact.add_to_class("company_name", models.CharField(max_length =
> 200))
>
> I have feeling that this is not right way to do. I'd appreciate any
> help, hint or thought on this.
> I also wonder how models are loaded in django.
>
> Bojan
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: An interesting URL dispatcher problem

2008-11-07 Thread redmonkey

Here's my solutions, for anyone who may be experiencing the same
problem.

In my url config, I have 4 different named patterns corresponding to
each of the possibilities:

url(r'^(?P[a-zA-Z]+)/(?P[\+\-].\w+)/$',
'catalogueFilter', name="catalogue_search_no_filters"),
url(r'^(?P[a-zA-Z]+)/(?P[\+\-].\w+)/(?
P\d+(?=-))?-(?P(?<=-)\d+)?/$',
'catalogueFilter', name="catalogue_search_estimates"),
url(r'^(?P[a-zA-Z]+)/(?P[\+\-].\w+)/(?
P[a-zA-Z0-9%]+)/$', 'catalogueFilter',
name="catalogue_search_desc"),
url(r'^(?P[a-zA-Z]+)/(?P[\+\-].\w+)/(?
P\d+(?=-))?-(?P(?<=-)\d+)?/(?
P[a-zA-Z0-9%]+)/$', 'catalogueFilter',
name="catalogue_search_estimates_desc"),

I apologise for them being a bit messy, but you can see that each
pattern starts with "(?P[a-zA-Z]+)/(?P[\+\-].\w+)"
These correspond to the drop down boxes in my form. They will always
be submitted. The first pattern contains just these parameters, and so
the url is called "catalogue_search_no_filters".

Second, we have a pattern for if some estimates are submitted. These
are optional form fields that can be filled in if the user wants to
narrow down the search. In order to allow for this flexibility, there
are a lot of '?' in the regular expression. The regular expression
adds a '-' character in to represent a range of values.

We then have another url for just the optional description field. This
is a simple text search.

Finally I have a named url for the optional estimate fields and an
optional description field. I was trying to write one single url that
allowed for both, but I couldn't. Instead I came up with this
solution. I different named url that points to the same view function.

The view function itself is pretty straight forward. It accepts all
the parameters and includes so default values:

def catalogueFilter(request, site='any', min_estimate=None,
max_estimate=None,
sort_by=LotSearchForm.SORT_CHOICES_URLS[0][1], description=None):

 do stuff, get "results' together ...

return object_list(
request=request,
queryset=results,
page=page,
paginate_by=20,
template_object_name="lot",
extra_context=dict(
search_form=form
)
)

I'm using a generic view to return the HttpResponse.

The messy bit is how I determine which named url to call. I'm afriad
it's a lot of if/else statements branching off to different
HttpResponseRedirects:

if ("min_estimate" in params) or ("max_estimate" in params):
if "description" in params:
return HttpResponseRedirect(
reverse('catalogue_search_estimates_desc', kwargs=params))
else:
return HttpResponseRedirect(
reverse('catalogue_search_estimates', kwargs=params)
else:
if "description" in params:
return HttpResponseRedirect(
reverse('catalogue_search_desc', kwargs=params))
else:
return HttpResponseRedirect(
reverse('catalogue_search_no_filters', kwargs=params))

I admit this isn't elegant at all, but it works. If anyone has any
ideas on how I could improve this, please let me know. If nothing
else, it might clear up what I'm trying to do here.

Thanks,

RM

On Nov 4, 5:48 pm, redmonkey <[EMAIL PROTECTED]> wrote:
> Hi Brian,
>
> Thanks for your comment. I completely understand what you are saying,
> and anyone trying to match the "?" character should take note, but in
> this situation I am using it to try to tell Django that that named
> group in the regular expression may, or may not, be included.
>
> RM
>
> On Nov 4, 5:33 pm, Brian Neal <[EMAIL PROTECTED]> wrote:
>
> > On Nov 4, 10:50 am, redmonkey <[EMAIL PROTECTED]> wrote:
>
> > > My problem is with the URL writing. I first wrote some unit tests to
> > > find the regular expressions that worked but Django doesn't seem to
> > > like the '?' in URL configurations.
>
> > ? is a special character in regular expressions, just like $, ^, etc.
> > You must escape it if you want to use it literally, e.g. \?. However,
> > I don't think the ? as part of any GET arguments in a URL are going to
> > be available to you, from what I remember about django works.
>
> > I'm not really following what you are trying to do however.
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: An interesting URL dispatcher problem

2008-11-04 Thread redmonkey

Hi Brian,

Thanks for your comment. I completely understand what you are saying,
and anyone trying to match the "?" character should take note, but in
this situation I am using it to try to tell Django that that named
group in the regular expression may, or may not, be included.

RM

On Nov 4, 5:33 pm, Brian Neal <[EMAIL PROTECTED]> wrote:
> On Nov 4, 10:50 am, redmonkey <[EMAIL PROTECTED]> wrote:
>
>
>
> > My problem is with the URL writing. I first wrote some unit tests to
> > find the regular expressions that worked but Django doesn't seem to
> > like the '?' in URL configurations.
>
> ? is a special character in regular expressions, just like $, ^, etc.
> You must escape it if you want to use it literally, e.g. \?. However,
> I don't think the ? as part of any GET arguments in a URL are going to
> be available to you, from what I remember about django works.
>
> I'm not really following what you are trying to do however.
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: An interesting URL dispatcher problem

2008-11-04 Thread redmonkey

I have to admit, the missing ) is a typo. I made up the ice cream
example to try to simplify my problem, and accidentally missed it off.

Perhaps my example is too simple.
> I have a small form on a page that is mostly optional fields with the
> exception of some drop down boxes.

My actual form has 3 optional fields, and this complicated matters
with matching URLs. Fortunately, two of the fields are limits for a
price search, so I've used "-" to identify the re, and the third is a
text description so I'm expecting URLs that look like "/100-200/persian
%20rug/" (Where 100-200 is the price range, and "persian%20rug" is a
quoted text search).

My issue is that any of those 3 fields may not be submitted, but
somehow I need to redirect to the process view.

The http://jobs.guardian.co.uk/jobs/; title="Guardian
Jobs">Guardian Jobs site is a nice example of the effect I want to
create as you add filtering paramters on the left, although I'm using
a form to collect user input as opposed to giving them a list of
ranges which is more difficult.

I hope that clears a few things up.

On Nov 4, 5:23 pm, Steve Holden <[EMAIL PROTECTED]> wrote:
> redmonkey wrote:
> > Hi,
>
> > I have a small form on a page that is mostly optional fields with the
> > exception of some drop down boxes. I want to take the data submitted
> > through this form and use them to form a URL.
>
> > My problem is with the URL writing. I first wrote some unit tests to
> > find the regular expressions that worked but Django doesn't seem to
> > like the '?' in URL configurations.
>
> > How can I write a workflow that converts optional, POSTed data to a
> > RESTful URL for processing?
>
> > Here's an example:
>
> > class IceCreamForm(forms.form):
> >     description = forms.CharField(required=False)
> >     flavour = forms.ChoiceField(choices=FLAVOUR_CHOICES, initial=0)
> >     FLAVOUR_CHOICES = (
> >            ...
> >     )
>
> > This is my form class. It contains one optional field, and one
> > required field. When rendered on a page, the form POSTs it's data to
> > the the 'process' view:
>
> > def process(request):
> >     # Standard form stuff (is_valid) ...
> >     params = {}
> >     if form.cleaned_data['description']:
> >         params.update(description=form.cleaned_data['description'])
> >    if form.cleaned_data['flavour']:
> >        params.update(flavour=form.cleaned_data['flavour'])
>
> >    return HttpResponseRedirect('proj.app.views.filter', kwags=params)
>
> > def filter(request, description=None, flavour=0):
> >     ... do stuff ...
>
> > Here, I collect the parameters from the form and try to turn them into
> > a pretty URL that redirects to the filter view to do something with
> > the data. It's the URL writing I'm having problems with. I want to
> > write things like:
>
> > urlpatterns += patterns('proj.app.views',
> >     (r'^(?P\w+)/((?P\w+)/)?$', 'filter'),
> > )
>
> It might be better to try something that makes the last slash optional
> in a different way. How about
>
>     (r'^(?P\w+)(/(?P\w+))/?$', 'filter'),
>
> > The question mark is wrapped around an extra '/' to complete the URL,
> > but it doesn't work. Nor does
>
> > urlpatterns += patterns('proj.app.views',
> >     (r'^(?P\w+)/$', 'filter'),
> >     (r'^(?P\w+)/(?P\w+/$', 'filter'),
> > )
>
> > I'm surprised with the result of the last one, and so I'm sure I'm
> > missing something. Does anyone have any ideas or simplifications for
> > me?
>
> The last one doesn't even appear to be a syntactically correct re due to
> mismatching parentheses ... did you copy and paste, or mis-transcribe?
>
> regards
>  Steve
> --
> Steve Holden        +1 571 484 6266   +1 800 494 3119
> Holden Web LLC              http://www.holdenweb.com/
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



An interesting URL dispatcher problem

2008-11-04 Thread redmonkey

Hi,

I have a small form on a page that is mostly optional fields with the
exception of some drop down boxes. I want to take the data submitted
through this form and use them to form a URL.

My problem is with the URL writing. I first wrote some unit tests to
find the regular expressions that worked but Django doesn't seem to
like the '?' in URL configurations.

How can I write a workflow that converts optional, POSTed data to a
RESTful URL for processing?

Here's an example:

class IceCreamForm(forms.form):
description = forms.CharField(required=False)
flavour = forms.ChoiceField(choices=FLAVOUR_CHOICES, initial=0)
FLAVOUR_CHOICES = (
...
)

This is my form class. It contains one optional field, and one
required field. When rendered on a page, the form POSTs it's data to
the the 'process' view:

def process(request):
# Standard form stuff (is_valid) ...
params = {}
if form.cleaned_data['description']:
params.update(description=form.cleaned_data['description'])
if form.cleaned_data['flavour']:
params.update(flavour=form.cleaned_data['flavour'])

return HttpResponseRedirect('proj.app.views.filter', kwags=params)

def filter(request, description=None, flavour=0):
... do stuff ...

Here, I collect the parameters from the form and try to turn them into
a pretty URL that redirects to the filter view to do something with
the data. It's the URL writing I'm having problems with. I want to
write things like:

urlpatterns += patterns('proj.app.views',
(r'^(?P\w+)/((?P\w+)/)?$', 'filter'),
)

The question mark is wrapped around an extra '/' to complete the URL,
but it doesn't work. Nor does

urlpatterns += patterns('proj.app.views',
(r'^(?P\w+)/$', 'filter'),
(r'^(?P\w+)/(?P\w+/$', 'filter'),
)

I'm surprised with the result of the last one, and so I'm sure I'm
missing something. Does anyone have any ideas or simplifications for
me?

Thanks,

Red Monkey



--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: content type

2008-10-30 Thread redmonkey

You need to set a 'Content-Disposition' header.

http://docs.djangoproject.com/en/dev/howto/outputting-pdf/?from=olddocs#complex-pdfs

Look within the 'some_view' definition. You need to generate a
HttpResponse object, set the response mimetype to the correct type of
file you're serving, and then set the 'Content-Disposition' key to
something like it says. Notice you can also set the filename if you
need to.

On Oct 30, 9:18 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> hi all i am using debian stable version 0.95
>
> and i would like know, how to tell django not to open some file types as
> JPG, PNG or MP3 in browser after click and rather open a classic menu to
> save the file.
>
> thank you very much pavel
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Triggering a custom signal

2008-10-29 Thread redmonkey

Exactly that. Here's what I put together:

class Catalogue(models.Model):
... everything above ...

# Added field to store reference to at-job number
at_job_number = models.IntegerField(editable=False)

def save(self, **kwargs):
self.create_at_job()# new method
super(Catalogue, self).save(kwargs)

def delete(self):
self.remove_at_job() # new method to make sure no at-job
are left in the system
super(Catalogue, self).delete()

# setup a regular expression to extract at-job number from output
RE_job_id = re.compile(r'^job (?P\d+) at')

def create_at_job(self):
if not self.has_ended():
if self.at_job_number:
self.remove_at_job()

# Get the domain from the current site
domain = Site.objects.get_current().domain

# Setup the command to run the at job
cmd = 'curl -I -# http://%s%s > /dev/null | at %s' %
(domain, self.get_delete_url(), self.auction_date.strftime('%H:%M %m%d
%y'))

# run the command, and save the output
response = commands.getoutput(cmd)

# extract job-id using the regular expression
job_id = Catalogue.RE_job_id.search(response).group('job_id')

# store at-job in model field
self.at_job_number = int(job_id)

# Borrow this principle from get_absolute_url()
def get_delete_url(self):
return ('catalogue_disableCatalogue', [str(self.id)]) #
named URL where we'll do all the magic we need to
get_delete_url = permalink(get_delete_url)

# straight forward function, just to make things easier
def has_ended(self):
return self.auction_date < datetime.now()

def remove_at_job(self):
job_id = self.at_job_number
cmd = 'atrm %s' % job_id
# This time there's no output to capture
os.system(cmd)
# reset the job number
self.at_job_number = None

It should be ok to follow; I haven't done anything major. It's not a
secure URL yet, but I figure I'll just do that by changing the url for
the curl command to use https and embed in the username/password, then
check for request.is_secure() in the 'catalogue_disableCatalogue'
view.

If anyone can spot anything glaringly obvious, or has any question,
please get back to me.

Red Monkey

On Oct 28, 12:55 am, "Matías Costa" <[EMAIL PROTECTED]> wrote:
> On Mon, Oct 27, 2008 at 5:52 PM, redmonkey <[EMAIL PROTECTED]>wrote:
>
>
>
> > h. Yeah, That's pretty simple.
>
> > I could even get a reference to the Job number using -v with at,
> > storing that in the DB and then removing and recreating another at-job
> > if the user changes the time.
>
> Do you mean some kind of shell scripting embed with os.system or
> process.call?
--~--~-~--~~~---~--~~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Triggering a custom signal

2008-10-27 Thread redmonkey

h. Yeah, That's pretty simple.

I could even get a reference to the Job number using -v with at,
storing that in the DB and then removing and recreating another at-job
if the user changes the time.

Brilliant, thank you.

On Oct 27, 4:05 pm, Steve Holden <[EMAIL PROTECTED]> wrote:
> redmonkey wrote:
> > Thanks Matías, you've come up with a good solution, but unfortunately
> > this won't really work for my situation.
>
> > For my client, online bidding ends immediately before they open
> > bidding on the shop floor. The catalogue for that sale must go offline
> > at that point. I can't expect my client to postpone things while they
> > wait for my cron job to decide to close the catalogue down. Thanks for
> > posting the save method though, it's quite neat.
>
> > I'm finding it hard to believe there isn't an easy way to do this, not
> > even with the full Python Library behind it. I understand what signals
> > are, and I know that you can create http://code.google.com/p/
> > django-cron/source/browse/trunk/cron/signals.py" title"Django-cron:
> > Signals">custom ones. I'd like to know how I can send my custom
> > signal at the DateTimeField value.
>
> > On Oct 27, 12:14 pm, "Matías Costa" <[EMAIL PROTECTED]> wrote:
>
> >> BTW this is the save method for the model with the rounding function:
>
> >>     def save(self):
> >>         def roundminute(d,  r):
> >>             """Rounds the datetime d to the nearer r multiple
> >>             If r == 15 =>
> >>             3:00 -> 3:00
> >>             3:05 -> 3:00
> >>             3:27 -> 3:30
> >>             3:55 -> 4:00
>
> >>             Adds hours correctly
> >>             """
> >>             from datetime import datetime,  timedelta
> >>             m = d.minute
> >>             if m > (60 - r/2):
> >>                 m = 0
> >>                 d += timedelta(60*60)
> >>             else:
> >>                 m = m - (m%r) if (m%r)<(r/2) else m+(r-(m%r))
> >>             return d.replace(minute=m,  second=0, microsecond=0)
>
> >>         if self.price == None:
> >>             self.price = self.start_price
> >>         self.start_date = roundminute(self.start_date,  15)
> >>         self.end_date = roundminute(self.end_date,  15)
> >>         super(Auction, self).save()
>
> >> On Mon, Oct 27, 2008 at 1:06 PM, Matías Costa <[EMAIL PROTECTED]> wrote:
>
> >>> I have the exact problem. I round end and start dates to 15 minutes. I
> >>> mean, user enters 12:10, I write 12:15. So each 15 minutes cron runs a
> >>> script with django-commands-extensions runscript. Is a balance between
> >>> accuracy and load.
>
> >>> The perfect should be finding the next success to happen (easy) and 
> >>> program
> >>> django-cron or anything else to run at that time (I don't know how)
>
> >>> I am very interested in the solutions people have found for this
>
> >>> On Mon, Oct 27, 2008 at 12:45 PM, redmonkey <[EMAIL PROTECTED]
>
> >>>> wrote:
>
> >>>> Hi,
>
> >>>> I'm working on a simple auctioneer's website. My Catalogue app
> >>>> consists of a list of Lots arranged into Catalogues. Each catalogue
> >>>> has an auction_data field which stores a status and a date and time of
> >>>> the sale:
>
> >>>> class Catalogue(models.Model):
> >>>>    DRAFT_STATUS = 1
> >>>>    LIVE_STATUS = 2
> >>>>    CATALOGUE_CHOICES = (
> >>>>        (DRAFT_STATUS, 'Draft'),
> >>>>        (LIVE_STATUS, 'Live'),
> >>>>    )
> >>>>    status = models.IntegerField("Status", choices=CATALOGUE_CHOICES,
> >>>>        default=DRAFT_STATUS)
> >>>>    auction_date = models.DateTimeField("Date of Auction")
> >>>>    ...
>
> >>>> class Lot(models.Model):
> >>>>    catalogue = models.ForeignKey(Catalogue, related_name="lots")
> >>>>    ...
>
> >>>> Pretty simple stuff. My problem is that I need to run a function at
> >>>> the auction_date of the catalogue that will do a few things like
> >>>> change the status of the catalogue, and send an email out to some
> >>>> admins.
>
> >>>> I've done some brief research, and found django-cron,
&

Re: Triggering a custom signal

2008-10-27 Thread redmonkey

Thanks Matías, you've come up with a good solution, but unfortunately
this won't really work for my situation.

For my client, online bidding ends immediately before they open
bidding on the shop floor. The catalogue for that sale must go offline
at that point. I can't expect my client to postpone things while they
wait for my cron job to decide to close the catalogue down. Thanks for
posting the save method though, it's quite neat.

I'm finding it hard to believe there isn't an easy way to do this, not
even with the full Python Library behind it. I understand what signals
are, and I know that you can create http://code.google.com/p/
django-cron/source/browse/trunk/cron/signals.py" title"Django-cron:
Signals">custom ones. I'd like to know how I can send my custom
signal at the DateTimeField value.

On Oct 27, 12:14 pm, "Matías Costa" <[EMAIL PROTECTED]> wrote:
> BTW this is the save method for the model with the rounding function:
>
>     def save(self):
>         def roundminute(d,  r):
>             """Rounds the datetime d to the nearer r multiple
>             If r == 15 =>
>             3:00 -> 3:00
>             3:05 -> 3:00
>             3:27 -> 3:30
>             3:55 -> 4:00
>
>             Adds hours correctly
>             """
>             from datetime import datetime,  timedelta
>             m = d.minute
>             if m > (60 - r/2):
>                 m = 0
>                 d += timedelta(60*60)
>             else:
>                 m = m - (m%r) if (m%r)<(r/2) else m+(r-(m%r))
>             return d.replace(minute=m,  second=0, microsecond=0)
>
>         if self.price == None:
>             self.price = self.start_price
>         self.start_date = roundminute(self.start_date,  15)
>         self.end_date = roundminute(self.end_date,  15)
>         super(Auction, self).save()
>
> On Mon, Oct 27, 2008 at 1:06 PM, Matías Costa <[EMAIL PROTECTED]> wrote:
> > I have the exact problem. I round end and start dates to 15 minutes. I
> > mean, user enters 12:10, I write 12:15. So each 15 minutes cron runs a
> > script with django-commands-extensions runscript. Is a balance between
> > accuracy and load.
>
> > The perfect should be finding the next success to happen (easy) and program
> > django-cron or anything else to run at that time (I don't know how)
>
> > I am very interested in the solutions people have found for this
>
> > On Mon, Oct 27, 2008 at 12:45 PM, redmonkey <[EMAIL PROTECTED]
> > > wrote:
>
> >> Hi,
>
> >> I'm working on a simple auctioneer's website. My Catalogue app
> >> consists of a list of Lots arranged into Catalogues. Each catalogue
> >> has an auction_data field which stores a status and a date and time of
> >> the sale:
>
> >> class Catalogue(models.Model):
> >>    DRAFT_STATUS = 1
> >>    LIVE_STATUS = 2
> >>    CATALOGUE_CHOICES = (
> >>        (DRAFT_STATUS, 'Draft'),
> >>        (LIVE_STATUS, 'Live'),
> >>    )
> >>    status = models.IntegerField("Status", choices=CATALOGUE_CHOICES,
> >>        default=DRAFT_STATUS)
> >>    auction_date = models.DateTimeField("Date of Auction")
> >>    ...
>
> >> class Lot(models.Model):
> >>    catalogue = models.ForeignKey(Catalogue, related_name="lots")
> >>    ...
>
> >> Pretty simple stuff. My problem is that I need to run a function at
> >> the auction_date of the catalogue that will do a few things like
> >> change the status of the catalogue, and send an email out to some
> >> admins.
>
> >> I've done some brief research, and found django-cron,
> >> and I imagine I could write something that checked each hour to see if
> >> any catalogues had expried recently, but that seems mad.
>
> >> Another solution I came up with involved checking for the expiry date
> >> every time a record is pulled up from the database. But this add's a
> >> hit to user responsiveness (even if it is tiny) and still doesn't
> >> allow me to send out the email.
>
> >> Finally, I read up on Django's signals to decide if I could use that
> >> mechanism to do other things. Signals sounds ideal, but I don't know
> >> how to trigger at the right time.
>
> >> Can anyone help me with this? How do I trigger a custom signal based
> >> on a DateTimeField value?
>
> >> 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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Triggering a custom signal

2008-10-27 Thread redmonkey

Hi,

I'm working on a simple auctioneer's website. My Catalogue app
consists of a list of Lots arranged into Catalogues. Each catalogue
has an auction_data field which stores a status and a date and time of
the sale:

class Catalogue(models.Model):
DRAFT_STATUS = 1
LIVE_STATUS = 2
CATALOGUE_CHOICES = (
(DRAFT_STATUS, 'Draft'),
(LIVE_STATUS, 'Live'),
)
status = models.IntegerField("Status", choices=CATALOGUE_CHOICES,
default=DRAFT_STATUS)
auction_date = models.DateTimeField("Date of Auction")
...

class Lot(models.Model):
catalogue = models.ForeignKey(Catalogue, related_name="lots")
...

Pretty simple stuff. My problem is that I need to run a function at
the auction_date of the catalogue that will do a few things like
change the status of the catalogue, and send an email out to some
admins.

I've done some brief research, and found django-cron,
and I imagine I could write something that checked each hour to see if
any catalogues had expried recently, but that seems mad.

Another solution I came up with involved checking for the expiry date
every time a record is pulled up from the database. But this add's a
hit to user responsiveness (even if it is tiny) and still doesn't
allow me to send out the email.

Finally, I read up on Django's signals to decide if I could use that
mechanism to do other things. Signals sounds ideal, but I don't know
how to trigger at the right time.

Can anyone help me with this? How do I trigger a custom signal based
on a DateTimeField value?

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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



TextField default String problem

2008-06-17 Thread redmonkey

I have two fields in a model, a name (CharField) and a description
(TextField). I'm trying to set the default description to be something
simple like:

default="hello, I'm the description of the %s" % name

(To my surprise) this validates, but the description includes a
reference to the name field, not it's value, resulting in:

"hello, I'm the description of the "

I want to get an affect similar to that of prepopulate_from, but
Django's documentation isn't being that useful. Is there no
[field].value property? Can anyone help me out?

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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---