Re: Django new comments framework error

2008-11-13 Thread DavidA

I just got bit by this too and it turned out that I had done an
install of Django-1.0 on top of an older Django install. In the site-
packages directory there was both a django/contrib/comments/urls.py
(from 1.0) and a django/contrib/comments/urls/ directory which
contained __init__.py and comments.py.

So the configuration of comments using this line:

(r'^comments/', include('django.contrib.comments.urls')),

Was just importing the empty __init__.py and no urlpatterns variable
was defined. Thus, urlresolvers.reverse never saw any urlpatterns for
comments and couldn't reverse the post_comment view.

Just thought I'd post this in case someone else runs into the same
thing.

-Dave

On Oct 1, 2:53 pm, hotani <[EMAIL PROTECTED]> wrote:
> It's back!
>
> No error on dev server, but crashing like crazy on test with same old
> crap:
>
> >> Caught an exception while rendering:Reversefor ' >> 0x2ae96d979410>' with arguments '()' and keyword arguments '{}' not found
>
> It alternates between that and:
>
> >> Caught an exception while rendering: No module named urls
>
> Then the error page goes on to show the error is being caused by the
> "{% comment_form_target %}" tag.
>
> I have removed .pyc files. I have removed all of django and reloaded
> it. What is left? This was working moments ago, and is fine on one
> server but not another.
--~--~-~--~~~---~--~~
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: how can i get the object comments are attached to after post?

2008-11-16 Thread DavidA

>From a quick scan of the source code, I don't think the object is
passed into the template, but you can get the related content object
directly from the comment (which is passed into the template). Just
use the content_object field of the comment like this:

{{ comment.content_object.slug }}  (or whatever property in the
related object you want to access)

content_object is a foreign key to the original object so in my case
it's a blog Post object which has a slug field.

-Dave

On Nov 16, 8:00 am, popufig <[EMAIL PROTECTED]> wrote:
> Hi everyone,
>
>     i am now using Django’s comments framework,  accoring to the book
> , after end user post the
> comment, we can create our own template comments/posted.html, and this
> template has a variable called object that refers to the object that
> received the comment. But i cannot get this object in the template, i
> am not sure it's old version feature or not.
>
> Any help and hints are appreciated!
>
> Thanks,
> Sky
--~--~-~--~~~---~--~~
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: Can I perform calculations directly in django tags/filters?

2008-11-18 Thread DavidA

You can do it in a custom eval-like tag:

@register.tag()
def evalpy(parser, token):
try:
tag_name, expression = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires a
single argument" % token.contents.split()[0]
if not (expression[0] == expression[-1] and expression[0] in
('"', "'")):
raise template.TemplateSyntaxError, "%r tag's argument
should be in quotes" % tag_name
return EvalNode(expression[1:-1])

class EvalNode(template.Node):
def __init__(self, expression):
self.expression = expression
def render(self, context):
return eval(self.expression, {}, context)

and then use it like below. Note you can access context/template
variables this way:

{% get_comment_count for post as comment_count %}
{% evalpy "comment_count + 3" %}

Kludgy, yes, but sometimes useful.
-Dave

On Nov 18, 3:26 pm, Rajesh Dhawan <[EMAIL PROTECTED]> wrote:
> > I am thinking about something like {{  (width - 5) *12  }}  ?
>
> No. That syntax is not supported in Django templates.
--~--~-~--~~~---~--~~
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: MySQL deadlocking issues

2008-11-18 Thread DavidA

Unrelated to Django, but we occasionally get deadlocks in MySQL due to
separate tasks running at the same time and accessing some tables in
common. We recently added logic to catch the exception, wait a second
or two, and retry it a few times before we give up. Most of the time,
that fixes it.

I agree with Malcolm, though, that for a pure Django app, I would
think it fairly unlikely to occur unless you are doing something non-
standard with your models/logic.

-Dave

On Nov 18, 8:52 pm, Malcolm Tredinnick <[EMAIL PROTECTED]>
wrote:
> On Wed, 2008-11-19 at 10:21 +0900, Ian Lewis wrote:
> > I've run into the following error in a SQL DB envornment and was
> > wondering if any one else had run into problems with Deadlocking with
> > MySQL. What would be the proper way to handle this kind of error in
> > Django?
>
> > Do most folks simply catch the OperationalError and show some sort of
> > error to the user?
>
> That sounds reasonable.
>
> More substantive for our purposes, though, would be knowing why this
> occurred and if there was any way to avoid it. Either you have a fairly
> twisted model setup that means an insert causes a deadlock, or there's
> something that can be improved in Django. So if you could post some
> details of how you are able to cause this error, it would be appreciated
> (by me, at least).
>
> Regards,
> Malcolm
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: MySQL deadlocking issues

2008-11-19 Thread DavidA

The application I'm referring to uses CherryPy without any ORM. We
have a shortcut "execute" method that all DB calls go through. We just
added special exception handling to that call. Not sure how you would
do the same thing in Django. You'd probably have to dig into django.db
to see if you can wrap the cursor class or something like that.

On Nov 19, 1:17 am, "Ian Lewis" <[EMAIL PROTECTED]> wrote:
> This isn't something that happens regularly. This error has only come
> about once as far as I can tell. It just isn't properly handled and I
> wondered what other folks did. Ideally we would have something like
> you described that retrys the writes but it occurs infrequenly enough
> that I think we can just catch it and return an error to the user.
>
> I'm curious what you did to catch the error and retry. Did you create
> a custom kind of DB backend? or did you just add that logic to the
> particular view that was giving you trouble?
>
> Ian
>
> On Wed, Nov 19, 2008 at 1:40 PM, DavidA <[EMAIL PROTECTED]> wrote:
>
> > Unrelated to Django, but we occasionally get deadlocks in MySQL due to
> > separate tasks running at the same time and accessing some tables in
> > common. We recently added logic to catch the exception, wait a second
> > or two, and retry it a few times before we give up. Most of the time,
> > that fixes it.
>
> > I agree with Malcolm, though, that for a pure Django app, I would
> > think it fairly unlikely to occur unless you are doing something non-
> > standard with your models/logic.
>
> > -Dave
>
> > On Nov 18, 8:52 pm, Malcolm Tredinnick <[EMAIL PROTECTED]>
> > wrote:
> >> On Wed, 2008-11-19 at 10:21 +0900, Ian Lewis wrote:
> >> > I've run into the following error in a SQL DB envornment and was
> >> > wondering if any one else had run into problems with Deadlocking with
> >> > MySQL. What would be the proper way to handle this kind of error in
> >> > Django?
>
> >> > Do most folks simply catch the OperationalError and show some sort of
> >> > error to the user?
>
> >> That sounds reasonable.
>
> >> More substantive for our purposes, though, would be knowing why this
> >> occurred and if there was any way to avoid it. Either you have a fairly
> >> twisted model setup that means an insert causes a deadlock, or there's
> >> something that can be improved in Django. So if you could post some
> >> details of how you are able to cause this error, it would be appreciated
> >> (by me, at least).
>
> >> Regards,
> >> Malcolm
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Flatpage App vs. Static Template

2008-11-21 Thread DavidA

I do something like you are suggesting: I actually write my "flat"
pages in Markdown since I prefer it to HTML, and I keep the contents
in a file instead of the database, so I can edit them with Emacs. Then
I just route these special pages to a trivial template that uses the
markdown filter to render them.

On Nov 21, 6:29 am, Caisys <[EMAIL PROTECTED]> wrote:
> Hi,
> I would like to publish some statics files on my website and I have a
> some questions:
> 1- The flatpage app examples likehttp://www.lawrence.com/about/staph/
> contain elaborate html, is this edited as a text field in the admin
> interface, wouldn't it be tedious to maintain?
> 2- Can i do something like point all pages/(?P\w+) to
> mysite.views.page_serve and create a view page_serve that accepts the
> page name as a parameter and reners_to_response a template with the
> same name?
> This way I can edit my static pages easily with my web development
> app?
> Is there anything wrong with doing the above.
> 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
-~--~~~~--~~--~--~---



Re: Is the initial value of a form field available in the template?

2008-12-01 Thread DavidA

> I think the basic issue is that there are some fields in the object
> that I'd like to display but not have editable, and it's not at all
> clear to me how to make that happen in the form processor. The values
> are dynamic, so they can't be in the template.

I often have this need so I created a custom widget where I just set
the readonly attribute on a TextInput widget:

class LabelWidget(forms.TextInput):
def __init__(self, *args, **kwargs):
attrs = kwargs.get('attrs', {})
attrs['readonly'] = True
if 'class' in attrs:
attrs['class'] = attrs['class'] + ' label'
else:
attrs['class'] = 'label'
super(LabelWidget, self).__init__(*args, **kwargs)

Then I use it in forms like this:

class AccountForm(forms.Form):
name = forms.CharField(widget=LabelWidget)
business = forms.CharField(widget=LabelWidget(attrs={'size': 5}))
...

I set/add 'label' to the CSS class so I can style these differently. I
used a custom widget over explicit "form.initial['field']" syntax in
my template so I could let the form lay itself out automatically
treating all fields the same way.

-Dave

On Dec 1, 1:45 pm, ChrisK <[EMAIL PROTECTED]> wrote:
> > I think you really need to explain what the real problem is that you're
> > trying to solve, because you're asking a question that is too specific.
>
> Fair enough. It's been several days, so I had to dredge a bit to
> remember :-)
>
> I think the basic issue is that there are some fields in the object
> that I'd like to display but not have editable, and it's not at all
> clear to me how to make that happen in the form processor. The values
> are dynamic, so they can't be in the template.
>
> I'm happy not to replicate the logic inside BoundField.as_widget(), if
> there's some way that the "correct" value is exposed to the
> template...
--~--~-~--~~~---~--~~
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: Reducing the number of my view's database queries

2008-12-08 Thread DavidA

If I undestand the problem correctly, in MySQL you could do this in
one query as:

select
m.*,
(select min(created) from model2 where id = m.model2_id) as
first_created,
(select max(created) from model2 where id = m.model2_id) as
last_created
from model1 m
;

I don't know how that translates to the Django ORM (or even if it
does), though.

-Dave

On Dec 8, 12:27 am, Malcolm Tredinnick <[EMAIL PROTECTED]>
wrote:
> On Sat, 2008-12-06 at 20:56 -0800, erikcw wrote:
> > Hi all,
>
> > I'm trying to write a model query that will return a queryset along
> > with the latest (and earliest) data from 2 related models.
>
> > Right now I'm doing something like this:
>
> > objects = Model1.objects.filter(user=3).select_related() #about 6,000
> > objects
>
> > data = {}
> > for o in objects:
> >     data[o.name] = [o.field1, o.field2]
> >     data[o.name].append(o.field3.model2_set.all().latest('created'))
> > #get latest row from related model2
> >     data[o.name].append(o.model3_set.all().order_by('created')[0])
> > #get earliest row from related model3
>
> > The problem is that this results in a TON of database queries.  This
> > view is taking over a minute to process.  The select_related on the
> > first line doesn't seem to be helping since I'm using latest()/
> > order_by which generates a new query.
>
> > How can I make this more efficient?  Denormalizing the isn't an option
> > since model2 and model 3 are many-to-one.
>
> By the way (since I still haven't worked out the complex SQL to make it
> three queries yet), this last statement isn't correct. Denormalising
> doesn't just mean flattening. You can store a computed dependent field
> in model1 for the related information. So you could, for example, store
> the relevant date and pk value of the related model2 row and update that
> whenever a new model2 is inserted.
>
> Malcolm
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Re: Problem loading custom PostgreSQL function at syncdb time.

2008-12-10 Thread DavidA

This sounds suspiciously similar to the problem I had with initial SQL
scripts in MySQL. In my case I was inserting rows into a table and one
of the string fields contained %. I had to "escape" the % (using %%).
I'm guessing that the SQL isn't directly executed but somehow
evaluated in the django.db bowels (didn't bother to track it down).

Is there a way to escape $'s in Postgres SQL (maybe with $$ or \$)?

Of course, I could be completely off base here, too...

-Dave

On Dec 10, 4:01 pm, Raymond Cote <[EMAIL PROTECTED]>
wrote:
> Hi Everyone,
>
> I'm having problems loading a custom PostgreSQL trigger function during
> syncdb and not sure how to address this:
> The function (trimmed down) looks as follows:
>
> CREATE OR REPLACE FUNCTION probe_data_insert()
>   RETURNS SETOF trigger AS $$
>
> DECLARE
>   ofs VARCHAR;
>
> BEGIN
>     NEW.collected_dt := NEW.received_dt;
>     RETURN NEW;
> END;
> $$  LANGUAGE 'plpgsql' VOLATILE;
>
> When I run that in PgAdmin2, it loads fine.
> However, when I try to load it with syncdb, I get the following error:
>
> Installing custom SQL for data.ProbeData model
> Failed to install custom SQL for data.ProbeData model: unterminated
> dollar-quoted string at or near "$$
>
> DECLARE
>   ofs VARCHAR;"
> LINE 2:   RETURNS SETOF trigger AS $$
>
> I found one reference on the net regarding the unterminated string that
> had to do with an old version of psql on the system. This is a clean OS
> install and I checked that psql 8.3.4 is the only one on the system.
>
> Any idea what I should be doing differently?
> Anyone have a sample of a PostgreSQL function that loads properly that
> they could share?
>
> Thanks
> --Ray
--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



Advice on form to create new object that has foreign key field

2008-12-13 Thread DavidA

I have two models, Trade and Fill. A Trade can have many fills. Fill
has a FK to Trade:

class Trade(models.Model):
trade_date = models.DateField(auto_now_add=True, editable=False)
side = models.CharField(max_length=12, choices=SIDE_CHOICES)
inst = models.ForeignKey(Inst)

class Fill(models.Model):
trade = models.ForeignKey(Trade)
quantity = models.DecimalField(max_digits=12,decimal_places=2)
price = models.DecimalField(max_digits=13,decimal_places=6)
fees = models.DecimalField
(max_digits=10,decimal_places=2,blank=True,null=True)
counterparty = models.CharField(max_length=12)
time = models.TimeField()
note = models.CharField(max_length=200, blank=True, null=True)

I have a web page that shows information about a Trade along with a
table of all the Fills for that trade. It also includes a form for
adding new Fills.

The problem I ran into was that in my view function for saving a new
Fill, I need to have the Trade instance set for the form to validate.
But it doesn't make sense for the user to edit the Trade since it's
tied to the one on the page they were viewing, so the default
ModelChoiceField doesn't work for this case.

Instead I created a custom field that stores the FK Trade id in a
hidden field and then resolves it back to the actual Trade instance in
the clean method:

class ModelField(forms.CharField):
def __init__(self, rel, *args, **kwargs):
super(ModelField, self).__init__(
widget=forms.HiddenInput, *args, **kwargs)
self.rel = rel
self.queryset = self.rel.to._default_manager.complex_filter(
self.rel.limit_choices_to)

def clean(self, value):
forms.Field.clean(self, value)
if value in (None, ''):
return None
try:
obj = self.queryset.get(pk=value)
except self.queryset.model.DoesNotExist:
raise ValidationError('Object not found for id: %s' %
value)
return obj

(I stole most of this from ModelChoiceField). I use it like this:

class FillForm(forms.ModelForm):
trade = ModelField(Fill._meta.get_field('trade').rel)
class Meta:
model = Fill

While this works, it feels like I'm digging into the internals of
Django too much with the _meta.get_field() and use of rel and queryset
in the ModelField.

Does anyone see a simpler solution to this? I feel like I'm missing
something obvious.

Thanks,
-Dave
--~--~-~--~~~---~--~~
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: Advice on form to create new object that has foreign key field

2008-12-13 Thread DavidA

The problem is that trade is required so is_valid will fail.

On Dec 13, 5:01 pm, Daniel Roseman 
wrote:
> On Dec 13, 9:30 pm, DavidA  wrote:
>
>
>
> > I have two models, Trade and Fill. A Trade can have many fills. Fill
> > has a FK to Trade:
>
> > class Trade(models.Model):
> >     trade_date = models.DateField(auto_now_add=True, editable=False)
> >     side = models.CharField(max_length=12, choices=SIDE_CHOICES)
> >     inst = models.ForeignKey(Inst)
>
> > class Fill(models.Model):
> >     trade = models.ForeignKey(Trade)
> >     quantity = models.DecimalField(max_digits=12,decimal_places=2)
> >     price = models.DecimalField(max_digits=13,decimal_places=6)
> >     fees = models.DecimalField
> > (max_digits=10,decimal_places=2,blank=True,null=True)
> >     counterparty = models.CharField(max_length=12)
> >     time = models.TimeField()
> >     note = models.CharField(max_length=200, blank=True, null=True)
>
> > I have a web page that shows information about a Trade along with a
> > table of all the Fills for that trade. It also includes a form for
> > adding new Fills.
>
> > The problem I ran into was that in my view function for saving a new
> > Fill, I need to have the Trade instance set for the form to validate.
> > But it doesn't make sense for the user to edit the Trade since it's
> > tied to the one on the page they were viewing, so the default
> > ModelChoiceField doesn't work for this case.
>
> > Instead I created a custom field that stores the FK Trade id in a
> > hidden field and then resolves it back to the actual Trade instance in
> > the clean method:
>
> 
>
> > While this works, it feels like I'm digging into the internals of
> > Django too much with the _meta.get_field() and use of rel and queryset
> > in the ModelField.
>
> > Does anyone see a simpler solution to this? I feel like I'm missing
> > something obvious.
>
> > Thanks,
> > -Dave
>
> Well, this does seem like a bit of overkill for what is after all a
> fairly common use case, if I'm understanding you correctly.
>
> Perhaps a better way would be not bother setting the FK value in the
> form at all, but to grab it from the request inside the view and use
> it there. For example:
>
> def add_fill(request, trade_id):
>     trade = get_object_or_404(Trade, trade_id)
>     if request.method == 'POST':
>         form = AddFillForm(request.POST)
>         if form.is_valid():
>             new_fill = form.save(commit=False)
>             new_fill.trade = trade
>             new_fill.save()
>     ... etc ...
>
> Does that work for you?
> --
> 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-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
-~--~~~~--~~--~--~---



Unable to delete inline model in admin that contains a FileField (...attribute has no file associated with it)

2009-09-25 Thread DavidA

I'm getting this error when I try to remove an inline model instance
in the Django admin:

Traceback:
File "C:\Python25\lib\site-packages\django\core\handlers\base.py"
in get_response
  92. response = callback(request, *callback_args,
**callback_kwargs)
File "C:\Python25\lib\site-packages\django\contrib\admin\sites.py"
in root
  490. return self.model_page(request, *url.split
('/', 2))
File "C:\Python25\lib\site-packages\django\views\decorators
\cache.py" in _wrapped_view_func
  44. response = view_func(request, *args, **kwargs)
File "C:\Python25\lib\site-packages\django\contrib\admin\sites.py"
in model_page
  509. return admin_obj(request, rest_of_url)
File "C:\Python25\lib\site-packages\django\contrib\admin
\options.py" in __call__
  1098. return self.change_view(request, unquote(url))
File "C:\Python25\lib\site-packages\django\db\transaction.py" in
_commit_on_success
  240. res = func(*args, **kw)
File "C:\Python25\lib\site-packages\django\contrib\admin
\options.py" in change_view
  835. change_message =
self.construct_change_message(request, form, formsets)
File "C:\Python25\lib\site-packages\django\contrib\admin
\options.py" in construct_change_message
  535.  'object':
force_unicode(deleted_object)})
File "C:\Python25\Lib\site-packages\django\utils\encoding.py" in
force_unicode
  71. s = unicode(s)
File "C:\private\src\itweb\..\itweb\controls\models.py" in
__unicode__
  160. return self.document.url
File "C:\Python25\lib\site-packages\django\db\models\fields
\files.py" in _get_url
  68. self._require_file()
File "C:\Python25\lib\site-packages\django\db\models\fields
\files.py" in _require_file
  46. raise ValueError("The '%s' attribute has no file
associated with it." % self.field.name)

Exception Type: ValueError at /admin/controls/review/24/
Exception Value: The 'document' attribute has no file associated
with it.

I can see that the file is being deleted on disk, but then it looks
like this error is being thrown when the admin is trying to display a
summary message of what was done, and that triggers a _require_file()
call which raises an exception.

I have the following models:

class Review(models.Model):
name = models.CharField(max_length=80)
review_type = models.CharField(max_length=20,
choices=REVIEW_TYPE_CHOICES)
frequency = models.CharField(max_length=20,
choices=FREQUENCY_CHOICES,
 null=True, blank=True)
description = models.TextField(null=True, blank=True)

class Evidence(models.Model):
review = models.ForeignKey(Review)
review_time = models.DateTimeField(null=True, blank=True)
reviewed_by = models.ForeignKey(User, null=True, blank=True)
document = models.FileField(upload_to='evidence/%Y/%m/%d')

And admin classes:

class EvidenceInline(admin.TabularInline):
model = Evidence

class ReviewAdmin(admin.ModelAdmin):
list_display = ['name', 'review_type', 'frequency',
'description']
list_filter = ['review_type', 'frequency']
search_fields = ['name', 'description']
fieldsets = [
(None,  {'fields':['name', 'review_type',
'frequency']}),
('Details', {'fields':['description']}),
]
inlines = [EvidenceInline]

admin.site.register(Review, ReviewAdmin)

Am I doing something wrong?

Thanks,
-Dave

--~--~-~--~~~---~--~~
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: Unable to delete inline model in admin that contains a FileField (...attribute has no file associated with it)

2009-09-25 Thread DavidA

Thanks, Karen. You were right - I had overridden it. If I delete the
__unicode__ method it works now. What's odd is that I can't seem to
catch any exception. If I try the code below, the admin still breaks.
And what's also odd is that I never see my models.py file in the stack
trace.

def __unicode__(self):
try:
return self.document.url
except:
return u'File deleted'

Thanks,
-Dave

On Sep 25, 10:36 am, Karen Tracey  wrote:
> On Fri, Sep 25, 2009 at 9:05 AM, DavidA  wrote:
>
> > I'm getting this error when I try to remove an inline model instance
> > in the Django admin:
>
> >    Traceback:
> >    File "C:\Python25\lib\site-packages\django\core\handlers\base.py"
> > in get_response
> >      92.                 response = callback(request, *callback_args,
> > **callback_kwargs)
> >    File "C:\Python25\lib\site-packages\django\contrib\admin\sites.py"
> > in root
> >      490.                 return self.model_page(request, *url.split
> > ('/', 2))
> >    File "C:\Python25\lib\site-packages\django\views\decorators
> > \cache.py" in _wrapped_view_func
> >      44.         response = view_func(request, *args, **kwargs)
> >    File "C:\Python25\lib\site-packages\django\contrib\admin\sites.py"
> > in model_page
> >      509.         return admin_obj(request, rest_of_url)
> >    File "C:\Python25\lib\site-packages\django\contrib\admin
> > \options.py" in __call__
> >      1098.             return self.change_view(request, unquote(url))
> >    File "C:\Python25\lib\site-packages\django\db\transaction.py" in
> > _commit_on_success
> >      240.                 res = func(*args, **kw)
> >    File "C:\Python25\lib\site-packages\django\contrib\admin
> > \options.py" in change_view
> >      835.                 change_message =
> > self.construct_change_message(request, form, formsets)
> >    File "C:\Python25\lib\site-packages\django\contrib\admin
> > \options.py" in construct_change_message
> >      535.                                              'object':
> > force_unicode(deleted_object)})
> >    File "C:\Python25\Lib\site-packages\django\utils\encoding.py" in
> > force_unicode
> >      71.                 s = unicode(s)
> >    File "C:\private\src\itweb\..\itweb\controls\models.py" in
> > __unicode__
> >      160.         return self.document.url
>
> You don't include this __unicode__ method in the code below, but this is
> likely where the problem is.  What the admin is trying to log is the unicode
> value of your deleted object.  I think you need to change your model's
> unicode method so that it does not trigger an exception when it is called
> for an instance that has no associated file.
>
> Karen
>
>
>
> >    File "C:\Python25\lib\site-packages\django\db\models\fields
> > \files.py" in _get_url
> >      68.         self._require_file()
> >    File "C:\Python25\lib\site-packages\django\db\models\fields
> > \files.py" in _require_file
> >      46.             raise ValueError("The '%s' attribute has no file
> > associated with it." % self.field.name)
>
> >    Exception Type: ValueError at /admin/controls/review/24/
> >    Exception Value: The 'document' attribute has no file associated
> > with it.
>
> > I can see that the file is being deleted on disk, but then it looks
> > like this error is being thrown when the admin is trying to display a
> > summary message of what was done, and that triggers a _require_file()
> > call which raises an exception.
>
> > I have the following models:
>
> >    class Review(models.Model):
> >        name = models.CharField(max_length=80)
> >        review_type = models.CharField(max_length=20,
> > choices=REVIEW_TYPE_CHOICES)
> >        frequency = models.CharField(max_length=20,
> > choices=FREQUENCY_CHOICES,
> >                                     null=True, blank=True)
> >        description = models.TextField(null=True, blank=True)
>
> >    class Evidence(models.Model):
> >        review = models.ForeignKey(Review)
> >        review_time = models.DateTimeField(null=True, blank=True)
> >        reviewed_by = models.ForeignKey(User, null=True, blank=True)
> >        document = models.FileField(upload_to='evidence/%Y/%m/%d')
>
> > And admin classes:
>
> >    class EvidenceInline(admin.TabularInline):
> >        model = Evidence
>
> >    cl

Is it possible to aggregate a field define in an extra method?

2009-10-08 Thread DavidA

I'm trying to understand how to use aggregation with "computed
columns", that is, columns that are expressions defined in the extra()
method, but it seems these aren't available in downstream parts of the
query:

class Trans(models.Model):
parent = models.ForeignKey('self', null=True, blank=True)
account = models.ForeignKey(Account, null=True, blank=True)
date = models.DateField(null=True, blank=True)
description = models.TextField(blank=True)
memo = models.TextField(blank=True)
quantity = models.FloatField(blank=True)
price = models.FloatField(blank=True)
class Meta:
db_table = u'trans'

>>> t = 
>>> Trans.objects.extra(select={'amount':'quantity*price'}).aggregate(total=Sum('amount'))
Traceback (most recent call last):
  File "", line 1, in 
  File "/Library/Python/2.6/site-packages/django/db/models/query.py",
line 277, in aggregate
is_summary=True)
  File "/Library/Python/2.6/site-packages/django/db/models/sql/
query.py", line 1471, in add_aggregate
field_list, opts, self.get_initial_alias(), False)
  File "/Library/Python/2.6/site-packages/django/db/models/sql/
query.py", line 1737, in setup_joins
"Choices are: %s" % (name, ", ".join(names)))
FieldError: Cannot resolve keyword 'amount' into field. Choices are:
account, date, description, id, memo, parent, price, quantity, trans
>>>

Am I going about this wrong? This is how I would do it in SQL:

select sum(quantity * price) as total from trans;

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: Types of projects Django is not well suited for?

2006-12-26 Thread DavidA



Saurabh  Sawant wrote:

How about the types of web applications for which Django is not well
suited for?


Saurabh,

I've been using Django for almost a year now and would have to say its
worked very well for most every type of application I've tried with it.
To name just a few:
- the obligatory blog app
- todo list manager
- scheduled task admin and reporting
- financial instrument editor (a form with over 100 fields)
- trade history tool
- data feed "builders" (form selection which builds data set returned
as Excel workbook)
- a grid editor that updates the database as each cell is modified
(like using Excel, based on YUI and YUI-ext).
- sparklines
- financial charts and graphs

Many of these build on tools that fall outside of Django but are
painless to integrate into the mix. That's one of the strengths of
Django - its so easy to add in what's not there.

There is, however, one important set of applications that I'm
struggling with. I would call these "drill-down reporting" or "OLAP
reporting" tools. The key problem is arbitrary grouping and aggregation
of data in the database. The Django DB-API has no real support for this
and while Django doesn't force you to use the DB-API, it sure makes
things a lot easier (most of the time).

Some people have pointed me to SQLAlchemy, but that doesn't really help
much here as its not aware of my models and doesn't really offer the
aggregation API that I need.

Custom SQL, while offering total flexibility, doesn't integrate with
the models at all so if your aggregated result sets include foreign key
fields, there is no way to automatically lookup related fields in the
template. You have to plan ahead and return all fields you'll ever want
to display in your custom SQL, which ties your views to your template
too much.

There has been some discussion about this general problem but not a lot
of progress on it yet. Django, like most community projects, has its
momentum focused on areas where there are enough people "itching" to
get the itch scratched (aside: I can't believe I'm paraphrasing ESR).
And that's probably how it should be.

But if you are working on a problem that very few people are looking
at, you might find the framework lacking and the community less
interested in your specific problem.

I don't see this as a failure of Django - I don't expect it to be all
things to all people - its just the nature of software, and you'll
always run into problems that you need to solve on your own or with
other tools.

Hope this helps,
-Dave


--~--~-~--~~~---~--~~
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: FloatField bug ?

2006-12-26 Thread DavidA



ak wrote:

A bit more info:

print user.tariff.monthly_fee.__class__, user.balance.__class__,
user.tariff.monthly_fee, user.balance, user.tariff.monthly_fee/3 >
user.balance

displays:

  180.00 1846.85 True

while 180/3 = 60 which is ofcourse less than 1846.85 so it should
display False in the last column


I've run into this: Django's FloatField is not really a Python float.
It creates a SQL numeric field in the DB. MySQLdb then maps the MySQL
numeric field to a Python decimal.Decimal value so that it retains the
full precision and range of the field. A Python float and
decimal.Decimal are not the same type and are not directly compatible:


import decimal
d = decimal.Decimal(180)
d

Decimal("180")

f = float(180)
d == f

False

float(d) == f

True

I wish there were a way to either (1) tell Django to use a real SQL
float field, or (2) tell MySQLdb to map the SQL numeric field to a
Python float, but I just live with the annoyance of doing wrapping all
my numeric model fields in float() all over my code.

I'm sure there is a better way and odds are that Malcolm will know it!
;-)

-Dave


--~--~-~--~~~---~--~~
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: Types of projects Django is not well suited for?

2006-12-26 Thread DavidA


Saurabh,

The other thing I was going to say was that what I really found helpful
about Django was the community and how patient and helpful they were.
And then I read the other replies to your question.

I don't know why everyone is giving you such a hard time. Sure, you
could have phrased your question a little bit better, but that's true
of many of the questions posted here. I guess no one got what they
wanted for Christmas and they are taking it out on you. Anyway, I hope
you hang around here long enough to realize that this thread is not
representative of the typical responses you'll get. And you'll also
realize that Django is an excellent framework for building _many_ types
of web applications.

-Dave


--~--~-~--~~~---~--~~
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: Why so slow?

2007-01-05 Thread DavidA


Is it possible your Apache server is doing reverse DNS lookups on the
GET requests and the lookup is failing for the client machine? I seem
to remember older versions of Apache having this on by default. You can
turn it off with this in your httpd.conf file.

   HostnameLookups off

Of course, I'm stabbing in the dark somewhat...
-Dave


--~--~-~--~~~---~--~~
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: What is the FloatField type returned when accessing the field value ?

2007-01-06 Thread DavidA


Chris,

I seem to recall running into this same issue using MySQL on Windows.
What version of MySQLdb are you using. If I'm remembering this
correctly, I was using an older version of MySQLdb which mapped DB
float/numeric fields to str and then I updated it and the newer version
mapped them correctly to Decimal.

Sorry I can't give you specific version numbers right now - I'd have to
dig around on my work machine.

-Dave


--~--~-~--~~~---~--~~
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: order_by with Foreign Keys

2007-01-12 Thread DavidA

I found this patch which fixes it. I've been using it for a while now:
http://code.djangoproject.com/ticket/2210

Honza Král wrote:
> this works fine, but if you forget the select_related() it will result
> in a cross join which is probably the last thing you want from your
> database...
>
> I was bitten by this when I specified this sort of ordering in the model...
>
> On 1/13/07, gordyt <[EMAIL PROTECTED]> wrote:
> >
> > Hi Carole,
> >
> > There is a workaround for this problem.  I am using the latest
> > subversion build of django, so I don't know if it works with the last
> > official build or not.
> >
> > Here is an example:
> >
> > ProductVersion.objects.select_related().order_by("kindledb_product.name","version_number")
> >
> > Here are the model definitions:
> >
> > class ProductVersion(models.Model):
> > product=models.ForeignKey(Product)
> > version_number=models.CharField(maxlength=16)
> > availability_date=models.DateField(null=True,blank=True)
> > release_notes=models.TextField(blank=True)
> >
> > class Product(models.Model):
> > name=models.CharField(maxlength=128)
> >
> >
> > Note that kindledb_product is the name of the database table that
> > stores the information from the Product.
> >
> > --gordon
> >
> >
> > >
> >
>
>
> --
> Honza Král
> E-Mail: [EMAIL PROTECTED]
> ICQ#:   107471613
> Phone:  +420 606 678585


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



Hiring Django/Python Developer

2007-02-06 Thread DavidA

Hi All,

I'm the CTO of a medium-sized hedge fund in Greenwich, CT and have
been the sole developer for our internal software projects. There's
too much on my plate for me to handle by myself and I'm looking to
hire a full-time Django/Python developer. I've been an avid reader and
occasional poster on this site and think the quality and friendliness
of people here is exactly what I'm looking for.

Here is the "official" job description I posted on a couple other
sites:
---
Plainfield Asset Management LLC, a hedge fund focusing on distressed
debt, is seeking a full-time Python Web Developer. This position will
be responsible for working on internal proprietary applications for
all departments including trading, operations, research and risk
management.

Candidates will need to have an understanding and comfortable working
knowledge of Python, HTML and CSS. Candidates should also be familiar
with at least some of the key technologies in our environment
including Windows, Apache and MySQL. Any experience with Django is a
(big) plus. Previous experience in financial services is not required.

The environment is friendly and relaxed and offers the opportunity to
work on interesting problems from both a technical and business
perspective.

Plainfield offers comprehensive benefits including medical, dental and
401k. Lunches and refreshements are also provided.
---
If you are interested and think you might be a good fit, please send
me your resume. Note that the job requires you to work in our office
as there is a need for lots of interaction with the users.

Send your resume to:
>>> ''.join([ ''.join(p) for p in zip('[EMAIL PROTECTED]', 'ai.vamdspa.o 
>>> ')]).strip()  # ;-)

-Dave


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



Django effects Python time/datetime and gives wrong time after DST update

2007-03-12 Thread DavidA

I have some scripts that run tasks and use Django DB models. They have
been running an hour late today after all the DST changes (here in the
US). I've traced it down to any call to Django is shifting my time
back an hour (like it was before this weekend's shift).

So the time as reported by time.time() and datetime.datetime.now() are
both correct _before_ this call:

  task = Task.objects.get(pk=opts['--taskid'])

where Task is a Django DB model. But immediately after this call both
time.time() and datetime.datetime.now() return a time an hour earlier
(after formatting using strftime).

I'm running under Windows 2003 Server (patched for DST and verfied
that the OS is patched). And I have TIME_ZONE set to 'EST5DT' in my
Django settings file.

I've tried manually setting the TIME_ZONE variable using
django.conf.settings.configure so it wouldn't effect the
os.environ['TZ'] setting, but then all python time seems to be based
as UTC, not New York time.

Has anyone seen anything similar? Can someone suggest a fix or at
least a quick workaround?

Thanks,
-Dave


--~--~-~--~~~---~--~~
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: Django effects Python time/datetime and gives wrong time after DST update

2007-03-12 Thread DavidA

I found a workaround but I'm not sure what the ramifications are. I
commented out this line in django.conf.__init__.py:

os.environ['TZ'] = self.TIME_ZONE

On Mar 12, 10:19 am, "DavidA" <[EMAIL PROTECTED]> wrote:
> I have some scripts that run tasks and use Django DB models. They have
> been running an hour late today after all the DST changes (here in the
> US). I've traced it down to any call to Django is shifting my time
> back an hour (like it was before this weekend's shift).
>
> So the time as reported by time.time() and datetime.datetime.now() are
> both correct _before_ this call:
>
>   task = Task.objects.get(pk=opts['--taskid'])
>
> where Task is a Django DB model. But immediately after this call both
> time.time() and datetime.datetime.now() return a time an hour earlier
> (after formatting using strftime).
>
> I'm running under Windows 2003 Server (patched for DST and verfied
> that the OS is patched). And I have TIME_ZONE set to 'EST5DT' in my
> Django settings file.
>
> I've tried manually setting the TIME_ZONE variable using
> django.conf.settings.configure so it wouldn't effect the
> os.environ['TZ'] setting, but then all python time seems to be based
> as UTC, not New York time.
>
> Has anyone seen anything similar? Can someone suggest a fix or at
> least a quick workaround?
>
> Thanks,
> -Dave


--~--~-~--~~~---~--~~
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: Django effects Python time/datetime and gives wrong time after DST update

2007-03-12 Thread DavidA

Thanks. I am on trunk, 4227 so I don't have this fix.

On Mar 12, 10:53 am, "Ramiro Morales" <[EMAIL PROTECTED]> wrote:
> On 3/12/07, DavidA <[EMAIL PROTECTED]> wrote:
>
>
>
> > I found a workaround but I'm not sure what the ramifications are. I
> > commented out this line in django.conf.__init__.py:
>
> > os.environ['TZ'] = self.TIME_ZONE
>
> What version/revision of Django are you using?.
>
> See ticket #2315 and changeset [4487] for some work donde
> in the Windows time zone stuff front.
>
> Regards,
>
> --
>  Ramiro Morales


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



Question about inspectdb output

2006-02-26 Thread DavidA

I'm experimenting with 'inspectdb' so I can use Django on an existing
database. I was curious to see what inspectdb would return for the
tutorial tables (Polls, Choices) and was confused by the output:

class PollsChoice(meta.Model):
id = meta.IntegerField()
poll_id = meta.IntegerField()
choice = meta.CharField(maxlength=600)
votes = meta.IntegerField()
class META:
db_table = 'polls_choices'

class PollsPoll(meta.Model):
id = meta.IntegerField()
question = meta.CharField(maxlength=600)
pub_date = meta.DateTimeField()
class META:
db_table = 'polls_polls'

Why are the choice and question fields maxlength of 600 when they were
specified as 200 in the model? I also tried on a different table I
created with a varchar(40) field and it came back with maxlength of 120
so it seems to consistently multiply the length by 3 (I'm using MySQL
4.1.18).


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



Re: Django in a Load-Balanced environment (ORM issues) ...

2006-03-01 Thread DavidA

I just want to echo Peter and Ivan's sentiments on NOT making this
default behavior. What attracted me to Django was a simple, fast,
elegant framework for quickly building common types of web
applications. I've wandered into the tarpits of J2EE in my past life
and I was looking for something at the other end of the
complexity/usability spectrum. Django is just that. I'd hate to see the
project bog down focusing on features that consume 80% of the dev
resources and are useful to only 20% of the community. And certainly if
this type of functionality is ever added it should be completely
separate and off by default.

Sometimes less is more.


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



Re: Question about inspectdb output

2006-03-01 Thread DavidA

I found the cause of this magic "multiply by 3" but I don't understand
it well enough to offer a solution. In the mysql backend, there is this
clause (lines 69-70 in DatabaseWrapper.cursor):

if self.connection.get_server_info() >= '4.1':
cursor.execute("SET NAMES utf8")

Setting the connection to use utf8 has the side effect of returning
lengths 3 times their number of chars in the cursor.description() call
as this demonstrates:

>>> import MySQLdb
>>> cn = MySQLdb.connect(user='root',db='data',passwd='hejphund')
>>> cu = cn.cursor()
>>> cu.execute('select investId from trade limit 1')
1L
>>> cu.description
(('investId', 253, 3, 40, 40, 0, 0),)
>>> cu.execute('set names utf8')
0L
>>> cu.execute('select investId from trade limit 1')
1L
>>> cu.description
(('investId', 253, 3, 120, 120, 0, 0),)
>>>

Note that before the 'set names utf8' the data lenght of the field is
40 (it was created as a varchar(40) field). But after the 'set names
utf8' it shows a length of 120.

I guess that by default MySQL 4.1+ uses unicode so when you say you are
creating a column of varchar(40) that's really 40 unicode chars and
MySQL must use 3 bytes per unicode char. Then when you change the
connection to use UTF8 it is showing you the number of bytes (UTF8
chars) for the length.

But I don't understand if this is a problem to worry about or not.

Note: I also tried doing 'set names utf8' *before* I created my table
but it had no effect.


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



Confusion about templates directory location

2006-03-14 Thread DavidA

I'm a little confused about the "right" place to put templates for an
app. In my mind, the templates are going to be specific to the
application, thus the obvious place to put the templates directory is
in the app directory. Ex:

  /some_path/
  myproject/
  myapp/
  models/
  templates/

and then you would set TEMPLATE_DIRS in settings.py to
'/some_path/myproject/myapp/templates'

But then the template loaders always want to look for a template within
yet another app subdirectory (i.e. TEMPLATE_DIRS + '/myapp/base.html').
Isn't that redundant? It seems if my TEMPLATE_DIR is "x" and my
template is "y" the loader should try and load "x/y" not "x//y".
Wouldn't that be more consistent with how other files like models are
located?

I'm sure I'm just misunderstanding some design concept of Django, but
I'd appreciate if someone could explain this. And is there a "default"
place I can put templates where I won't need to set TEMPLATE_DIRS to
just keep it simpler?

Thanks,
-Dave


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



Re: Confusion about templates directory location

2006-03-15 Thread DavidA

Thanks. After thinking about it some more, now the idea of having app
directories beneath the templates directory makes sense: I will have a
project-level banner and nav bar that will be used by multiple apps. So
I moved my templates directory back to where it was, right under the
project directory.

One other thing that tripped me up - it seems the template loaders
cache the search paths at startup so if you create new directories you
need to restart the server to find them.


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



Help getting admin and non-admin app running in Apache

2006-03-22 Thread DavidA

I've read this documentation:
http://www.djangoproject.com/documentation/modpython/
but I can't figure out how to configure the VirtualHost section to get
the URLs I want.

Here's what I'm trying to do:
I have one Django project (data) with two apps under it (trades,
marks). I also have the admin app installed. I have setup a CNAME alias
for 'data' to point to my server (Win 2003 Srv) running Apache2 and
Django 0.91.

I want
- http://data/trades to go to my trade app
- http://data/marks to go to my marks app
- http://data/admin to go to the admin app for this project

It kind of works but I frequently get the TemplateSyntaxError message
that the above document is supposed to fix when I go to the admin site.
The problem is that I can't figure out how to map the advice in that
document to my Apache config. Here it is:
--
NameVirtualHost *

ServerName data
DocumentRoot "C:/Dev/Source/Web/data"
SetHandler mod_python
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE data.settings
PythonPath sys.path+['C:/Dev/Source/Web']
PythonDebug On
PythonAutoReload On
Alias /admin-media/
"C:/Python24/Lib/site-packages/Django-0.91-py2.4.egg/django/contrib/admin/media/"

SetHandler none


--

And my urls.py is:
--
from django.conf.urls.defaults import *

urlpatterns = patterns('',
(r'^trades/', include('data.trades.urls')),
(r'^marks/', include('data.marks.urls')),
(r'^admin/', include('django.contrib.admin.urls.admin')),
)
--

It seems like I'd have to create three additional Location sections
(marks, trades, admin) but that kinds of defeats the purpose of the
urls.py file.

BTW, I've never gotten the PythonAutoReload to work either.

Thanks,
-Dave (Apache noob)


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



Advice on using model to bulk/batch load database

2006-03-22 Thread DavidA

I am prepopulating my database with data from a number of flat files.
I've written a small script to do this using my model class. While this
works, there are a couple of kludges I made to get it to work and I was
hoping someone could advise my on a better way to do this.

First, to use the model from a script I had to set the
DJANGO_SETTINGS_MODULE environment variable and add the base directory
to sys.path. I've seen this before so I guess this is just the way it
is but it would be nice not to have dependencies on environment
variables. Is there a different way to do this?

Second, I'm using a manipulator to convert string values from the file
to python values but the do_html2python method expects a POST which
isn't quite the same as a dict. I had to write a little wrapper dict to
make it compatible:

class MyDict(dict):
def getlist(self, key):
return (self[key],)

def setlist(self, key, value):
self[key] = value[0]

Again, not a big deal but it seems kludgy and I thought there might be
a better way. Any ideas?

Finally, for dates I had to manually convert them because they weren't
in the -mm-dd format required by DateField.html2python. It seems a
bit limited to only support one date format in DateField but I guess
that avoids the ambiguities with date formats. Since my model's fields
are the same names as the column headings in the flat files, now I can
map all the conversions automatically without doing anything
field-specific, *except* for date fields. Any suggestions?

Thanks,
-Dave


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



Re: Advice on using model to bulk/batch load database

2006-03-23 Thread DavidA

> You can set the environment variable at the top of your scripts by
> importing the Python os module, just like you can import sys and set
> sys.path.

Thanks, I added this and it works fine:

os.environ['DJANGO_SETTINGS_MODULE'] = 'data.settings'

> The Python datetime and time modules are huge resources.  In this case
> you want time.strptime() to parse an arbitrary time format into a tuple
> and then you can use that tuple to create a datetime.date object which
> you can directly assign to the DateField.

I had already done that - I was hoping I could tell the DateField what
format it should expect the date in when it parses it via html2python.
Something like:

myDateField.inputFormats = ['%d-%b-%y', '%m/%d/%y']

and then when I call html2python on it (indirectly via the manipulator)
it will try each of those until it gets a valid date back. Right now,
DateField is hardwired to use '%Y-%m-%d', so I'm pre-converting all
date fields before I send the row from the file to the manipulator.
Like I said, its a small detail, just the one place where I my
parser/loader needs to be aware of the type of columns and I was hoping
to eliminate that.

Thanks,
-Dave


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



Re: Advice on using model to bulk/batch load database

2006-03-23 Thread DavidA

> BTW, if you do this repeatedly and format of those flat files is not a
> requirement it is possible to have all initial data in a form of SQL
> script. If you place it in /sql/.sql then Django will
> include it in 'sqlall' command right after DB creation.

While I'm not in control of the file format in this case, your
suggestion will help solve a different problem I have: I use full-text
searching on some of my tables and I was manually running a little sql
script after I did a 'manage.py sqlall  | mysql ...':

CREATE FULLTEXT INDEX ix_ft_trade_all
ON trade (tradeType, investIdType, investId, portfolio, book,
strategy,
  counterparty, custodian, account);
...

and then I use the where form of get_list(...,
where=["match() against('')"]) to search
for them in one of my views.

Your suggestion automates that step (which I forget to do quite a bit!)

> You can use the very class that is used for POSTs - MultiValueDict. It's
> in django.utils.datastructures:
>
> from django.utils.datastructures import MultiValueDict
> d = MultiValueDict(your_dict)

I made the change and its working fine. One thing you have to be
careful with is to build a MultiValueDict where the values are
lists/tuples. I was putting scalars in and it was interpreting strings
as sequences which caused problems in do_html2python.

-Dave


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



Re: Help getting admin and non-admin app running in Apache

2006-03-23 Thread DavidA

That still leaves my Django apps running in the same space
(PythonInterpreter) as the admin app which I think is the root of the
problem. I've tried using a separate  for "/" and "/admin/"
but that didn't work. I don't see how its possible to separate my
non-admin apps from the admin app since they are both defined in the
same settings and urls files.

Should I just create a new project that uses a copy of the settings
file but only install the admin app? But then I'd have to install new
apps in both places.

I must be doing something wrong because it can't be that hard to do
what I'm trying to do. Isn't the typical setup for most people to have
both thier custom apps and the admin app all installed in the same
project and all working together?

No matter what I try I always get the same results: my apps work fine,
the main page of the admin app works, but whenever I click on one of my
models to look at the data, I get the dreaded TemplateSyntaxError:

Mod_python error: "PythonHandler django.core.handlers.modpython"

Traceback (most recent call last):

  File "C:\Python24\Lib\site-packages\mod_python\apache.py", line 299,
in HandlerDispatch
result = object(req)

  File
"c:\python24\lib\site-packages\Django-0.91-py2.4.egg\django\core\handlers\modpython.py",
line 165, in handler
return ModPythonHandler()(req)

  File
"c:\python24\lib\site-packages\Django-0.91-py2.4.egg\django\core\handlers\modpython.py",
line 139, in __call__
response = self.get_response(req.uri, request)

  File
"c:\python24\lib\site-packages\Django-0.91-py2.4.egg\django\core\handlers\base.py",
line 109, in get_response
return self.get_technical_error_response(request)

  File
"c:\python24\lib\site-packages\Django-0.91-py2.4.egg\django\core\handlers\base.py",
line 139, in get_technical_error_response
return debug.technical_500_response(request, *sys.exc_info())

  File
"c:\python24\lib\site-packages\Django-0.91-py2.4.egg\django\views\debug.py",
line 126, in technical_500_response
return HttpResponseServerError(t.render(c), mimetype='text/html')

  File
"c:\python24\lib\site-packages\Django-0.91-py2.4.egg\django\core\template\__init__.py",
line 146, in render
return self.nodelist.render(context)

  File
"c:\python24\lib\site-packages\Django-0.91-py2.4.egg\django\core\template\__init__.py",
line 707, in render
bits.append(self.render_node(node, context))

  File
"c:\python24\lib\site-packages\Django-0.91-py2.4.egg\django\core\template\__init__.py",
line 725, in render_node
result = node.render(context)

  File
"c:\python24\lib\site-packages\Django-0.91-py2.4.egg\django\core\template\defaulttags.py",
line 112, in render
nodelist.append(node.render(context))

  File
"c:\python24\lib\site-packages\Django-0.91-py2.4.egg\django\core\template\defaulttags.py",
line 179, in render
return self.nodelist_true.render(context)

  File
"c:\python24\lib\site-packages\Django-0.91-py2.4.egg\django\core\template\__init__.py",
line 707, in render
bits.append(self.render_node(node, context))

  File
"c:\python24\lib\site-packages\Django-0.91-py2.4.egg\django\core\template\__init__.py",
line 735, in render_node
raise wrapped

TemplateSyntaxError: Caught an exception while rendering.


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



Re: Advice on using model to bulk/batch load database

2006-03-23 Thread DavidA

Eric,

The typical mode of operation will be to incrementally load new data
each night - about 10 files each containing dozens to hundreds of rows.
Maybe only a couple will be in the thousands category. But I've also
created my scripts to work in two steps: 1) download the data from
various sources (FTP, HTTP, web scrape, custom API) and save the files
on a server, 2) parse any new files and load into the database.

Occasionally I will modify my schema, drop the old tables and reload
all the data from the "cached" files. Over time that could easily be
millions of rows and some optimization of my technique will be in
order. But for now, the simple approach (parse a row, create a django
model object, stuff it and save it) works fine.

-Dave


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



Re: Advice on using model to bulk/batch load database

2006-03-23 Thread DavidA

My motivation for using the Django ORM layer was simply to reuse the
logic that parses text values to native values (html2python) and any
column name mapping that goes on, both of which are managed by the
*Field members. I know that's not a huge win, but since I'm at an early
point in the project where I'm tweaking the schema quite a bit, its
nice to know if I change an int field to a float, or add another field
that was previously being skipped from the file, or rename a column, it
just works. But I see your point - it remains to be seen if I'm getting
enough benefit to justify this approach.

Speed really isn't an issue right now. Each file takes a few seconds to
load (up to a minute for the really large ones) and they run as
scheduled jobs over night. And this is all running on a VMWare virtual
machine on my lowly Dell desktop - I could copy the VM to a server and
get a huge boost.

If I _really_ cared about speed, since I'm using MySQL, I'd consider
mapping a table directly to the file via the CSV storage engine and
then just copy it from the CSV table to a "real" table.


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



Error in saferef.py?

2006-04-08 Thread DavidA

I just switched to the m-r branch and am seeing this error very
frequently:

Exception exceptions.AttributeError: "'NoneType' object has no
attribute 'print_exc'" in  ignored

>From a search of the code, it appears to be line 113 in
django/dispatch/saferef.py. However, I'm unsure if its an error in the
code or just a side-effect of something I'm doing wrong.

Does anyone more familiar with the code know if this is an error, and
if not, what I might look for in my code as the problem?

Thanks,
-Dave


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



Need to reload model object after saving?

2006-04-10 Thread DavidA

The DateTimeField of my object has 'auto_now_add' set to true on it.
But I can't see the value of the field after saving, unless I reload
it. Is this intended behavior?

>>> from plainfield.tasks.models import Task, Run
>>> t = Task.objects.get(name__exact='Test')
>>> r = Run(task_id=t, command='')
>>> r.id# No id yet since not saved
>>> r.save()
>>> r.id# now its there
9L
>>> r.startTime # but startTime, an 'auto_now_add' DateTimeField is not set
>>> r = Run.objects.get(pk=9)
>>> r.startTime # but it is after reloading.
datetime.datetime(2006, 4, 10, 13, 31, 53)
>>>

Note that startTime, which is defined as:
startTime = models.DateTimeField(auto_now_add=True)
gets set properly but I can't see it unless I explicity reload the Run
object. I would have thought that after calling save, in addition to
the 'id' field being set, all the default values would also be set. It
works for default BooleanFields but not for this DateTimeField.

Maybe auto_now_add is handled back in the database? Anyway seems a
little inconsistent and potentially a bug.

Thanks,
-Dave


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



Re: Problem with threads accessing MySQL database

2006-04-12 Thread DavidA

Hi kopikopiko,

I thought I'd chime in on how I'm solving a similar problem. I also
have a task scheduling app written in Django, but I actually run the
tasks through Django rather than outside of it: I have a special view
(/tasks/trigger) which remembers the last time the view ran and checks
for any tasks that should have run since the last trigger time. It then
simply loads and runs each task in sequence.

Outside of Django I have a schedule NT/Windows task that runs every 5
minutes and just does an HTTP get of the trigger view url.

I can get away with this since my tasks are simple and usually take a
few seconds to run so I don't mind running them synchronously. I did
think about your approach, though, and I was going to load all the DB
data that defines the task, then fire off the task on a background
thread, then have those tasks update the DB with their stats directly
(each making their own MySQL connection and doing direct SQL). I was
going to do it that way since I didn't want my task scripts to be
dependent on Django's ORM.

But like I said, I never went down the multi-threaded route because I
wanted to keep it simple and at this point, I don't need to.
-Dave


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



Understanding FloatFields

2006-04-13 Thread DavidA

I'm a little confused about FloatFields and I was hoping someone could
shed some light. They seem to be represented in the DB as 'numeric' but
exist in Python as strings:

class FundCapital(models.Model):
fund = models.ForeignKey(Fund)
date = models.DateField()
capital = models.FloatField(max_digits=14, decimal_places=2)

C:\Dev\Source\Web\plainfield>manage.py sql data
BEGIN;
CREATE TABLE `data_fundcapital` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`fund_id` integer NOT NULL REFERENCES `data_fund` (`id`),
`date` date NOT NULL,
`capital` numeric(14, 2) NOT NULL
);
COMMIT;

>>> from plainfield.data.models import FundCapital
>>> fc = FundCapital.objects.all()[0]
>>> fc.date
>>> fc.capital
'16200.00'
>>> type(fc.capital)

>>> fc.capital = 1000
>>> fc.capital
1000
>>> fc.save()
>>> fc = FundCapital.objects.all()[0]
>>> fc.capital
'1000.00'
>>> float(fc.capital)
1000.0

I ran into problems in my __repr__ method where I was trying to format
the field using %f which doesn't work.

Is a string used so it can represent the actual precision? I saw an old
posting referring to use of Decimal for FloatFields but I don't see
that in the code, the docs, or my example.

Is the convention to just use float() or Decimal()
whenever I need to use it as a number?

Thanks,
-Dave


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



Re: Importing external modules/classes

2006-04-14 Thread DavidA

Hi Cary,

What I did to avoid all the PYTHONPATH stuff was to just 'install' my
python library using distutils. I set up a trivial setup.py script and
then I just run 'python setup.py install' for my library whenever I
make changes.

from distutils.core import setup

setup(name='pf',
  version='0.1',
  packages=['pf', 'pf.utils', 'pf.task'],
)

While forgetting to install changes has tripped me up once or twice,
I've done this enought that its "wired" into my fingers now. While this
might seem a bit of overkill, using distutils is so simple that I don't
mind it.
-Dave


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



Bug in django/contrib/admin/templatetags/admin_list.py

2006-04-14 Thread DavidA

If you use a FloatField in the admin list_display, you get an error
rendering the template from line 160 in admin_list.py (TypeError, float
argument required)

158.elif isinstance(f, models.FloatField):
159.if field_val is not None:
160.result_repr = ('%%.%sf' % f.decimal_places) %
field_val
161.else:
162.result_repr = EMPTY_CHANGELIST_VALUE

This comes back to a previous post I had about FloatFields - they are
stored as strings so you can't use it directly in a %f format. I think
the line should be:

160.result_repr = ('%%.%df' % f.decimal_places) %
float(field_val)

But I'm not sure if that should be float() or Decimal().

I'm not sure what the process is to report things like this - and I'm
not a member of django-developers so I just posted it here.

Thanks,
-Dave


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



Re: Tutorial for MR

2006-05-04 Thread DavidA

But for every model? Sounds a little kludgy to have to add that to
every model just to break them into separate files.


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



Re: DSN useful for database settings?

2006-05-09 Thread DavidA

Can't you just accomplish the same goal by adding a couple of lines to
your settings file? Assuming you had an environ variable DSN set like
this:

DSN=ENGINE=mysql;NAME=data;USER=root;PASSWORD=redpill;HOST=localhost

then add:

import os
dsn = dict([kv.split('=') for kv in os.environ['DSN'].split(';')])
DATABASE_ENGINE = dsn['ENGINE']
DATABASE_NAME = dsn['NAME']
...

I'm under Windows so you might want to choose different delimiters than
'=' and ';' but you get the idea.

I guess it just seems like its easy enought to do in Python directly,
why would you need to really add a new feature to Django for this?

My two cents...


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



Re: There is no v0.92 or v0.95 release of Django

2006-05-17 Thread DavidA

I just googled: django 0.95 site:www.djangoproject.com

and found one other thing that could be potentially confusing:

http://www.djangoproject.com/documentation/tutorial1/
The sample output under "The development server" section shows: Django
version 0.95 (post-magic-removal).

Of course, that is the actual output if you are running the trunk, so
this may be where people are getting the idea that there is indeed a
0.95 release. Maybe someone should patch the comment so it just says
"Django trunk (post-magic-removal)"?


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



Re: I need instructions in best way to use django under IIS shared hosting (Python is installed)

2006-05-25 Thread DavidA

I've used Python with IIS for the MoinMoin wiki (where do they get
these names?). They have a good doc on configuring IIS for Python:
http://moinmoin.wikiwikiweb.de/HelpOnInstalling/InternetInformationServer#head-890abdbd0d21bf874ce794be87067abf433a51d7

I've done it. It works fine. And then I woke up and installed Apache
and turned off the IIS service.

Note that if you are stuck on Windows, Apache + mod_python + MySQL +
Django works very well. I run that at work and do a lot of my personal
Django development on that and then just "svn up" and "service httpd
restart" on my Linux box to roll out changes.


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



Re: I need instructions in best way to use django under IIS shared hosting (Python is installed)

2006-05-25 Thread DavidA

I should have clarified: I use Apache2 on Windows (and Linux for that
matter). As Ian pointed out, Apache2 is multi-threaded and works very
well on both Linux and Windows.


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



Re: I need instructions in best way to use django under IIS shared hosting (Python is installed)

2006-05-25 Thread DavidA

> Ok. So if work, what reason you have for ditch it for Apache?

There were really four reasons I moved from IIS to Apache:
1) Virtual hosting: although you _can_ do virtual hosting on IIS, you
really need IIS6 on Win2k3 to support the host header fields. The
default IIS on XP Pro doesn't allow this and I wanted my dev and prod
environments to behave the same way. Apache's virtual hosting support
is a head and shoulders above IIS, in my opinion.
2) Performance: while I don't have specific numbers at hand, the IIS
configuration (of Django and the MoinMoin wiki) always felt a little
sluggish for what should have been snappy apps. I tried them out under
Apache2 and they felt much more responsive. I can't really say if I was
using IIS in the best way, but I did the quick-and-dirty setup in both
IIS and Apache2 and Apache seemed faster. I especially notice this when
I haven't accessed a page in a while. It seems that IIS takes a while
to "warm up" but once it does its not bad. Apache seems to always be
pretty fast.
3) Consistency: I like that my configuration on Windows and Linux is
very similar now. And I've even been thinking of buying a Mac so that
becomes even more important.
4) Community/documentation: once I decided to start using Python, MySQL
and now Django, I find it a lot easier to find information on the web
for using Apache with those technologies. Its sort of the "go with the
grain" mentality. I didn't want to run into the very kinds of problems
you are now - where its hard to find good examples of how to use the
various technologies you have chosen.

I used to be a C#/ASP.NET guy so I have used IIS quite a bit. Its not
bad, and I haven't had the problems with security that other note - at
least not in any of the more recent versions of Windows and IIS. But I
just find for the development platform I've chose, Apache is a better
fit than IIS. That's 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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~--~~~~--~~--~--~---



Re: views

2006-05-26 Thread DavidA

Mary,

If I'm understanding you correctly you can simply use the 'values'
method of the DB-API to query the value of the field for all rows:

>>> from danet.blog.models import Post
>>> Post.objects.values('slug')
[{'slug': 'yet-another-django-blog'}, {'slug':
'fun-at-home-and-zoes-first-birth
day'}, {'slug': 'florida-feb-06'}, {'slug':
'probability-and-expectation'}, {'sl
ug': 'author'}, {'slug': 'sample-article'}, {'slug': 'christmas-2004'},
{'slug':
 'letters-to-eli'}, {'slug': 'snow-day-january-2005'}, {'slug':
'favorites'}, {'
slug': 'encrypted-usb-backups'}, {'slug': 'aspnet-2'}, {'slug':
'code-highlighti
ng'}, {'slug': 'multiple-main'}, {'slug': 'strcpy'}, {'slug':
'zoes-arrival'}, {
'slug': 'getting-nia'}]
>>>

This returns a list of dictionaries. You can just extract out the
values with:

>>> x = Post.objects.values('slug')
>>> [d['slug'] for d in x]
['yet-another-django-blog', 'fun-at-home-and-zoes-first-birthday',
'florida-feb-
06', 'probability-and-expectation', 'author', 'sample-article',
'christmas-2004'
, 'letters-to-eli', 'snow-day-january-2005', 'favorites',
'encrypted-usb-backups
', 'aspnet-2', 'code-highlighting', 'multiple-main', 'strcpy',
'zoes-arrival', '
getting-nia']
>>>

If you want to get them in a certain order, or filter them first, then
you can use the 'order_by' and 'filter' methods.


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



Re: What server configuration to use

2006-05-26 Thread DavidA

I'm running my Django blog (http://davidavraamides.net) on Fedora under
VMWare GSX 3.1. I have it configured for 256M (the physical box has
1GB). There is another Fedora guest running phpBB similarly configured.
My typical load across all VMs is about 3%. It works great. Both are
running Apache + MySQL.

-Dave


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



Re: Django and daemon?

2006-05-31 Thread DavidA


Russell Blau wrote:
> Ahh, thanks, it always helps to take the blinders off.  The only downside is
> that I have to learn how to use yet another software package.  ;-)

An alternative that stays inside Django is to setup a trigger in cron
(or NT's Task Scheduler) that gets a URL every few minutes and the view
code for that URL does the email processing you mention. You avoid
creating a true daemon/service just by "waking" up periodically and
doing any work that needs to be done.

I use this technique for a scheduled task application written in
Django. It works well, avoids the threading issues, and in my case is
good enough for the problem at hand.


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



Re: Wiki or Blogs done with django

2006-06-01 Thread DavidA


Jarek Zgoda wrote:
> I second that. Actual code may vary, but domain model (and its
> representation as Django data model) would remain constant, as long as
> software will be performing similar tasks.

Well, maybe. I think its really hard in any real application to have a
one-size-fits-all data model. Even for something as seemingly simple as
a blog, I think its a tough challenge. I, too, am one of the people who
wrote their own blog in Django. I did it more as a project to force me
to learn some of the less obvious things about Django then for the goal
of having a blog (I ported from WordPress once I got the basics
working).

Even if such a "standard" project existed, I probably would have opted
to start from scratch to just learn it - but my motivation might be the
exception, not the norm.

In any case, I think what you might end up with are a few model classes
that have *many* optional fields to accomodate different uses. Just
look at the comments model right now: it has 20 fields. My Post and Tag
models have 8 and 3 fields, respectively.

I think the right way to do it is to follow the Django approach with
User: keep the generic model as stripped down as possible and let
people extend it through subclassing (when that works, or via
relationships for now).

But I am +1 on the idea of a community blog project for things like
photos, pingbacks, captcha, etc. The comments add-in is a good example
of the building blocks I'd like to see, and use in my own project.


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



Re: Please help with project setup

2006-06-01 Thread DavidA

Kristoffer wrote:
> So, I have decided to use Docutils now, but I am a bit lost.
> How do I do this http://code.djangoproject.com/wiki/UsingMarkup with
> Docutils?
>
> Thanks,
> Kristoffer

Kristoffer,

I think that document is a little misleading. Its more about saving the
post-processed HTML output from one of the markup filters *in* your
model to increase the performance of your site. Its not necessary to
use one of the markup filters.

I have a post on my blog where I describe how I added markdown support.
You should be able to follow the same steps, but instead of
  {{ object.body|markdown }}
you would use
  {{ object.body|restructuredtext }}

Of course you need to install Docutils, first.

http://davidavraamides.net/blog/2006/05/23/markdown-support/

-Dave


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



Re: A little help with a filter

2006-06-01 Thread DavidA

Chris,

If I understand your problem, its that you want to do an "and" across
multiple rows, which is not a simple query (and I'm not sure how to do
in the model API). To be more clear, your Sub_Item table relates
through a many-to-many relationship to ObjectItem so the SQL to get all
Sub_Items with a "color" of "blue" would look something like this

select * from app_sub_item si
join app_sub_item_optionitems mtm on si.id = mtm.sub_item_id
join app_optionitem oi on mtm.optionitem_id = oi.id
where oi.name = 'color' and oi.value = 'blue'

This would return one set of Sub_Items. Likewise, the same query with
oi.name = 'size' and oi.value = 'small' would return a different set.
You want the intersection of those two sets (intersecting on
app_sub_item.id). But I think your query ends up forming a where like
this:

where oi.name = 'color' and oi.value = 'blue' and oi.name = 'size' and
oi.value = 'small'

which will always be empty. You can't simply change the middle AND to
an OR because the OR could be true for different Sub_Items. You really
need something like this:

select * from app_sub_item si
join app_sub_item_optionitems mtm1 on si.id = mtm1.sub_item_id
join app_optionitem oi1 on mtm1.optionitem_id = oi1.id
join app_sub_item_optionitems mtm2 on si.id = mtm2.sub_item_id
join app_optionitem oi2 on mtm2.optionitem_id = oi2.id
where oi1.name = 'color' and oi1.value = 'blue'
and oi2.name = 'size' and oi2.value = 'small'

Which joins Sub_Item back to OptionItems twice and constrains one join
by the color clause and one by the size clause resulting in the
intersecation (AND) of the two separate clauses.

Its complicated. Its ugly. In a nutshell, its why I hate SQL. And I'm
not sure the best way to map it back to Django. This should probably
work:

s1 = set([obj.id for obj in
item1.sub_item_set.filter(options__name__exact="Small")])
s2 = set([obj.id for obj in
item1.sub_item_set.filter(options__name__exact="Blue")])

smallAndBlueIDs = s1.intersection(s2)
smallAndBlueSubItems = Sub_Item.objects.in_bulk(list(smallAndBlueIDs))

You are just doing some of the work in SQL (the two filter clauses) and
then manually intersecting the IDs of the results and reloading the
objects by the resulting IDs.

But, yuck! And it hits the DB 3 times instead of only once.

-Dave


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



Re: Guidance would be most welcome

2006-06-13 Thread DavidA

I have a similar problem where I want to maintain an audit trail for
"manual overrides" to inputs to our risk loop. I haven't implemented it
in Django yet, but the way I've done this in the past is similar to
Waylan: using a history version of the table. There are a few
differences, however. My table's will probably look more like this:

ParameterOverride
  id
  name
  value
  user
  note

ParameterOverrideHist
  id
  name
  value
  user
  note
  time_from
  time_thru

The "hist" table simply adds the time_from/thru fields to track the
date range that this value was valid. Whenever a new row is added to
the main table, it is also added to the hist table (the id is *not*
auto_increment on the hist table). Then time_from is set to the current
time and time_thru is set to null. When a row is edited, a new row is
inserted into the hist table with time_from set to now and time_thru
set to null, but the old row that had time_thru null is updated so its
time_thru is the same as the new row's time_from. Deleted rows simply
update the row in the hist table with time_thru = null to time_thru =
the current time.

Thus you can query the hist table on any give date/time to get the
active row at that moment: "where _date_ >= time_from and (_date_ <
time_thru or time_thru is null)". While these queries are a little
ugly, this design allows you to get the row at a given time more
effectively that only storing the "updated" date in it (you have to
find the row with max(date) where date >= _eval_date_)

In my C#/Sql Server life, I handled this update logic using triggers on
the main table. In Django I'd probably override save() and delete()
like Waylan suggested.

I've been noodling on how to do this more easily since I'll have need
this approach quite a few times in my applications. Maybe a decorator?
It would be way cool to just say:

@track_audits()
class ParameterOverride(models.Model):
name = models.CharField(...)
value = models.FloatField(...)
user = models.ForeignKey(...)
note = models.TextField(...)

And it creates the hist table, overrides the save/delete methods and
maybe adds a few convenience methods like get_audit_trail(),
get_on_date(...)

Anyway, food for thought...
-Dave


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



Re: hello & question (sorting related cmodels)

2006-06-13 Thread DavidA

Bram,

You can add this to your model:

class Meta:
ordering = ('name',)

Here is the documentation:
http://www.djangoproject.com/documentation/models/ordering/


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



Re: MS SQL Django suport is stable?

2006-06-21 Thread DavidA

mamcxyz,

I've had pretty good luck with Fedora Core 4. Here are my (terse) notes
from setting up Django and my blog on FC4 a couple of weeks ago. Note
that FC4 already had MySQL 4.1.x and Python 2.4.1 and Apache 2.0.54
(with mod_python) so I just went with them. On Windows I use MySQL 5
but I haven't run into any probs between them yet.

  - yum install subversion
  - yum install python-docutils
  - svn co http://code.djangoproject.com/svn/django/trunk
  - python ez_setup.py (in Django co dir)
  - python setup.py install (in Django co dir)
  - mysqladmin create database web
  - mysql web < web.sql to restore it
  - make mysql autostart
chkconfig --level 3 mysqld on
  - make httpd autostart
chkconfig --level 3 httpd on
  - start them
service httpd start
service mysqld start

Note that I build and install Django. Most people here use symlinks
instead. But I like to follow the same process as I do on XP. I also
didn't have to compile any of the dependency packages.

There are of course more details than I've listed above but that really
covers the most of it. I think in all it took me about 30 minutes once
I had the Linux VM built.


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



Re: Comments: Failed lookup for key [id] in ''

2006-06-22 Thread DavidA


Patrick J. Anderson wrote:
> {% load comments.comments %}
>
> 
> {% for p in latest %}
>   {% get_free_comment_count for blog.post object.id as comment_count

> What could be the reason for failed lookup on key[id]?

Shouldn't that be 'p.id' rather than 'object.id' in the
get_free_comment_count 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
-~--~~~~--~~--~--~---



resolve_variable in custom filter

2006-06-23 Thread DavidA

I'm trying to write a filter that will highlight substrings in text
that matched a search pattern. I was hoping to do something like this:

   {{ obj.field|highlight:search }}

where 'search' is a template-context variable that is the string the
user was searching for and the highlight filter would look something
like:

@register.filter()
def highlight(value, arg):
s = template.resolve_variable(arg, c)  # WHERE DO I GET THE CONTEXT
FROM?
return re.sub('(%s)' % (s,),
  r'\1', value)

But I don't see a way to reference the template context ('c') in my
filter, nor a way to pass the value of a variable from the template.

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



Re: resolve_variable in custom filter

2006-06-23 Thread DavidA


RajeshD wrote:
> Don't know if a filter can do what you need. But you could turn this
> into a tag instead of a filter:
>
> {{ highlight search obj.field }}

Thanks. That worked nicely.

It would be nice, however, if filters had access to the template
context so you could do more sophisticated things. Even though I've got
this working as a tag, it sure seems like a good use case for a filter.


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



Re: Checking For Existing Rows

2006-06-27 Thread DavidA

You could just check the count of that many items (since its unique it
should always be 1 or 0):

if Photo.objects.filter(flickr_id=photo("id")).count() == 0:
# create the object ...

But its my understanding that Python exceptions are not as heavy weight
as they are in languages like C++/Java/C# so not only is either way
probably fine, the exception approach is actually fairly common in
Python. But I understand your discomfort - I had always taught myself
(pre Python) to only use exceptions for exceptional cases, i.e. things
you didn't expect to happen.


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



Re: after_acreate after_change

2006-07-03 Thread DavidA


Malcolm Tredinnick wrote:
> On Mon, 2006-07-03 at 08:54 -0700, Glenn Tenney wrote:
> > Perhaps instead of relying on the behavor of the object's ID not
> > existing until it's been created, that should become a method.
> > something like Model.created() returning true/flase or Model.is_created
> > or... something...???
>
> I can't see any real advantage in this. As Ivan shows, it's only a
> couple of lines of code anyway (and a more or less documented feature).
> The boolean test for "not created" at the moment is "if not self.pk:",
> which seems pretty reasonable.

But doesn't that assume you are using an auto-generated ID column? What
if my model looked like this:

class Post(models.Model):
slug = models.SlugField(prepopulate_from=('title',),
primary_key=True)
title = models.CharField(maxlength=80)
body = models.TextField()

In this case it would be up to the app or developer to populate the
slug primary key field before saving. But then just testing the pk
field wouldn't really tell me if it was saved, unless I misunderstand
what "self.pk" is actually doing behind the scenes.

I'll admit, my example is what I would consider bad form, but its valid
and I only point this out as I've seen it used.

-Dave


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



Re: after_acreate after_change

2006-07-04 Thread DavidA


Malcolm Tredinnick wrote:
> On Tue, 2006-07-04 at 02:11 +0000, DavidA wrote:
> I'm not sure a created() method is going to be the right API, since this
> event has very transitory relevance, but your example does suggest we
> may need something extra here at some point.

I agree that created() is probably the wrong way to think about it. In
the past, I've used some sort of "dirty" flag to indicate if the object
is out of sync with the database (you can call it what you like: dirty,
changed, modified). New objects have their dirty bit set, which would
be cleared when the object is saved (successfully). If you really do
this right (where the dirty flag is set on mutator methods only if the
state of the object changes), then you can optimize save calls, too.
But that might also just be a case of premature optimization...


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



Re: Null values in Foreign Keys?

2006-07-04 Thread DavidA

One related question on nullable foreign keys: does the Django ORM
always use inner/left joins for select_related() calls? If so, null FKs
will cause rows to be excluded from a query so you may have to handle
these with direct SQL.

Personally, I often create an "unknown" row in a table (and do a little
trickery to set its auto-increment ID to 0) and use this special value
for the same cases you might use a null ID for. It ensures all your
queries are simple and always return complete result sets, but still
allows you to easily query for (or exclude) these special cases.

-Dave


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



Re: after_acreate after_change

2006-07-05 Thread DavidA


Malcolm Tredinnick wrote:
> You've drifted a bit from the original topic here, though, haven't you?

Um, yes. Guilty as charged...


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



Syncdb generates non-unique foreign key constraints

2006-07-14 Thread DavidA

I've been having a problem rebuilding my database from scratch via
syncdb. I've tracked it down to duplicate constraint name. Here is the
output from manage.py sql for my app:

ALTER TABLE `data_rawinst` ADD CONSTRAINT
`inst_id_referencing_data_inst_id` FOREIGN KEY (`inst_id`) REFERENCES
`data_inst` (`id`);
ALTER TABLE `data_instmap` ADD CONSTRAINT
`inst_id_referencing_data_inst_id` FOREIGN KEY (`inst_id`) REFERENCES
`data_inst` (`id`);

Note that I have two tables, both with FK's to data_inst and its
generating the same constraint name
(`inst_id_referencing_data_inst_id`). It seems the source table should
be part of that name, such as
`data_rawinst_inst_id_referencing_data_inst_id`.

I'm on the trunk at Rev 3350.

This used to work, I'm pretty sure, but I haven't rebuilt the whole DB
from scratch for a long time so I don't know if its been lingering for
a while.

Thanks,
-Dave


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



Re: Syncdb generates non-unique foreign key constraints

2006-07-14 Thread DavidA

As soon as I hit "Post" I realized this should be in django-developers.
I'll do that now...


--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~--~~~~--~~--~--~---



Re: Database API question: I am not able to return a QuerySet

2006-07-31 Thread DavidA

Suriya,

You will probably have to do this in custom SQL or using extra(). Your
query requires a subselect to get the "current B's" (B's with max(date)
for each A).

Here's the SQL that I think you need (if I understand the problem
correctly):

select * from _A join _B on _B.a_id = _A.id
where _B.date = (select max(date) from _B where a_id =
_B.a_id)
and _B.status = 1

I think that maps to

 A.objects.extra(where=['_B.a_id = (select max(date) from _B
where a_id = _B.a_id)'], tables=['_B']).filter(b__status=1)

You might want to consider modeling this differently. I have a similar
problem where I'm essentially tracking different versions of an object.
But instead of just using one date, I use two for the range that the
version was valid: date_from and date_thru. For the current version, I
set date_thru to null. Then a query of the current versions is really
easy: filter(date_thru__isnull=True). You can also see all versions at
a given point in time with the slightly more complex (but efficient):
filter(date_from__lte=some_date).filter(Q(date_thru__gt=some_date)|Q(date_thru__isnull=True))

In your design all of these types of queries require a subselect. Of
course, its more work to keep my table up to date, but I have the need
to query it arbitrarily in many ways so paying a little expense at
insert time (once per quarter) for better query performance (many times
per day) is a good tradeoff, in my case.

-Dave

Suriya wrote:
> SmileyChris wrote:
> > How about just making the query like this:
> >
> > A.objects.filter(b__status=1)
>
> This returns the list of rows in table A that have status
> in table B set to 1 at some point in the past. What I want
> is the latest status from table B. For example, if table B
> has the two entries:
>B(id=1, a=1, status=1, date=yesterday) and
>B(id=2, a=1, status=0, date=today)
> a = 1 should not be returned in the list, because the current
> status is 0.
> 
> Suriya


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



Re: Weird slowdown with dev server behind nat

2006-08-02 Thread DavidA


Akatemik wrote:
> > In my experience, when you encounter non-obvious but fairly consistant slow
> > downs in net traffic, the first thing to check is DNS.
> >
> > In this case, I'd make sure that each of the DNS cache servers that the 
> > client
> > consults to resolve the address of your server can perform both a forward 
> > and
> > reverse lookup of your server's name an IP.
> >
> > Conversely, make sure the server isn't being slowed down by failed attempts 
> > at
> > reverse lookups on the client.
>
> You are correct, if I add the client machine to /etc/hosts on django
> server, everything is smooth. However I find quite odd that the server
> does a separate reverse dns checks for every GET it gets even in the
> same connection...

Turn this off in your Apache httpd.conf with:

HostnameLookups off

It was defaulted to on in older versions of Apache to make the logs
more readable but impacts performance (as you well know).

-Dave


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



Re: Weird slowdown with dev server behind nat

2006-08-02 Thread DavidA


Malcolm Tredinnick wrote:
> Um, Dave? The original poster was using the development server. Apache
> doesn't get a seat at the table here. :-)

Er ... in my best Emily Litella impression: "Never mind"


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



Re: How to get a subset of records from a subset?

2006-08-08 Thread DavidA


PythonistL wrote:
> To explain:
> Let's suppose we have a command
>
> HistoryList=historys.get_list(id__exact='2',order_by=['-PostedDate'])
>
> that command extracts a few records and from them I would like to use
> for further processing all without the first or last record.
> How can I do that in Django version 0.91?
> Thank you for help
> L.

I'm rusty on 0.91 but I think you could do it in two calls with:
count=historys.get_count(id__exact='2',order_by=['-PostedDate'])

HistoryList=historys.get_list(id__exact='2',order_by=['-PostedDate'],
limit=count-2, offset=1)

Or in the post-mr world:

HistoryList=history.objects.filter(id='2').order_by('-PostedDate')[1:-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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~--~~~~--~~--~--~---



How to support of alternate date formats for DateField

2006-08-09 Thread DavidA

I'm sure I'm just misunderstanding how manipulators and validators
work, but I can't see the right way to do this: I want to support more
formats for a DateField then just '-MM-DD' (which is checked in
DateField by isValidANSIDate).

It seems like I can add *more restrictive* validators but can't
*replace* the existing ones with more relaxed validators.

So instead I've manually checked and converted the value in my view
right before the call to manipulator.get_validation_errors (I validate
it, and if its a valid date, I convert it to a string in the format
'-MM-DD' and put it back in the new_data dict so it *will* pass the
isValidANSIDate check.)

This seems kludgy to me, and 9 times out of 10, when something looks
kludgy in my Django code, its because I'm missing something obvious.

Thanks in advance,
-Dave


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



Re: How to support of alternate date formats for DateField

2006-08-10 Thread DavidA

Steven Armstrong wrote:
> I've had similar problems and solved them like this:
>
> myproject/validators.py
> %<--
> from django.utils.translation import gettext_lazy as _
> from django.core.validators import *
> import re
>
> my_ansi_date_re = re.compile('put regexp here')
> def isValidANSIDate(field_data, all_data):
>  if not my_ansi_date_re.search(field_data):
>  raise ValidationError, _('Enter a valid date in PUT FORMAT
> DESCRIPTION HERE format.')
>
> [more custom or overridden validators]
> %<--
>
> And in my models I do:
> from myproject import validators
>
> instead of
>
> from django.core import validators
>
>
> Like this I can override any of djangos validators or add custom ones
> and they are all still available in one namespace.
>
> hope this helps
> cheers
> Steven

Hi Steven,

I tried your suggestion, but it still seems that Django is using the
isValidANSIDate funcion from django.core.validators rather than mine. I
put trace statements in django.core.validators.py as well as my
override and although I could see mine being imported after the core
ones, when the form's validation occurs, its using the core one. I
googled on "override module function in python" and got this hit:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/30bfdfd91d759275/6eaa3b20deb47d84%236eaa3b20deb47d84

I've used the suggested technique in the following way and now it
works:

 my custom validators.py 
from pf.utils.convert import toDateRelaxed

def isValidANSIDate(field_data, all_data):
try:
toDateRelaxed(field_data)
except ValueError:
raise ValidationError, "Invalid date"

import django.core.validators
django.core.validators.isValidANSIDate = isValidANSIDate


And then I import my validators in my models.py class. The downside to
this, as explained in the link, is that if someone uses

from django.core.validators import isValidANSIDate

they will get the original, not my custom version.

Thanks for your suggestion as it got me on the right track.
-Dave


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



Re: How to support of alternate date formats for DateField

2006-08-10 Thread DavidA


Steven Armstrong wrote:
> On 08/10/06 20:25, DavidA wrote:
> > Steven Armstrong wrote:
> >> I've had similar problems and solved them like this:
> >>
> >> myproject/validators.py
> >> %<--
> >> from django.utils.translation import gettext_lazy as _
> >> from django.core.validators import *
> >> import re
> >>
> >> my_ansi_date_re = re.compile('put regexp here')
> >> def isValidANSIDate(field_data, all_data):
> >>  if not my_ansi_date_re.search(field_data):
> >>  raise ValidationError, _('Enter a valid date in PUT FORMAT
> >> DESCRIPTION HERE format.')
> >>
> >> [more custom or overridden validators]
> >> %<--
> >>
> >> And in my models I do:
> >> from myproject import validators
> >>
> >> instead of
> >>
> >> from django.core import validators
> >>
> >>
> >> Like this I can override any of djangos validators or add custom ones
> >> and they are all still available in one namespace.
> >>
> >> hope this helps
> >> cheers
> >> Steven
> >
> > Hi Steven,
> >
> > I tried your suggestion, but it still seems that Django is using the
> > isValidANSIDate funcion from django.core.validators rather than mine. I
> > put trace statements in django.core.validators.py as well as my
> > override and although I could see mine being imported after the core
> > ones, when the form's validation occurs, its using the core one. I
> > googled on "override module function in python" and got this hit:
> >
> > http://groups.google.com/group/comp.lang.python/browse_thread/thread/30bfdfd91d759275/6eaa3b20deb47d84%236eaa3b20deb47d84
> >
> > I've used the suggested technique in the following way and now it
> > works:
> >
> >  my custom validators.py 
> > from pf.utils.convert import toDateRelaxed
> >
> > def isValidANSIDate(field_data, all_data):
> > try:
> > toDateRelaxed(field_data)
> > except ValueError:
> > raise ValidationError, "Invalid date"
> >
> > import django.core.validators
> > django.core.validators.isValidANSIDate = isValidANSIDate
> > 
> >
> > And then I import my validators in my models.py class. The downside to
> > this, as explained in the link, is that if someone uses
> >
> > from django.core.validators import isValidANSIDate
> >
> > they will get the original, not my custom version.
> >
> > Thanks for your suggestion as it got me on the right track.
> > -Dave
> >
>
> Hi Dave
>
> Good to hear you've found a solution.
>
> I have yet only used my approach with validators that I've set myself by
> passing them to the field constructors.
>
> Guess it fails with the date related fields because django imports and
> adds them automagically there.
>
> cheers
> Steven

Guess I spoke to soon. While my previous post successfully _validated_
dates of different formats, it didn't address _converting_ them to a
Python value. I ended up subclassing both models.DateField and
forms.DateField to get this to work. Seems like a lot of code to simply
allow different formats for entering dates, but at least it works.

-Dave


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



Re: How to log ALL queries

2006-08-11 Thread DavidA


Hancock, David (DHANCOCK) wrote:
> So, I¹d appreciate any pointers to documentation, code, etc. to let me log
> queries to a file.

David,

While not exactly what you want, I wrote a simple middleware class to
track page-generation stats when calling a view. In it, I count the
number of queries and total time spent in them. You could take my class
and simply change the part where I'm computing the time to print out
each SQL call.

Here's the post about it:
http://davidavraamides.net/blog/2006/07/03/page-stats-middleware/

And just change this section:

# compute the db time for the queries just run
queries = len(connection.queries) - n
if queries:
dbTime = reduce(add, [float(q['time'])
  for q in connection.queries[n:]])
else:
dbTime = 0.0

To something like:

# log the sql of each new query
queries = len(connection.queries) - n
if queries:
for q in connection.queries[n:]:
logging.info(q['sql'])

Hope that helps,
-Dave


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



Re: Reproduce admin search functionality

2006-08-22 Thread DavidA


Seth Buntin wrote:
> So how will I get the queries if more than one word is used to search?
> The only reason I am using the way I am is in case people search
> multiple words.  Can I run queries and add them together or something?

Seth,

I do a similar thing using the ORM's Q object:
from django.db.models import Q

...

def search(request):

terms = request['search'].lower()
query = Q()
for term in terms.split(' '):
q = Q(instName__icontains=term)| \
Q(instDesc__icontains=term)| \
Q(instClass__icontains=term)| \
Q(note__icontains=term)
query = query & q

trades = RawTrade.objects.filter(query)

return render_to_response('trades/search', {'trades': trades,
'search': terms})

This will generate analogous SQL as your case but you don't have to
deal with all the gory SQL details.

-Dave


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



Re: Is this a transaction use case?

2006-08-23 Thread DavidA


[EMAIL PROTECTED] wrote:
> Hi all,
>
> i have the following scenario for a real-estate search engine:
>
> "Ad" table where i define the properties of the ad such as created_on,
> expires_on, user_id and is related with a 1-1 FK to the "Property"
> table which defines stuff such as sq_feet, district_id etc...
>
> I'd like to keep them separated (though your design advice is more than
> welcome) but how do i make sure to populate the Ad table with the
> correct property_id which has just been added to the Property table?
> The "Get Latest Object" recipe is not safe to use here. Still, if i
> wrap everything in a transaction i need to get the property_id just
> created.
>
> With SqlServer i would return the @@Identity and use it to populate the
> property_id FK on the Ad table... i need something like that.
>
> Hope i expressed my thoughts clearly ;-)
>
> Thanks,
> Lorenzo

The identity value is set in the new instance once you call save so you
can simply do this:

p = Property(sq_feet=2300, ...)
p.save()  # now p.id is set

a = Ad(property=p, ...)
a.save()

The equivalent of the @@Identity trick is handled during 'save' via the
db backend's get_last_insert_id function which is database-dependent.
-Dave


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



Re: FreeComment doesn't work with slugs?

2006-08-23 Thread DavidA


[EMAIL PROTECTED] wrote:
> I've been refactoring some stuff to use slugs, and it looks like
> FreeComment needs an object.id
>
> Is this correct or have I missed something?
>
> Derek

The FreeComment model assumes the primary key of the object it refers
to is an integer, so you can't make the primary key of your model a
slug, but you can still use a slug on your model:

class Post(models.Model):
slug = models.SlugField(prepopulate_from=('title',), unique=True)
title = models.CharField(maxlength=80)
...

Since I have slug as 'unique=True' rather than 'primary_key=True'
Django will auto-generate an integer primary key field ('id').
-Dave


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



Re: FreeComment doesn't work with slugs?

2006-08-24 Thread DavidA


Derek Hoy wrote:
> Some of the slug examples use slug as PK.  Funnily enough, your blog
> example does :)
> http://davidavraamides.net/blog/2006/05/11/yet-another-django-blog/

Yes, and that's how I learned about the problem. If you would have
stumbled upon this later post, you would have seen that I ran into it
when I added comments:

http://davidavraamides.net/blog/2006/05/13/adding-comments/

>From that post:


The second problem was that while I could enter comments, the same ones
always showed up for all my posts. They didn't seem to have the right
association with the specific post. A quick perusal of the database
showed the problem. The comments_freecomment table uses two fields to
"link" to a blog post: 1) content_type_id which refers to the type of
model in django_content_type, and 2) object_id which refers to the
specific row/instance of the model, in this case a Post.

But as you may recall, my first version used slug, a string, as the
primary key for a Post so all my comments had their object_id set to 0
and thus weren't pointing to any post. This bug resulted in all
comments being shown, no matter which post was displayed. To fix this,
I changed the primary_key argument of the slug field to unique. Since
now I wasn't explicitly setting a primary key for a Post, Django
automatically added one using an integer - just what I needed for the
comments to work.


To your point about this being documented in the Django docs: agreed.
Right now there is only this description about the contrib comments app
on the Django documentation site:

  comments
  A simple yet flexible comments system. This is not yet documented.

-Dave


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



Re: viewing generated SQL without running the query

2006-08-29 Thread DavidA


Gary Wilson wrote:
> I see that there is a _get_sql_clause() method, but is there a function
> that will return the constructed query string?

You can just do the same construction that's done in
django/db/models/query.py:

>>> from danet.blog.models import Post, Tag
>>> qs = Tag.objects.filter(title__icontains='a', description__icontains='n')
>>> cols, sql, args = qs._get_sql_clause()
>>> "SELECT %s %s" % (', '.join(cols), sql % tuple(args))
'SELECT `blog_tag`.`slug`, `blog_tag`.`title`, `blog_tag`.`description`
 FROM `b
log_tag` WHERE (`blog_tag`.`description` LIKE %n% AND
`blog_tag`.`title` LIKE %a
%) ORDER BY `blog_tag`.`title` ASC'
>>>

There's some special handling for DISTINCT if you look at
django.db.models.query.iterator(), but the snippet above is close
enough. After a while you get used to just looking at the list from
_get_sql_clause() directly and can just add the "SELECT" and replace
the args in your head.
-Dave


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



Re: Finding entries with multiple tags

2006-08-29 Thread DavidA

Gary Wilson wrote:
> [EMAIL PROTECTED] wrote:
> > > def tags(request, url):
> > > # Don't need the last item in the list since it will
> > > # always be an empty string since Django will append
> > > # a slash character to the end of URLs by default.
> > > tags = url.split('/')[:-1]
> > > posts = Post.objects.filter(tags__name__in=tags)
> > > return render_to_response("blog/tags.html", {'posts': posts})
> >
> > If I'm not mistaken, __in will return results that aren't tagged by all
> > tags. So using the original example:
> >
> > Post1: articles, python, django
> > Post2: articles, python
> > Post3: articles, music
> >
> > and tags has [articles, python, django], all 3 posts will be returned
> > since IN just OR's the values together, correct? That's why I came up
> > with that mess of a loop.
>
> Yes, you are right.  I was not thinking straight.  Anyone know what the
> best method for performing this in SQL would be?  Select all posts for
> each tag and use intersect?

With ManyToMany relationships, you have to think of chasing the
relationship backwards. Instead of finding the posts with a given tag,
start with the tag and find the related posts:

>>> from danet.blog.models import Post, Tag
>>> t = Tag.objects.get(pk='programming')
>>> t.post_set.all()
[, ]
>>>

My models look like this:

class Tag:
   ...
class Post:
tags = models.ManyToManyField(Tag)
...

Thus Post.tags is the set of tags for a given post and the reverse
relationship is created automatically as Tag.post_set (you can override
this with the 'related_name' arg to something like 'posts' if you
like).

-Dave


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



Re: Finding entries with multiple tags

2006-08-29 Thread DavidA

[EMAIL PROTECTED] wrote:
> That works easily when you're just looking up one Tag. What I'm trying
> to figure out is the best way to search for multiple tags and return
> only the Posts common to all of those tags:

Joe,

My bad. I misunderstood your question. I think the only way to do this
(in SQL) is with a subselect or with multiple joins to the same table,
neither of which are possible in the direct DB API. But you can use the
extra() method to get around some of the constraints.

To solve your specific problem, I started with the custom SQL:

select slug from blog_post
where id in (select post_id from blog_post_tags
where tag_id in ('programming', 'finance'))

This can be implemented in Django as:

>>> from danet.blog.models import Post, Tag
>>> Post.objects.all().extra(where=["blog_post.id in (select post_id from 
>>> blog_post_tags where tag_id in ('programming', 'finance'))"])
[, , ]
>>>

So I've just copied the where-clause from the SQL (and explicitly
qualified the id column with 'blog_post.id').

Its debatable whether this is an improvement over direct SQL. You could
just as easily do

>>> from django.db import connection
>>> cursor = connection.cursor()
>>> cursor.execute("select post_id from blog_post_tags where tag_id in ('program
ming', 'finance')")
3L
>>> Post.objects.in_bulk([row[0] for row in cursor.fetchall()])
{16L: , 1L: , 6L:
}
>>>

In either case you've got about the same amount of custom SQL in your
Python code so its really a six-of-one situation.
-Dave


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



Re: Filter question

2006-09-05 Thread DavidA


primitive wrote:
> Is it possible to use a string (coming from an request object) as a
> keyword to filter? I keep getting errors, but I don't know how to
> convert these strings into types that filter will understand.

Sure, Python allows you to pass a dict as a set of keyword arguments,
so you could do something like this (not tested, obviously):

def search(request):
if request['keyword'] and request['search']:
lookup = {'%s__icontains' % request['keyword']:
request['search']}
objs = MyModel.objects.filter(**lookup)
...

-Dave


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



Re: error with inspectdb using oracle (v0.95)

2006-09-11 Thread DavidA

world_domination_kites wrote:
> ---
> But then, alas:
> ---
> Traceback (most recent call last):
>   File
> "c:\Python23\Lib\site-packages\Django-0.95-py2.3.egg\django\bin\django-admin.py",
> line 5, in ?
> management.execute_from_command_line()
>   File
> "c:\python23\lib\site-packages\Django-0.95-py2.3.egg\django\core\management.py",
> line 1224, in execute_from_command_line
> for line in action_mapping[action]():
>   File
> "c:\python23\lib\site-packages\Django-0.95-py2.3.egg\django\core\management.py",
> line 745, in inspectdb
> field_type = introspection_module.DATA_TYPES_REVERSE[row[1]]
> IndexError: string index out of range
> ---

I think django.db.backends.oracle.introspection is broken/incomplete.
Compare its get_table_description()

def get_table_description(cursor, table_name):
return table_name

With MySQL's (where I've used inspectdb successfully):

def get_table_description(cursor, table_name):
"Returns a description of the table, with the DB-API
cursor.description interface."
cursor.execute("SELECT * FROM %s LIMIT 1" % quote_name(table_name))
return cursor.description

This makes me think no one has ever tried 'inspectdb' on Oracle. Note
that get_relations and get_indexes both throw NotImpmementedError, too.
You could try implementing those three functions, using one of the
other backends as a starting point, but you'll need to be fairly
familiar with Oracle to get through it, me thinks.


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



Re: Re:

2006-09-11 Thread DavidA


Adam Kelly wrote:
> In the view:
> rows = zip( *[ ( thing.name, thing.color, thing.weight ) for thing in
> object_list ] )
>
> In the template:
> {% for row in rows %}
> 
> {% for item in row %}
> {{item}}
> {% endfor %}
> 
> {% endfor %}

To generalize this a bit more, you could do:

rows = zip(*[[getattr(thing, field.name) for field in
Thing._meta.fields] for thing in Thing.objects.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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~--~~~~--~~--~--~---



Re: Strategies for modifying models with existing data

2006-09-12 Thread DavidA

Hi Joe,

There is a "schema evolution" project underway to address this problem
in a more automated way, here is background on the project:

http://code.djangoproject.com/wiki/SchemaEvolution

but I don't know anything about the status of it.

But to respond to your question, I have two projects where I've run
into this and I've dealt with it in two different ways. In the first
case, I'm building a database to support various internal applications
for the hedge fund I work at. So far, all of the data is imported from
external sources (mostly read-only db) such as files, other databases,
web scraping, etc. Thus I can regenerate the entire database by
re-importing the data. So I wrote a 'makedb.py' script which:
1. backs up the database (table by table)
2. drops and re-creates the database
3. calls manage.py syncdb to rebuild the django tables
4. runs all my import tasks to re-load the data

When I make changes to models, I simply have to run this (and possibly
update the parsing/loading code). The few tables that are read-write
are just restored from the backup scripts I created in step 1. The only
tweaking required is when one of those tables changes and most of the
time MySQL will just get it right (if your new columns are not
required). Ocassionally, I need to tweak the backup SQL before
restoring it.

The second project is my personal site which consists of a blog and
to-do app. For these I just have to write the 'alter table' statements
directly to get them in sync. That's what most people have been doing.
Sometimes you have to do a few round trips to get it right. For
example, if you want to add a non-null field to a model and there isn't
an easy way to describe its default value in the model API, you can
create the column in the DB as null-able (with alter table) then write
a script (SQL or Python) to populate the column, then use an alter
table statement again to make it non-null.

-Dave


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



Re: Comments framework

2006-09-13 Thread DavidA


Guillermo Fernandez Castellanos wrote:
> I am thinking of using the comments framework for a project, although
> besides the FreeComment there's no real documentation about it that I
> have found besides the source.

This might help:
http://www.b-list.org/weblog/2006/07/16/django-tips-hacking-freecomment

-Dave


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



ChangeManipulator for model with multi-field key (unique_together)

2006-09-18 Thread DavidA

I have a model whose identity is defined by two fields: a foreign key
field and a boolean field. I'm trying to use a ChangeManipulator for it
but am stuck because ChangeManipulator assumes there is a single
primary key field.

Has anyone run into this? Can someone suggest a workaround?

Thanks
-Dave


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



Re: ChangeManipulator for model with multi-field key (unique_together)

2006-09-18 Thread DavidA


DavidA wrote:
> I have a model whose identity is defined by two fields: a foreign key
> field and a boolean field. I'm trying to use a ChangeManipulator for it
> but am stuck because ChangeManipulator assumes there is a single
> primary key field.
>
> Has anyone run into this? Can someone suggest a workaround?

Never mind - I see that this is a job for a custom manipulator.


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



Re: variable multiple filter question

2006-09-20 Thread DavidA


Luis P. Mendes wrote:
> But if he chooses to apply five filters, there will have to be five
> filter methods appended, or five key=values pairs as arguments.

You can do something like this:

from django.db.models import Q

def my_view(request):
query = Q()
for i in range(1, 13):
chk = "var%d" % i
if request.has_key(chk) and request[key]:
query = query & Q(**{chk:True})

objects = MyModel.objects.filter(query)

You build up a dynamic "and" query with a term for each checked box in
the UI. Then you use that compound query to filter your model objects.

Now that I think about it, since this is an "and" you could also do:

def my_view(request):
query = {}
for i in range(1, 13):
chk = "var%d" % i
if request.has_key(chk) and request[key]:
query[chk] = True

objects = MyModel.objects.filter(**query)


The first pattern is a little more generic (would also work with an
"or").
-Dave


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



Re: two models -> one form -> addmanipulator

2006-09-22 Thread DavidA


Ulrich Nitsche wrote:
> hi,
>
> i have two models (tables) concerning user data which belong together.
> Now I would like to use one single form to display and edit these
> values.
> Is there a way to use one changemanipulator to do this?
> Or if this is not possible is there a way to use different
> changemanipulators at the same
> time?
> How would this look like?

I'm doing something similar. I have a financial instrument object that
is split into two tables: Inst and InstDetail. But I want them to
appear as parts of the same object. My situation is slightly more
complicated in that each Inst has two InstDetails objects - a default
and an override. The user can only edit the override part. Here's how
my update view looks:

def update_inst(request, inst_id):
inst_manip = Inst.ChangeManipulator(inst_id)
inst = inst_manip.original_object
default = InstDetail.objects.get(inst=inst, is_override=False)
detail = InstDetail.objects.get(inst=inst, is_override=True)
detail_manip = InstDetail.ChangeManipulator(
detail.id,
follow={'is_override': False})
detail_manip.default_object = default

if request.POST:
new_data = request.POST.copy()

# fk's are not fixed up??
new_data['inst_id'] = inst.id
new_data['inst'] = inst.id

errors = {}
errors.update(inst_manip.get_validation_errors(new_data))
errors.update(detail_manip.get_validation_errors(new_data))
inst_manip.do_html2python(new_data)
detail_manip.do_html2python(new_data)

if not errors:
inst_manip.save(new_data)
detail_manip.save(new_data)
return HttpResponseRedirect(inst.get_absolute_url())

print errors

else:
errors = {}
new_data = {}
new_data.update(inst_manip.flatten_data())
new_data.update(detail_manip.flatten_data())

inst_form = forms.FormWrapper(inst_manip, new_data, errors)
detail_form = forms.FormWrapper(detail_manip, new_data, errors)

return render_to_response('core/inst_form.html',
  { 'inst_form': inst_form,
'detail_form': detail_form })

Note that I use the Inst id to find the corresponding InstDetail
objects and then create both manipulators. The rest is just standard
update logic but repeated twice. Then I return both forms to the
template. Its been working fine so far.

-Dave


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



Re: SlugField is not unique?

2006-09-27 Thread DavidA

Gábor Farkas wrote:
> hi,
>
> i've just checked and SlugField does not imply unique=True.
>
> i somehow always assumed that it does.
>
> so before i go and add the unique=True to all my SlugFields,
>
> is there any reason to have non-unique SlugFields?
>
> as far as i understand, SlugFields are mostly used in URLs which
> imho implies that they need to be unique...
>
>
> gabor

Gabor,

Remember that just adding unique=True won't fix the DB as this is a
database contstraint, not Python logic. You'll need to resync, or if
you have data you need to preserve, use the alter table statement, like
this (on MySQL):

alter table myapp_mymodel modify my_slug_field varchar(100) not null
unique;

-Dave


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



Re: date format other than YYYY-MM-DD

2006-09-29 Thread DavidA

viestards wrote:
> thanks, suppose I have to do it this way. I just hoped to have a
> sollution that works in admin pages too.

I also ran into this problem so I did it that hard way: I created a
custom model DateField and a custom form DateField. (I call them
RelaxedModelDateField and RelaxedFormDateField meaning they are relaxed
about what format you put the date in). Every time I look at this code
I think "this is way too complicated to simply allow different date
formats on input/output" which is probably one of the reasons the
forms/manipulators/validators are all getting revisited right now.

To use this, just use RelaxedModelDateField in place of
models.DateField in your model. This works in the admin.

class RelaxedModelDateField(models.DateField):
"""A DateField that supports various date formats
rather than just -mm-dd. The following formats
are allowed:
  m/-d/-6-23-2006
  m/-d/-yy  6/23/06
  m/-d  6/23
  -mm-dd2006-6-23
  mmdd  20060623

In the UI, the date will be displayed as mm/dd/"""
def __init__(self, verbose_name=None, name=None,
 auto_now=False, auto_now_add=False, **kwargs):
models.DateField.__init__(self, verbose_name, name,
  auto_now, auto_now_add, **kwargs)

def get_internal_type(self):
return "DateField"

def to_python(self, value):
if isinstance(value, datetime.datetime):
return value.date()
if isinstance(value, datetime.date):
return value
try:
return toDateRelaxed(value)
except ValueError:
raise validators.ValidationError, gettext('Enter a valid
date.')

def get_manipulator_field_objs(self):
return [RelaxedFormDateField]

def flatten_data(self, follow, obj = None):
val = self._get_val_from_obj(obj)
return {self.attname:
(val is not None and val.strftime("%m/%d/%Y") or '')}

class RelaxedFormDateField(forms.DateField):
"""A version of forms.DateField that automatically
supports various formats of dates."""
def __init__(self, field_name, is_required=False,
validator_list=None):
forms.DateField.__init__(self, field_name, is_required,
validator_list)

def isValidDate(self, field_data, all_data):
try:
toDateRelaxed(field_data)
except ValueError:
raise validators.CriticalValidationError, 'Enter a valid
date.'

def html2python(data):
"Converts the field into a datetime.date object"
try:
return toDateRelaxed(data)
except ValueError:
return None
html2python = staticmethod(html2python)


And here is the routine that actually does the "relaxed" parsing:

# handle many formats:
# m/-d/-6-23-2006
# m/-d/-yy  6/23/06
# m/-d  6/23
# -mm-dd2006-6-23
# mmdd  20060623
def toDateRelaxed(s):
exps = (r'^(?P\d{1,2})[/-](?P\d{1,2})[/-](?P\d{4})$',
r'^(?P\d{1,2})[/-](?P\d{1,2})[/-](?P\d{2})$',
r'^(?P\d{1,2})[/-](?P\d{1,2})$',
r'^(?P\d{4})-(?P\d{1,2})-(?P\d{1,2})$',
r'^(?P\d{4})(?P\d{2})(?P\d{2})$')
for exp in exps:
m = re.match(exp, s)
if m:
mm = int(m.group('m'))
dd = int(m.group('d'))
try:
yy = int(m.group('y'))
if yy < 100:
yy += 2000
except IndexError:
yy = datetime.date.today().year
return datetime.date(yy, mm, dd)
raise ValueError, s

Hope this helps...
-Dave


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



Re: Why I'm giving up on Django

2006-09-29 Thread DavidA


[EMAIL PROTECTED] wrote:
>
> Here's my anecdote on that.
>
> Even though it was literally staring me in the face, it took me AGES to
> discover that the error dump page is actually interactive and has
> little sections that expand and collapse.
> I kept running into error messages which told me about exceptions in
> the Django source code (this is the top part of the error page) and I
> kept thinking "well, where's the bloody use in that??? I want to know
> what MY error was! Grmbl.".
>
> It took me at least two weeks (yes, sometimes I really *am* that dense)
> until I scrolled down and explored and figured out that there was the
> information that I had been wanting all along.
> Somehow, the styles, fonts and layout choices of the error page (lots
> of text, lots of grey) made it totally non-intuitive for me that it was
> interactive.

You're not the only one. It took me quite a while to figure that out,
too. In fact, I only figured it out because I saw someone post a
screenshot to a blog one time and I was thinking "why does his
traceback show more source lines and the variable values?! Its not
fair!"

I was always afraid to admit that it took me so long to figure it out.
But now that you've come out of the closet...

I agree that the UI could be tweaked to make it more obvious, like
changing "Local vars" to "Click here to show local vars". I also don't
understand why the code and variables are hidden by default (which is
where I want to look 99% of the time) and the request and settings
information is expanded (where I end up finding the answer about 1% of
the time).

But pointing out these little things is the first part of the process
of making Django better. And it _does_ keep getting better, even over
the short period of time that I've been using it.

-Dave


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



Referencing the current URL in a view

2006-10-03 Thread DavidA

I have a number of views where function args (parsed from the URL conf)
and/or query string arguments are used to filter the results that are
displayed in a template. The template includes paging and sorting which
need to use a URL that points back to the view using the same
arguments, but I'm finding the way I'm doing this a little non-elegant.
Here's an example:

A sample url in the browser might look like this:

http://127.0.0.1:8000/data/pos/20060922/dle/?filter=inst__exposure_asset_class:9&page=2

Which maps to this URL conf:

# positions
(r'^pos/(?P\d{8})/(?P.*)/$',
'pfweb.core.views.list_positions'),

And uses this view:

def list_positions(request, date, fund):
positions = Position.objects.filter(
date=date,
account__custodian__portfolio__fund_name=fund)
if request.has_key('filter'):
# account__name:abc,spectrum:123
kwargs = dict([kv.split(':') for kv in
request['filter'].split(',')])
positions = positions.filter(**kwargs)

# HACK post message to django groups to see if there is a better
way...
# get a url suitable for paging by starting with the original
# and stripping off any 'page=' part
nav_base_url = request.META['PATH_INFO'] + '?'
query_string = re.sub(r'[?&]page=\d+', r'',
request.META['QUERY_STRING'])
if query_string:
nav_base_url += query_string + '&'

return object_list(
request,
positions,
paginate_by=30,
extra_context={'nav_base_url':nav_base_url})

Notice that I'm passing back the 'nav_base_url' to the template so I
can setup the previous/next links for paging. I also plan to use that
url for sorting links in column headers.

But its a little nasty. Starting at the HACK comment you can see that
I'm digging into the request meta info to get the url path and query
string, strip off any 'page=nnn' fragment and return a base url that I
can append the 'page=nnn' or 'sort=xxx' in my template, like this:

   {% if has_previous %}
   Prev
   {% endif %}
   {% if has_next %}
   Next
   {% endif %}

It seems this is part of (what I would think would be) a general
problem: building a link in a page back to the same view using the same
args, but optionally adding or replacing certain fields within that
url.

Does anyone see a cleaner, more elegant way to solve this without
manually parsing and building a query string? I'm worried that as this
gets more complex, there will be all sorts of bugs with issues like
getting the '?' and '&' in the right place.

Thanks in advance,
-Dave


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



Re: creating models / performance issue

2006-10-04 Thread DavidA


va:patrick.kranzlmueller wrote:
> I have a model with blog-postings, assigned to a specific user - the
> user is stored in the table "posting" via foreignkey.
>
> the user is part of a grade, part of a school and part of a state -
> all of which have overview-pages.
> so, to get all the postings for a state I have to do the following:
>
> 1. search for schools in that state
> 2. search for grades in that school
> 3. search for users within that grade
> 4. and finally, get all the postings for that user
>
> seems a little complicated.

Not sure if I understand your models exactly, but you don't need to do
four "searches" (queries), you just need to do one query with the
constraint that spans the four relations. Assuming your models look
something like this:

class State(models.Model):
code = models.CharField(maxlength=2)

class School(models.Model):
state = models.ForeignKey(State)

class Grade(models.Model):
school = models.ForeignKey(School)

class User(models.Model):
grade = models.ForeignKey(Grade)

class Posting(models.Model):
user = models.ForeignKey(User)

Then you can just do this to find all postings for users in grades in
schools in New York:

   Posting.objects.filter(user__grade__school__state__code='NY')

Which will translate into one query looking something like this:

  select * from posting
  join user on posting.user_id = user.id
  join grade on user.grade_id = grade.id
  join school on grade.school_id = school.id
  join state on school.state_id = state.id
  where state.code = 'NY'

(abbreviated - the actual Django version of the SQL will be quite a bit
more verbose due to fully qualified column names).

Of course, I may have completely misunderstood your models and this may
be completely off base!
-Dave


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



Re: Freecomment need love, it doesnt likes "♥"

2006-10-10 Thread DavidA


Geert Vanderkelen wrote:
> Did you forget to do
>   mysql> SET NAMES 'UTF8";
> when selecting in your client?
>

That's done automatically for you in
django.db.backends.mysql.DatabaseWrapper.cursor:

if self.connection.get_server_info() >= '4.1':
cursor.execute("SET NAMES 'utf8'")

So assuming he's using MySQL >= 4.1 then that shouldn't be the problem.

-Dave


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



Re: sorting QuerySets

2006-10-10 Thread DavidA

Tom Smith wrote:
> With about a million records I can't imagine doing it any other way...
>
> I want to find my top 100 words (by product_count) then sort them
> alphabetically to make a tag cloud...
>
> thanks...

If you are only dealing with 100 records after the query, then its not
a big deal to just sort them by some property in memory. Something
like:

# get the top 100 objects by the first criteria
object_list = Word.objects.all().order_by('-product_count')[:100]

# create a dict of the second criteria -> index of the current list
index = dict([(word.value, i) for i, word in enumerate(object_list)])

# get a new list of objects ordered by the second criteria
sorted_object_list = [object_list[index[key]] for key in
sorted(index.keys())]

I think I got all that syntax right...
-Dave


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



Re: Todo application -- where it is?

2006-10-19 Thread DavidA


Guillermo Fernandez Castellanos wrote:
> That's it, thanks!
>
> G
>
> On 10/19/06, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> >
> > Here is a link to the Django Powered Sites:
> >
> >
> > http://code.djangoproject.com/wiki/DjangoPoweredSites#Variousapplications
> >
> > Look for WorkStyle.  The project page is still up, but the sandbox was
> > broken last time I checked.
> >
> > --Nick Pavlica
> >
> >
> > >
> >

Or for a different slant on the same idea:


http://davidavraamides.net/blog/2006/07/27/getting-things-done-django-style-part-1/
http://davidavraamides.net/blog/2006/07/30/getting-things-done-django-style-part-2/
http://davidavraamides.net/blog/2006/09/05/getting-things-done-django-style-part-3/



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



Re: getting max and min

2006-10-19 Thread DavidA


Russell Keith-Magee wrote:
> On 10/19/06, zenx <[EMAIL PROTECTED]> wrote:
> >
> > I want to get the maximum and the minimum values of various numbers. Is
> > the following method the best way to do it?
>
> The most efficient way would be to use SQL; this way, the min and max
> would fall out as the result of a single query.
>
> Unfortunately, this requires some fairly complex use of aggregate
> clauses. The only support that Django provides for these clauses is as
> part of the extra clause.

I take it 'tag' is a ManyToMany field in 'artista'? Assuming your app
is named 'app', you should be able to do something like this:

from django.db import connection
...
cursor = connection.cursor()
cursor.execute("""
select min(c), max(c)
from (select tag_id, count(*) as c from app_artista_tags group by
tag_id) s""")
(min_c, max_c) = cursor.fetchall()[0]
cusor.close()

I find some things are easier (and faster) to do in SQL so its not
necessarilly a bad thing to drop down to custom SQL.
-Dave


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



  1   2   >