Re: Generic Relations and Django Admin?

2010-01-18 Thread greatlemer
On Jan 19, 5:25 am, Victor Hooi  wrote:
> heya,
>
> I'm trying to use an "Address" model as a generic relation against
> multiple other models (e.g. in a "User Profile", for each User, as
> well as for "Building", "Institution", and various other ones).
>
> So I've added the content_type, object_id and content_object fields to
> Address.
>
> class Address(models.Model):
>     """
>     Basic object for holding address information - for either people
> or institutions.
>     """
>     street_address = models.CharField(max_length=50)
>     suburb = models.CharField(max_length=20)
>     state = models.CharField(max_length=3,
> choices=AUSTRALIAN_STATES_CHOICES)
>     # PositiveIntegerField doesn't allow max_length? Have to use form
> validation for this.
>     postcode = models.CharField(max_length=4)
>     # This should probably be a list of choices.
>     country = models.CharField(max_length=20)
>     address_category = models.OneToOneField(AddressCategory)
>
>     # We make Address a generic relation model
>     content_type = models.ForeignKey(ContentType)
>     object_id = models.PositiveIntegerField()
>     content_object = generic.GenericForeignKey('content_type',
> 'object_id')
>
>     class Meta:
>         verbose_name_plural = 'Addresses'
>
>     def __unicode__(self):
>         return self.street_address + ', ' + self.suburb
>
>  And my other objects have GenericRelations to Address. E.g.:
>
> class Hospital(models.Model):
>     name = models.CharField(max_length=20)
>     address = generic.GenericRelation(Address)
>
>     def __unicode__(self):
>         return self.name
>
> However, when I try and use the Django admin to add an Address item,
> the form has fields for content_type and object_id. I had thought
> these fields wouldn't appear? Also, the model won't validate/save if I
> don't fill in these fields. I don't think I'm quite using this right -
> is there a better way of doing what I'm trying to achieve here?
>
> Also, I'm using the Address object as in Inline for the other models,
> so I have an Address Inline as well (Nb: I'm using django-reversion
> with this site, hence the "VersionAdmin")
>
> class AddressAdmin(VersionAdmin):
>     pass
> class AddressInline(generic.GenericTabularInline):
>     model = Address
> ...
> class HospitalAdmin(admin.ModelAdmin):
>     inlines = [
>         AddressInline,
>     ]
> ...
> admin.site.register(Address, AddressAdmin)
>
> Thanks,
> Victor

Hi,

I think here what you're looking for is to use:
address = models.ForeignKey(Address)
rather than a GenericRelation.  GenericRelations are for cases when
you don't know what the target model should be (hence the extra
content_type field).

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




Re: Generic Relations and Django Admin?

2010-01-18 Thread Raffaele Salmaso
Victor Hooi wrote:
> class AddressAdmin(VersionAdmin):
> pass
> class AddressInline(generic.GenericTabularInline):
> model = Address
> ...
  fields = (the fields you want to display)
or
  exclude = ('content_type', 'object_id',)

> class HospitalAdmin(admin.ModelAdmin):
> inlines = [
> AddressInline,
> ]
> ...
> admin.site.register(Address, AddressAdmin)

-- 
()_() | That said, I didn't actually _test_ my patch.  | +
(o.o) | That's what users are for! | +---+
'm m' |   (Linus Torvalds) |  O  |
(___) |  raffaele dot salmaso at gmail dot com |
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




problem with multiple database with django 1.1.1 please help

2010-01-18 Thread chiranjeevi.muttoju
Hi friends,

i am working with django1.1.1, now i want to connect django with
multiple database, could you people please help me how to achieve
this. if possible please send me the sample application using django
multiple db.. i tried it by reading some procedure in the net.. but i
cont able to achieve this.. so plz friends if any one of you know
please help me..

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




Re: ANN: LFC - a CMS

2010-01-18 Thread Kenneth Gonsalves
On Monday 18 Jan 2010 3:37:08 pm Kai Diefenbach wrote:
> I would like to announce the alpha release of LFC - a CMS based on Django:
> 

great - actually I had written a CMS a couple of years ago - but never had 
time to polish it and release it. Yours seems to have almost exactly done what 
I had been doing! Of course much better. Some points that I had thought about 
are missing - I will try to find the time to add/suggest these. Keep up the 
good work.
-- 
regards
Kenneth Gonsalves
Senior Project Officer
NRC-FOSS
http://nrcfosshelpline.in/web/
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Generic Relations and Django Admin?

2010-01-18 Thread Victor Hooi
heya,

I'm trying to use an "Address" model as a generic relation against
multiple other models (e.g. in a "User Profile", for each User, as
well as for "Building", "Institution", and various other ones).

So I've added the content_type, object_id and content_object fields to
Address.

class Address(models.Model):
"""
Basic object for holding address information - for either people
or institutions.
"""
street_address = models.CharField(max_length=50)
suburb = models.CharField(max_length=20)
state = models.CharField(max_length=3,
choices=AUSTRALIAN_STATES_CHOICES)
# PositiveIntegerField doesn't allow max_length? Have to use form
validation for this.
postcode = models.CharField(max_length=4)
# This should probably be a list of choices.
country = models.CharField(max_length=20)
address_category = models.OneToOneField(AddressCategory)

# We make Address a generic relation model
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type',
'object_id')

class Meta:
verbose_name_plural = 'Addresses'

def __unicode__(self):
return self.street_address + ', ' + self.suburb

 And my other objects have GenericRelations to Address. E.g.:

class Hospital(models.Model):
name = models.CharField(max_length=20)
address = generic.GenericRelation(Address)

def __unicode__(self):
return self.name

However, when I try and use the Django admin to add an Address item,
the form has fields for content_type and object_id. I had thought
these fields wouldn't appear? Also, the model won't validate/save if I
don't fill in these fields. I don't think I'm quite using this right -
is there a better way of doing what I'm trying to achieve here?

Also, I'm using the Address object as in Inline for the other models,
so I have an Address Inline as well (Nb: I'm using django-reversion
with this site, hence the "VersionAdmin")

class AddressAdmin(VersionAdmin):
pass
class AddressInline(generic.GenericTabularInline):
model = Address
...
class HospitalAdmin(admin.ModelAdmin):
inlines = [
AddressInline,
]
...
admin.site.register(Address, AddressAdmin)

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




Re: Efficient access through two manytomany layers

2010-01-18 Thread Alastair Campbell
On Mon, Jan 18, 2010 at 5:25 PM, Alex Robbins wrote:
> Hmm, you might also look at just doing something like
> Event.objects.values_list
> ('classes_involved__parent_disciplines__name', flat=True).distinct().
> That works on some relations, but I haven't tested it in your case.

I tried that and a few variations, e.g:
self.get('classes_involved__parent_discipline').values_list('name',
flat=True).distinct()
or
self.classes_involved.parent_discipline.values_list('name',
flat=True).distinct()

But I always get to either an attribute error (e.g. Event has no get)
or an instance error, i.e. I'm working with an instance rather than a
queryset. This seems to be a dead end. Reading around on instance
errors, it seems to be common for methods on models, and the answer
seems to be a manager class, but I'm struggling to work out how to
access related fields from a model instance. Especially ones that are
two deep.


> Second problem: Save doesn't work right.
> You could try doing a super(Event, self).save(*args, **kwargs) before you
> compute the disciplines list, and then again after you have computed
> it, to save the value.

Good idea, but unfortunately doesn't work. I suspect it's to do with
the model method working from the data rather than form values, but I
don't know enough about the admin area to work out how to change that.

Thanks for the help, but I think in this case I think I'll just have
to get admin users to select both categorisations rather than
automating it.

Kind regards,

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




Re: Entire site requires login

2010-01-18 Thread Shawn Milochik

I did it with middleware. Here's my code.

http://pastebin.com/f52e6ef04

Make sure you provide exceptions for the login page, password reset,  
static content, etc.


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




save method manytomany

2010-01-18 Thread Wim Feijen
Hi,

Will you help me please?

I've got a model called Card which has a ManyToMany relationship to
Tag. When I save a Card, I'd like to create a Product as well, which I
want to have the same ManyToMany relationship to tag.

How do I access the instance's tags? self.tags.all() gives an empty
list, while if I check after saving, the card actually has tags. My
code is below. For the record, I am using Django 1.0.5.

Major thanks!

Wim

class Card(models.Model):
product = models.ForeignKey(Product, editable=False,
null=True)
name   = models.CharField('name', max_length=50, unique=True,
help_text='A short and unique name or title of the object.')
identifier = models.SlugField('identifier', unique=True,
help_text='A unique identifier constructed from the name of the
object. Only change this if you know what it does.', db_index=True)
tags   = models.ManyToManyField(Tag, verbose_name='tags',
db_index=True)
price  = models.DecimalField('price', max_digits=15,
decimal_places=2, db_index=True)

def add_product(self):
product = Product(
name = self.name,
identifier = self.identifier,
price = self.price
)
product.save()
return product

def save(self, *args, **kwargs):
# Step 1: Create product
if not self.id:
self.product = self.add_product()
# Step 2: Create Card
super(Card, self).save(*args, **kwargs)
# Step 3: Copy cards many to many to product
# How do I do this?
print self.tags.all() # gives an empty list??


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




Entire site requires login

2010-01-18 Thread Wiiboy
Hi guys,
How would I make it so that every page requires a login?  Should I use
middleware or something like?
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




authentication and an http POST from a java applet

2010-01-18 Thread stephendwolff
I'm having problems authenticating an http POST from a java applet
(which is loaded from a fully authenticated django view).

Does anyone have any idea how I could share the authentication of the
browser user with the applet which is loaded? Am i missing something
blindingly obvious here?

I am considering passing some sort of request.session key to the
applet, via a parameter, but I am unsure how i can search currently
open sessions (in django_session) for the key?

Any help / suggestions would be very very welcome. How would
authentication be share with a Flash Movie loaded via HTML? Does this
just work? (i'll have to try!)
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Re: Splitting tests.py

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

Okay, I found the problem. In my tests I'm importing models, with something 
like:

from models import ...

That works when tests.py is located at the root of the app, that is: at the same
level as the models module.

But when splitting tests.py into individual files into tests/, models can't be
imported anymore. For it to work, I must use :

from my_app.models import ...

And now it works. The real problem here is that Django current behaviour is
silent failure, no error.

A little debugging led me in django.test.simple.get_tests() (at r12555 line 65):

try:
app_path = app_module.__name__.split('.')[:-1]
test_module = __import__('.'.join(app_path + [TEST_MODULE]), {}, {},
TEST_MODULE)
except ImportError, e:
# Couldn't import tests.py. Was it due to a missing file, or
# due to an import error in a tests.py that actually exists?
import os.path
from imp import find_module
try:
mod = find_module(TEST_MODULE, 
[os.path.dirname(app_module.__file__)])
except ImportError:
# 'tests' module doesn't exist. Move on.
test_module = None


Here the __import__ fails, not because the tests module is missing, but because
the tests module fails to import another module.

And then, the find_module() fallback fails too: my debugging shows that
os.path.dirname(app_module.__file__) points to /path/to/myapp/models and *not*
to /path/to/myapp as it should be.

This could be caused by the fact that my models are also split into models/,
thus dirname() returns a bogus value. But app_path above is correct, since it
doesn't rely on the fact the models module is a file...

Hum.. My head hurts ;)

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




Re: how to do a form with elements drawn from database (not hard-wired in forms.py)?

2010-01-18 Thread Shawn Milochik
In your form's __init__ function, you can dynamically add items to its 
self.fields. You can dynamically supply the label value as well, so what is 
shown on-screen will be properly labeled.

So, you'd pull from your database, then create (in code) a field (such as a 
forms.CharField or forms.BooleanField), assign it a label, then update your 
self.fields dictionary with that field.

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




how to do a form with elements drawn from database (not hard-wired in forms.py)?

2010-01-18 Thread dk
I have an application in which I'd like to present a form whose
elements are stored in a database.  To be specific, the database
contains a series of questions that I'd like to ask the user, via
radio buttons.

I can't do e.g.

 class thingee(forms.Form):
 q1 = forms.BooleanField()
 q2 = forms.BooleanField()

and so forth, because the code doesn't "know" how many questions will
be asked (nor, of course, the labels for the questions, not shown
above).

Is there a way to do this?  I've tried putting e.g. the following in
my 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-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Re: Using the form field values in templates

2010-01-18 Thread Shawn Milochik
This is something I've run into as well. If it's a forms.ModelForm, and you 
instantiated it by passing an instance, you can access it like this:

{{ person_form.instance.last_name }}

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




Admin pages, filtering instance list by instance field value and a newbie (me)

2010-01-18 Thread Massimiliano della Rovere
Greetings,
I'm here to seek your help:
I'm new to Django (I have experience with Prado and Zope3 though).

Here is my problem:
I created a model having - among the other ones - a status field (approved,
draft, proposed, etc) and a reference to the user that created the instance.
I'd like to use Admin pages (derived from django.contrib.admin and
django.contrib.auth.models.User) to interact with instances of this models.
I'm trying to show - in the index (a.k.a. list) page for the instances of
this models - only the instances created by the logged user, all of them if
the logged user is the administrator and only the approved ones for
anonymous users.

I could easily resolve the problem with a simple template & view pair, but I
was wondering if somehow I can specify in the class derived
from admin.ModelAdmin and associated to my model somehow that I want to use
a filter (Manager?) that reads a value from request.User.
-- 

You received this message because you are subscribed to the Google Groups "Django users" group.

To post to this group, send email to django-us...@googlegroups.com.

To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/django-users?hl=en.



Re: Splitting tests.py

2010-01-18 Thread Olivier Guilyardi
On 01/18/2010 10:04 PM, Ramiro Morales wrote:
> On Mon, Jan 18, 2010 at 4:40 PM, Olivier Guilyardi  wrote:
>> Hi,
>>
>> I'm trying to split tests.py into individual files into a tests/ subfolder, 
>> but
>> that doesn't work.
>>
>> I correctly import everything from within tests/__init__.py, as previously 
>> said
>> on this mailing list:
>> http://groups.google.com/group/django-users/browse_frm/thread/10cfd65e398360d2/dae3a7226dccdc5f
>>
>> But that doesn't work. I tested on Django 1.0.2 and SVN r12255, same thing.
>>
>> Any clue?
> 
> What do you mean with "doesn't work" ?. Do you get a traceback? No
> error but your
> tests aren't being run?, ...

No error, the tests are not run. When splitting, it says:

Ran 0 tests in 0.000s

Instead of the following with tests.py:

Ran 14 tests in 1.875s

> Try with SVN r12254 because the test infrastructure was refactored in r12255
> and it still has some small rough edges.

I reverted back to r12254, same problem.

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




Re: Splitting tests.py

2010-01-18 Thread Olivier Guilyardi
On 01/18/2010 09:58 PM, Shawn Milochik wrote:
> On Jan 18, 2010, at 3:50 PM, Olivier Guilyardi wrote:
> 
>> On 01/18/2010 08:59 PM, Shawn Milochik wrote:
>>> Here's a fantastic resource. It's what I used to switch to this 
>>> methodology. It talks you through exactly how to do this.
>>>
>>> http://ericholscher.com/blog/2008/nov/4/introduction-pythondjango-testing-basic-unit-tests/
>> Oh yes, I found this one.
>>
>> The following doesn't work in my case (quoted from the page you cite):
>>
>> "Unit tests are a lot easier to import than doctests. You simply do a from
>>  import . I named my unit test file unittst.py, and 
>> python
>> will import that from the current directory. You are importing the test 
>> classes
>> that you defined in your file. So I could have as easily put from unittest
>> import TestBasic and it would work. Using the import * syntax allows us to 
>> add
>> more tests to the file later and not have to edit it. "
>>
> 
> Then what does your tests/__init__.py look like?
> 
> Mine looks like this:
> 
> from address_tests import *
> from random_tests import *
> from other_tests import *
> 
> #where the tests folder contains address_tests.py, random_tests.py, and 
> other_tests.py.

$ cat tests/__init__.py
from model_tests import *

$ find tests
tests
tests/model_tests.py
tests/__init__.py

Django doesn't see my test cases unless I move tests/model_tests.py to tests.py.

One thing though: the tests directory (or tests.py if I revert it) is not at the
root of a project, it's located in an application that I'm developing.

--
  Olivier

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




Re: Splitting tests.py

2010-01-18 Thread Ramiro Morales
On Mon, Jan 18, 2010 at 4:40 PM, Olivier Guilyardi  wrote:
> Hi,
>
> I'm trying to split tests.py into individual files into a tests/ subfolder, 
> but
> that doesn't work.
>
> I correctly import everything from within tests/__init__.py, as previously 
> said
> on this mailing list:
> http://groups.google.com/group/django-users/browse_frm/thread/10cfd65e398360d2/dae3a7226dccdc5f
>
> But that doesn't work. I tested on Django 1.0.2 and SVN r12255, same thing.
>
> Any clue?

What do you mean with "doesn't work" ?. Do you get a traceback? No
error but your
tests aren't being run?, ...

Try with SVN r12254 because the test infrastructure was refactored in r12255
and it still has some small rough edges.

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




Re: Splitting tests.py

2010-01-18 Thread Shawn Milochik

On Jan 18, 2010, at 3:50 PM, Olivier Guilyardi wrote:

> On 01/18/2010 08:59 PM, Shawn Milochik wrote:
>> Here's a fantastic resource. It's what I used to switch to this methodology. 
>> It talks you through exactly how to do this.
>> 
>> http://ericholscher.com/blog/2008/nov/4/introduction-pythondjango-testing-basic-unit-tests/
> 
> Oh yes, I found this one.
> 
> The following doesn't work in my case (quoted from the page you cite):
> 
> "Unit tests are a lot easier to import than doctests. You simply do a from
>  import . I named my unit test file unittst.py, and 
> python
> will import that from the current directory. You are importing the test 
> classes
> that you defined in your file. So I could have as easily put from unittest
> import TestBasic and it would work. Using the import * syntax allows us to add
> more tests to the file later and not have to edit it. "
> 
> --
>  Olivier
> 

Then what does your tests/__init__.py look like?

Mine looks like this:

from address_tests import *
from random_tests import *
from other_tests import *

#where the tests folder contains address_tests.py, random_tests.py, and 
other_tests.py.

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




Re: Splitting tests.py

2010-01-18 Thread Olivier Guilyardi
On 01/18/2010 08:59 PM, Shawn Milochik wrote:
> Here's a fantastic resource. It's what I used to switch to this methodology. 
> It talks you through exactly how to do this.
> 
> http://ericholscher.com/blog/2008/nov/4/introduction-pythondjango-testing-basic-unit-tests/

Oh yes, I found this one.

The following doesn't work in my case (quoted from the page you cite):

"Unit tests are a lot easier to import than doctests. You simply do a from
 import . I named my unit test file unittst.py, and python
will import that from the current directory. You are importing the test classes
that you defined in your file. So I could have as easily put from unittest
import TestBasic and it would work. Using the import * syntax allows us to add
more tests to the file later and not have to edit it. "

--
  Olivier


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




Re: Splitting tests.py

2010-01-18 Thread Olivier Guilyardi
On 01/18/2010 09:19 PM, Reinout van Rees wrote:
> On 01/18/2010 08:40 PM, Olivier Guilyardi wrote:
>> Hi,
>>
>> I'm trying to split tests.py into individual files into a tests/
>> subfolder, but
>> that doesn't work.
>>
>> I correctly import everything from within tests/__init__.py, as
>> previously said
>> on this mailing list:
>> http://groups.google.com/group/django-users/browse_frm/thread/10cfd65e398360d2/dae3a7226dccdc5f
>>
>>
>> But that doesn't work. I tested on Django 1.0.2 and SVN r12255, same
>> thing.
> 
> Wild guess: place the test code in normal python test files inside the
> tests/ folder instead of in the __init__.py?  (I tend to keep that one
> virtually empty anyway).

Yes, I like it almost empty too :)

> Again: pretty wild guess ;-)

My __init__.py just contains an import statement, that is:

from individual_test import *

where individual_test.py resides in tests/

It doesn't work so far.

I'm not sure why, but splitting individual files tend to be a complex matter in
my Django experience. For example, when moving models from models.py to models/,
I needed to add an app_label to models' Meta class. That's a different problem,
but there seem to be some obscurity in the way things get loaded.

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




Re: no attribute 'save_m2m'

2010-01-18 Thread Daniel Roseman
On Jan 18, 7:17 pm, GoSantoni  wrote:
> I didn't alter the model but the view
>
> def new(request, form_class=BlogForm, template_name="blog/new.html"):
>     if request.method == "POST":
>         if request.POST["action"] == "create":
>             blog_form = form_class(request.user, request.POST)
>             if blog_form.is_valid():
>                 blog = blog_form.save(commit=False)
>                 blog.author = request.user
>                 if getattr(settings, 'BEHIND_PROXY', False):
>                     blog.creator_ip = request.META
> ["HTTP_X_FORWARDED_FOR"]
>                 else:
>                     blog.creator_ip = request.META['REMOTE_ADDR']
>                 blog.save(commit=False)

*** HERE IS THE PROBLEM (as you should know from the traceback)***. At
this point, `blog` is already a Post instance, not a form. You can't
do commit=False, or save_m2m, as these are methods of the **form**, as
Adam Knight pointed out above.

The save_m2m should be done on the **blog_form** object, on which you
already do .save(commit=False) seven lines up.

>                 request.user.message_set.create(message=_
> ("Successfully saved post '%s'") % blog.item)
>                 if notification:
>                     if blog.status == 2: # published
>                         if friends: # @@@ might be worth having a
> shortcut for sending to all friends
>                             notification.send((x['friend'] for x in
> Friendship.objects.friends_for_user(blog.author)),
> "blog_friend_post",
> {"post": blog})
>                 return HttpResponseRedirect(reverse
> ("blog_list_yours"))
>         else:
>             blog_form = form_class()
>     else:
>         blog_form = form_class(request.user)
>     return render_to_response(template_name, {
>         "blog_form": blog_form,
>     }, context_instance=RequestContext(request))



> There is no save in the form:

There doesn't need to be, it's inherited from the ModelForm
superclass.

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




Re: Splitting tests.py

2010-01-18 Thread Reinout van Rees

On 01/18/2010 08:40 PM, Olivier Guilyardi wrote:

Hi,

I'm trying to split tests.py into individual files into a tests/ subfolder, but
that doesn't work.

I correctly import everything from within tests/__init__.py, as previously said
on this mailing list:
http://groups.google.com/group/django-users/browse_frm/thread/10cfd65e398360d2/dae3a7226dccdc5f

But that doesn't work. I tested on Django 1.0.2 and SVN r12255, same thing.


Wild guess: place the test code in normal python test files inside the 
tests/ folder instead of in the __init__.py?  (I tend to keep that one 
virtually empty anyway).


Again: pretty wild guess ;-)

Reinout

--
Reinout van Rees - rein...@vanrees.org - http://reinout.vanrees.org
Programmer/advisor at http://www.nelen-schuurmans.nl
"Military engineers build missiles. Civil engineers build targets"

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




Re: Splitting tests.py

2010-01-18 Thread Shawn Milochik
Here's a fantastic resource. It's what I used to switch to this methodology. It 
talks you through exactly how to do this.

http://ericholscher.com/blog/2008/nov/4/introduction-pythondjango-testing-basic-unit-tests/

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




Splitting tests.py

2010-01-18 Thread Olivier Guilyardi
Hi,

I'm trying to split tests.py into individual files into a tests/ subfolder, but
that doesn't work.

I correctly import everything from within tests/__init__.py, as previously said
on this mailing list:
http://groups.google.com/group/django-users/browse_frm/thread/10cfd65e398360d2/dae3a7226dccdc5f

But that doesn't work. I tested on Django 1.0.2 and SVN r12255, same thing.

Any clue?

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




Re: My Own Auth Backend

2010-01-18 Thread Olivier Détour
Thanks for this link, I saw it Saturday.
But the problem is the same, I have to login to use template like that:

{% if user.is_authenticated %}
  lol
{% else %}
  not lol
{% endif %}

and my view.py is somethink like that:

  username = request.POST['user']
  password = request.POST['password']
  user = authenticate(username=username, password=password)
  if user is not None:
login(request, user)

Do I have to overload login method to use it like that ?


On Mon, Jan 18, 2010 at 9:32 AM, nostradamnit  wrote:
> Olivier,
>
> Look at this - 
> http://stackoverflow.com/questions/1057149/django-users-and-authentication-from-external-source
>
> I imagine your problem comes from the fact that django.contrib.auth
> User is tied to the DB
>
> Sam
>
> On Jan 18, 12:09 am, Olivier Détour  wrote:
>> up
>>
>> 2010/1/16 Détour Olivier :
>>
>>
>>
>> > Hi,
>> > I would create my own auth backend. I tried to understand and trace
>> > source code.
>> > I want to create an internal DB with SHA1 and username.
>> > But I cannot login, Django says me I do not set DB ENGINE. I would not
>> > use something like MySQL or any DB Engine.
>>
>> > Here is my source code:
>> > mybackend.py:
>>
>> > from django.contrib.auth.models import User
>> > from django.contrib.auth.backends    import RemoteUserBackend
>>
>> > class MyUser (User):
>> >  def save (self):
>> >    """saving to DB disabled"""
>> >    pass
>>
>> >  objects = None # we cannot really use this w/o local DB
>> >  username = ""  # and all the other properties likewise.
>> >                 # They're defined as model.CharField or similar,
>> >                 # and we can't allow that
>>
>> >  def get_group_permissions (self):
>> >    """If you don't make your own permissions module,
>> >       the default also will use the DB. Throw it away"""
>> >    return [] # likewise with the other permission defs
>>
>> >  def get_and_delete_messages (self):
>> >    """Messages are stored in the DB. Darn!"""
>> >    return []
>>
>> > class WWWBackend (RemoteUserBackend):
>> >  # Create a User object if not already in the database?
>> >  create_unknown_user = False
>>
>> >  def get_user (self, user_id):
>> >    user = somehow_create_an_instance_of(MyUser, user_id)
>> >    return user
>>
>> >  def authenticate (self, username=None, password=None):
>> >    if username == "lol" and password == "lol":
>> >      user = MyUser(username=username, password=password)
>> >      return user
>> >    return None
>>
>> > my view.py:
>>
>> > from django import forms
>> > from django.core.context_processors import csrf
>> > from django.template import RequestContext, loader
>> > from django.http import HttpResponse, HttpResponseRedirect
>> > from django.contrib.auth import authenticate, login
>>
>> > #! Form Upload Object
>> > class LoginForm (forms.Form):
>> >  user     = forms.CharField(widget = forms.TextInput)
>> >  password = forms.CharField(widget = forms.PasswordInput)
>>
>> > def index(request):
>> >  if request.method == 'POST':
>> >    form = LoginForm(request.POST)
>> >    if form.is_valid():
>> >      # FIXME: Check if file is good.
>> >      #handle_uploaded_torrent(request.FILES['file'])
>> >      username = request.POST['user']
>> >      password = request.POST['password']
>> >      user = authenticate(username=username, password=password)
>> >      if user is not None:
>> >        login(request, user)
>>
>> >      return HttpResponseRedirect('/')
>> >  else:
>> >    form = LoginForm()
>>
>> >  t = loader.get_template('template/index.html')
>> >  c = RequestContext(request, {
>> >      'login_form': form,
>> >  })
>> >  return HttpResponse(t.render(c))
>>
>> > Thanks for reponses,
>> > Regards,
>>
>> --
>> Olivier Détour
>> Sent from Reserved, ***
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
>
>
>
>



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




Re: permalinks from cron job

2010-01-18 Thread eric.frederich

I do not understand how this would work.
The only place where /apps/ is mentioned is apache's config file.

WSGIScriptAlias /apps /export/home/web/docs/django/my_site/apache/
django.wsgi

There is nothing in my Django settings about /apps/.
Is there a setting that I can put in my Django settings? ... If so
what is it?

Putting URLs together works fine when browsing my site because it is
going through apache.
The problem is when I'm not running through apache (like via cron,
or ./manage_py shell).

So, I do not understand how setting PYTHONPATH via crontab would let
cron know that it is at /apps when currently Apache is the only thing
that know.

~Eric


On Jan 17, 11:54 pm, Ted Nyman  wrote:
> More generally, in a crontab, you'll need to set both the PYTHONPATH  
> and give the location of the relevant Django settings.
>
> -Ted
>
> On Jan 17, 2010, at 8:22 PM, "eric.frederich"  
>
>  wrote:
>
> >> Is there some setting somewhere to set the prefix?
> >> Can it be set via an environment variable?
> >> How to I get the reverse function in urlresolvers to add /apps to my
> >> url like it does when run through wsgi?
>
> >> Thanks,
> >> ~Eric
> > --
> > You received this message because you are subscribed to the Google  
> > Groups "Django users" group.
> > To post to this group, send email to django-us...@googlegroups.com.
> > To unsubscribe from this group, send email to 
> > django-users+unsubscr...@googlegroups.com
> > .
> > For more options, visit this group 
> > athttp://groups.google.com/group/django-users?hl=en
> > .
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Re: no attribute 'save_m2m'

2010-01-18 Thread Bill Freeman
Have you, perhaps, overridden the save() method of your model form, and
neglected to capture **kwargs and pass it on to the superclass method?

On Mon, Jan 18, 2010 at 1:23 PM, GoSantoni  wrote:
> Hi Nek4life,
>
> Unfortunately that didn't work.
>
> TypeError at /blog/new/
> save() got an unexpected keyword argument 'commit'
> Request Method: POST
> Request URL:    http://localhost:8000/blog/new/
> Exception Type: TypeError
> Exception Value:
> save() got an unexpected keyword argument 'commit'
>
> On Jan 18, 4:21 pm, nek4life  wrote:
>> On Jan 18, 10:01 am, GoSantoni  wrote:
>>
>>
>>
>>
>>
>> > Hi
>>
>> > Trying to use save_m2m as described 
>> > herehttp://docs.djangoproject.com/en/1.0/topics/forms/modelforms/#the-sav...
>> > Though in run into an attrribute error 'Post' object has no attribute
>> > 'save_m2m'
>>
>> > *** Model ***
>> > class Post(models.Model):
>> >     id                     = models.AutoField(primary_key=True)
>> >     imagepost       = models.ManyToManyField(Image, verbose_name=_
>> > ('media'))
>>
>> >     def save(self, force_insert=False, force_update=False):
>> >         self.updated_at = datetime.now()
>> >         super(Post, self).save(force_insert, force_update)
>>
>> > *** View ***
>> > def new(request, form_class=BlogForm, template_name="blog/new.html"):
>> >     if request.method == "POST":
>> >         if request.POST["action"] == "create":
>> >             blog_form = form_class(request.user, request.POST)
>> >             if blog_form.is_valid():
>> >                 blog = blog_form.save(commit=False)
>> >                 blog.author = request.user
>> >                 if getattr(settings, 'BEHIND_PROXY', False):
>> >                     blog.creator_ip = request.META
>> > ["HTTP_X_FORWARDED_FOR"]
>> >                 else:
>> >                     blog.creator_ip = request.META['REMOTE_ADDR']
>> >                 blog.save()
>> >                 blog.save_m2m()
>> >                 request.user.message_set.create(message=_
>> > ("Successfully saved post '%s'") % blog.item)
>> >                 if notification:
>> >                     if blog.status == 2: # published
>> >                         if friends: # @@@ might be worth having a
>> > shortcut for sending to all friends
>> >                             notification.send((x['friend'] for x in
>> > Friendship.objects.friends_for_user(blog.author)), "blog_friend_post",
>> > {"post": blog})
>>
>> >                 return HttpResponseRedirect(reverse
>> > ("blog_list_yours"))
>> >         else:
>> >             blog_form = form_class()
>> >     else:
>> >         blog_form = form_class(request.user)
>>
>> >     return render_to_response(template_name, {
>> >         "blog_form": blog_form,
>>
>> >     }, context_instance=RequestContext(request))
>>
>> > Question 1:
>> > So far i found these 2 posts using map and instances in the view. Is
>> > that the way to solve 
>> > this?http://stackoverflow.com/questions/1477319/how-to-get-the-django-curr...
>>
>> > Question 2:
>> > Does the def save() in the model need alteration? Or addition of a def
>> > save_m2m() ? Change gives a 'super' object has no attribute 'save_m2m'
>>
>> > Thanks
>>
>> From the link you provided.
>>
>> "[..] To work around this problem, every time you save a form using
>> commit=False, Django adds a save_m2m() method to your ModelForm
>> subclass."
>>
>> Try adding blog.save(commit=False) instead of just blog.save()
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
>
>
>
>
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Re: Save inline instances first

2010-01-18 Thread Marco Rogers

I had a need for this at one point because my main model had an
overridden save method that would modify the inlines. But it didn't
work because the inlines weren't there. I had to reverse the save
method and put it on the inline model. But in my case, there was no
reason not to do that.

:Marco


On Jan 18, 8:14 am, Karen Tracey  wrote:
> On Mon, Jan 18, 2010 at 6:23 AM, Gabriel Reis  wrote:
> > In the ModelAdmin using inline forms I would like to know if it is possible
> > to save the inline instances first/before saving the instance edited by the
> > main ModelAdmin form.
>
> Why do you want to?
>
> It can't be done when you are adding a new main model, since the inlines
> have a ForeignKey to the main model and the main model needs to have a
> primary key (thus needs to have been saved) before the inlines can be
> saved.  (For changes it might could be made to work, but it is not the way
> the admin code is written: it first saves the main model, then the inlines,
> just as it does for adding.)
>
> Karen
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Re: no attribute 'save_m2m'

2010-01-18 Thread GoSantoni
I didn't alter the model but the view

def new(request, form_class=BlogForm, template_name="blog/new.html"):
if request.method == "POST":
if request.POST["action"] == "create":
blog_form = form_class(request.user, request.POST)
if blog_form.is_valid():
blog = blog_form.save(commit=False)
blog.author = request.user
if getattr(settings, 'BEHIND_PROXY', False):
blog.creator_ip = request.META
["HTTP_X_FORWARDED_FOR"]
else:
blog.creator_ip = request.META['REMOTE_ADDR']
blog.save(commit=False)
request.user.message_set.create(message=_
("Successfully saved post '%s'") % blog.item)
if notification:
if blog.status == 2: # published
if friends: # @@@ might be worth having a
shortcut for sending to all friends
notification.send((x['friend'] for x in
Friendship.objects.friends_for_user(blog.author)),
"blog_friend_post",
{"post": blog})
return HttpResponseRedirect(reverse
("blog_list_yours"))
else:
blog_form = form_class()
else:
blog_form = form_class(request.user)
return render_to_response(template_name, {
"blog_form": blog_form,
}, context_instance=RequestContext(request))

There is no save in the form:

class BlogForm(forms.ModelForm):

user = 'mark'


slug = forms.SlugField(max_length=20,
help_text = _("unique name"),
error_message = _("This value must contain only letters,
numbers, underscores and hyphens."))
imagepost = forms.ModelChoiceField(queryset=Image.objects.filter
(member__username=user))

class Meta:

model = Post
exclude = ('author', 'creator_ip', 'created_at', 'updated_at',
'publish')

def __init__(self, user=None, *args, **kwargs):
self.user = user
super(BlogForm, self).__init__(*args, **kwargs)
self.fields['imagepost'].queryset = Image.objects.filter
(member=self.user)



def clean_slug(self):
if not self.instance.pk:
if Post.objects.filter(author=self.user,
created_at__month=datetime.now().month, created_at__year=datetime.now
().year, slug=self.cleaned_data['slug']).count():
raise forms.ValidationError(u'This field must be
unique for username, year, and month')
return self.cleaned_data['slug']
try:
post = Post.objects.get(author=self.user,
created_at__month=self.instance.created_at.month,
created_at__year=self.instance.created_at.year, slug=self.cleaned_data
['slug'])
if post != self.instance:
raise forms.ValidationError(u'This field must be
unique for username, year, and month')
except Post.DoesNotExist:
pass
return self.cleaned_data['slug']

This resulted in the TypeError

On Jan 18, 7:33 pm, Adam Knight  wrote:
> Ensure it's the save() method on the FORM and not the MODEL. :)
>
>
>
>
>
> On Mon, Jan 18, 2010 at 12:23 PM, GoSantoni  wrote:
> > Hi Nek4life,
>
> > Unfortunately that didn't work.
>
> > TypeError at /blog/new/
> > save() got an unexpected keyword argument 'commit'
> > Request Method: POST
> > Request URL:    http://localhost:8000/blog/new/
> > Exception Type: TypeError
> > Exception Value:
> > save() got an unexpected keyword argument 'commit'
>
> > On Jan 18, 4:21 pm, nek4life  wrote:
> >> On Jan 18, 10:01 am, GoSantoni  wrote:
>
> >> > Hi
>
> >> > Trying to use save_m2m as described 
> >> > herehttp://docs.djangoproject.com/en/1.0/topics/forms/modelforms/#the-sav...
> >> > Though in run into an attrribute error 'Post' object has no attribute
> >> > 'save_m2m'
>
> >> > *** Model ***
> >> > class Post(models.Model):
> >> >     id                     = models.AutoField(primary_key=True)
> >> >     imagepost       = models.ManyToManyField(Image, verbose_name=_
> >> > ('media'))
>
> >> >     def save(self, force_insert=False, force_update=False):
> >> >         self.updated_at = datetime.now()
> >> >         super(Post, self).save(force_insert, force_update)
>
> >> > *** View ***
> >> > def new(request, form_class=BlogForm, template_name="blog/new.html"):
> >> >     if request.method == "POST":
> >> >         if request.POST["action"] == "create":
> >> >             blog_form = form_class(request.user, request.POST)
> >> >             if blog_form.is_valid():
> >> >                 blog = blog_form.save(commit=False)
> >> >                 blog.author = request.user
> >> >                 if getattr(settings, 'BEHIND_PROXY', False):
> >> >                     blog.creator_ip = request.META
> >> > ["HTTP_X_FORWARDED_FOR"]
> >> >                 else:
> >> >                     blog.creator_ip = request.META['REMOTE_ADDR']
> >> >                 blog.save()
> >> >                 

Re: no attribute 'save_m2m'

2010-01-18 Thread Adam Knight
Ensure it's the save() method on the FORM and not the MODEL. :)

On Mon, Jan 18, 2010 at 12:23 PM, GoSantoni  wrote:
> Hi Nek4life,
>
> Unfortunately that didn't work.
>
> TypeError at /blog/new/
> save() got an unexpected keyword argument 'commit'
> Request Method: POST
> Request URL:    http://localhost:8000/blog/new/
> Exception Type: TypeError
> Exception Value:
> save() got an unexpected keyword argument 'commit'
>
> On Jan 18, 4:21 pm, nek4life  wrote:
>> On Jan 18, 10:01 am, GoSantoni  wrote:
>>
>>
>>
>>
>>
>> > Hi
>>
>> > Trying to use save_m2m as described 
>> > herehttp://docs.djangoproject.com/en/1.0/topics/forms/modelforms/#the-sav...
>> > Though in run into an attrribute error 'Post' object has no attribute
>> > 'save_m2m'
>>
>> > *** Model ***
>> > class Post(models.Model):
>> >     id                     = models.AutoField(primary_key=True)
>> >     imagepost       = models.ManyToManyField(Image, verbose_name=_
>> > ('media'))
>>
>> >     def save(self, force_insert=False, force_update=False):
>> >         self.updated_at = datetime.now()
>> >         super(Post, self).save(force_insert, force_update)
>>
>> > *** View ***
>> > def new(request, form_class=BlogForm, template_name="blog/new.html"):
>> >     if request.method == "POST":
>> >         if request.POST["action"] == "create":
>> >             blog_form = form_class(request.user, request.POST)
>> >             if blog_form.is_valid():
>> >                 blog = blog_form.save(commit=False)
>> >                 blog.author = request.user
>> >                 if getattr(settings, 'BEHIND_PROXY', False):
>> >                     blog.creator_ip = request.META
>> > ["HTTP_X_FORWARDED_FOR"]
>> >                 else:
>> >                     blog.creator_ip = request.META['REMOTE_ADDR']
>> >                 blog.save()
>> >                 blog.save_m2m()
>> >                 request.user.message_set.create(message=_
>> > ("Successfully saved post '%s'") % blog.item)
>> >                 if notification:
>> >                     if blog.status == 2: # published
>> >                         if friends: # @@@ might be worth having a
>> > shortcut for sending to all friends
>> >                             notification.send((x['friend'] for x in
>> > Friendship.objects.friends_for_user(blog.author)), "blog_friend_post",
>> > {"post": blog})
>>
>> >                 return HttpResponseRedirect(reverse
>> > ("blog_list_yours"))
>> >         else:
>> >             blog_form = form_class()
>> >     else:
>> >         blog_form = form_class(request.user)
>>
>> >     return render_to_response(template_name, {
>> >         "blog_form": blog_form,
>>
>> >     }, context_instance=RequestContext(request))
>>
>> > Question 1:
>> > So far i found these 2 posts using map and instances in the view. Is
>> > that the way to solve 
>> > this?http://stackoverflow.com/questions/1477319/how-to-get-the-django-curr...
>>
>> > Question 2:
>> > Does the def save() in the model need alteration? Or addition of a def
>> > save_m2m() ? Change gives a 'super' object has no attribute 'save_m2m'
>>
>> > Thanks
>>
>> From the link you provided.
>>
>> "[..] To work around this problem, every time you save a form using
>> commit=False, Django adds a save_m2m() method to your ModelForm
>> subclass."
>>
>> Try adding blog.save(commit=False) instead of just blog.save()
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
>
>
>
>



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




Re: no attribute 'save_m2m'

2010-01-18 Thread GoSantoni
Hi Nek4life,

Unfortunately that didn't work.

TypeError at /blog/new/
save() got an unexpected keyword argument 'commit'
Request Method: POST
Request URL:http://localhost:8000/blog/new/
Exception Type: TypeError
Exception Value:
save() got an unexpected keyword argument 'commit'

On Jan 18, 4:21 pm, nek4life  wrote:
> On Jan 18, 10:01 am, GoSantoni  wrote:
>
>
>
>
>
> > Hi
>
> > Trying to use save_m2m as described 
> > herehttp://docs.djangoproject.com/en/1.0/topics/forms/modelforms/#the-sav...
> > Though in run into an attrribute error 'Post' object has no attribute
> > 'save_m2m'
>
> > *** Model ***
> > class Post(models.Model):
> >     id                     = models.AutoField(primary_key=True)
> >     imagepost       = models.ManyToManyField(Image, verbose_name=_
> > ('media'))
>
> >     def save(self, force_insert=False, force_update=False):
> >         self.updated_at = datetime.now()
> >         super(Post, self).save(force_insert, force_update)
>
> > *** View ***
> > def new(request, form_class=BlogForm, template_name="blog/new.html"):
> >     if request.method == "POST":
> >         if request.POST["action"] == "create":
> >             blog_form = form_class(request.user, request.POST)
> >             if blog_form.is_valid():
> >                 blog = blog_form.save(commit=False)
> >                 blog.author = request.user
> >                 if getattr(settings, 'BEHIND_PROXY', False):
> >                     blog.creator_ip = request.META
> > ["HTTP_X_FORWARDED_FOR"]
> >                 else:
> >                     blog.creator_ip = request.META['REMOTE_ADDR']
> >                 blog.save()
> >                 blog.save_m2m()
> >                 request.user.message_set.create(message=_
> > ("Successfully saved post '%s'") % blog.item)
> >                 if notification:
> >                     if blog.status == 2: # published
> >                         if friends: # @@@ might be worth having a
> > shortcut for sending to all friends
> >                             notification.send((x['friend'] for x in
> > Friendship.objects.friends_for_user(blog.author)), "blog_friend_post",
> > {"post": blog})
>
> >                 return HttpResponseRedirect(reverse
> > ("blog_list_yours"))
> >         else:
> >             blog_form = form_class()
> >     else:
> >         blog_form = form_class(request.user)
>
> >     return render_to_response(template_name, {
> >         "blog_form": blog_form,
>
> >     }, context_instance=RequestContext(request))
>
> > Question 1:
> > So far i found these 2 posts using map and instances in the view. Is
> > that the way to solve 
> > this?http://stackoverflow.com/questions/1477319/how-to-get-the-django-curr...
>
> > Question 2:
> > Does the def save() in the model need alteration? Or addition of a def
> > save_m2m() ? Change gives a 'super' object has no attribute 'save_m2m'
>
> > Thanks
>
> From the link you provided.
>
> "[..] To work around this problem, every time you save a form using
> commit=False, Django adds a save_m2m() method to your ModelForm
> subclass."
>
> Try adding blog.save(commit=False) instead of just blog.save()
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Re: Newbie question : passing control from one view function to another. I get a function does not return an HttpResponse object error

2010-01-18 Thread harijay
Thanks Karen..
Did not realize that  "Running of the end of the code" in python
results in returning a None and not the last evaluated expression.

I wrote a small test case and realized what you said that without an
explicit return , python returns a None even though the evaluated
expression returns something. Makes a lot of sense

Thanks again

def func2(arg):
print "func2 called"
x = "Give me an arg"
return x

def func1(arg=None):
if arg != None:
x = "Thanks"
return x
else:
func2(arg)



if __name__=="__main__":
print "Calling first func with argument"
x = func1("hello")
print x
print "Calling first func without argument"
x = func1()
print x

On Jan 18, 7:40 am, Karen Tracey  wrote:
> On Sun, Jan 17, 2010 at 11:47 PM, Benjamin Welton <
>
> benjamin.r.wel...@wmich.edu> wrote:
> >   Since the call structure goes similar to this Django Internals ->
> > view_func1 -> authenticate_user. That return is required so that the Django
> > internals see the HttpResponse Class. Without this return all thats passed
> > back to django is None.
>
> To clarify, it is Python the language, not Django, that requires an explicit
> return value.  In Python, if a function or method wants to return something
> other than None, it much have an explicit return specifying what is to be
> returned.  "Running off the end of the code" results in the function/method
> returning None, not (as in some languages) the value of the last evaluated
> expression.
>
> Karen
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




AttributeError: 'module' object has no attribute 'DatabaseError'

2010-01-18 Thread abs
Trying to start dev server of django on mac os x with postresql
database.

bash-3.2$ ./manage.py runserver
Validating models...
Unhandled exception in thread started by 
Traceback (most recent call last):
  File "/Library/Python/2.6/site-packages/django/core/management/
commands/runserver.py", line 48, in inner_run
self.validate(display_num_errors=True)
  File "/Library/Python/2.6/site-packages/django/core/management/
base.py", line 249, in validate
num_errors = get_validation_errors(s, app)
  File "/Library/Python/2.6/site-packages/django/core/management/
validation.py", line 22, in get_validation_errors
from django.db import models, connection
  File "/Library/Python/2.6/site-packages/django/db/__init__.py", line
74, in 
connection = connections[DEFAULT_DB_ALIAS]
  File "/Library/Python/2.6/site-packages/django/db/utils.py", line
75, in __getitem__
backend = load_backend(db['ENGINE'])
  File "/Library/Python/2.6/site-packages/django/db/utils.py", line
20, in load_backend
return import_module('.base', backend_name)
  File "/Library/Python/2.6/site-packages/django/utils/importlib.py",
line 35, in import_module
__import__(name)
  File "/Library/Python/2.6/site-packages/django/db/backends/
postgresql_psycopg2/base.py", line 23, in 
DatabaseError = Database.DatabaseError
AttributeError: 'module' object has no attribute 'DatabaseError'

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-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Re: Efficient access through two manytomany layers

2010-01-18 Thread Alex Robbins
Probably need to solve the problem individually:

First problem: Performance.
Have you looked at using select_related[1] in your query? That might
speed up the loop since it would do all the lookups in one big query.
(It'll need more memory since it is loading it all at once, but it
will probably be faster since the db doesn't have to do a query for
every forloop iteration.

Hmm, you might also look at just doing something like
Event.objects.values_list
('classes_involved__parent_disciplines__name', flat=True).distinct().
That works on some relations, but I haven't tested it in your case.

Second problem: Save doesn't work right.
Sorry, don't have any good ideas here. Maybe the relations aren't
being updated until you call the superclass's save method? (ManyToMany
fields are a separate table internally. It probably isn't updated
until you save.) That happens after you compute self.disciplines. You
could try doing a super(Event, self).save(*args, **kwargs) before you
compute the disciplines list, and then again after you have computed
it, to save the value. That is two saves into the db for one admin
save, but it shouldn't be too hard on your db.

new save method:

super(Event, self).save(*args, **kwargs)
# variable the will be saved in a charfield on the event.
disciplines = []
 # get the related many to many field which has all the 'classes'
classes = self.classes_involved.all()
 for this_class in classes:
  parent_disciplines = this_class.parent_discipline.all()
  for disc in parent_disciplines:
  disciplines.append(str(disc.name))
self.disciplines = ', '.join(set(disciplines))
super(Event, self).save(*args, **kwargs)

Hope that helps,
Alex

[1] http://docs.djangoproject.com/en/dev/ref/models/querysets/#id4

On Jan 18, 10:32 am, Alastair Campbell  wrote:
> On Mon, Jan 18, 2010 at 2:59 PM, Alex Robbins
>
>  wrote:
> > Hmm, you posted the save method for your Event model, but not the
> > definition. I think you haven't gotten any feed back because no one
> > really knows what you are asking. Could you show the Event model, and
> > then show what a finished save should look like? What should the data
> > end up like?
>
> Thanks for the reply Alex, I hadn't posted the model definition
> because there's a lot of irrelevant stuff, but point taken, here's
> most of it:
>
> class Event(models.Model):
>         name = models.CharField("Listings title", max_length=100)
>         disciplines = models.CharField(max_length=250)
>         classes_involved =  models.ManyToManyField("categories.Class",
> blank=True, null=True)
>         start_date = models.DateField("First day of the event")
>         end_date = models.DateField("Last day of the event")
>         approved = models.BooleanField()
>         # some removed.
>         def __unicode__(self):
>                 return self.name
>
> It's fairly simple, the complex bit is filling in the disciplines. I
> tried to add something to the save() to fill it in.
>
> In the Admin area, the event form shows the classes_involved (a choice
> of about 20), but doesn't show the disciplines.
> I was hoping to fill in the disciplines from the classes_involved.
> It's just used in listings, not for comparison, so a text string is
> fine.
>
> There are two problems:
> 1. The performance hit by going through 2 levels of manytomany fields.
> The first to get all classes_involved and then for each of those, to
> get it's parent. (I assume this is bad, my laptop seems to think so.)
> 2. When I edit an event, the save() doesn't seem to work from the
> form-data, it works on the previously saved data. I.e. if edit the
> classes_involved once and save, the discipline is not adjusted. If I
> save it twice, the discipline is adjusted.
>
> I was aiming for a cheap way to do two-level categorisation, however,
> I'm now thinking I just keep the categories separate and make admin
> users fill in the discipline manually.
>
> Kind regards,
>
> -Alastair
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Re: Project layout: put templates and js/css together?

2010-01-18 Thread Bill Freeman
I suppose that you can do what you want, but in deployment static files like
js and css files are usually served by the front end (apache, for example),
while, despite the .html, templates are not static files, and should never be
served as is, only through the django template engine.  It is reasonably
easy to set up apache to serve a directory's content, including that in
sub-directories, while I don't know how to go about keeping it from serving
templates in the same directory.

Too bad they feel far away.  What are you using to edit them?

Bill

On Mon, Jan 18, 2010 at 8:49 AM, Stephan Walter  wrote:
> Hi,
> After having Django used a long time ago, I recently started a new
> project, using "django-admin.py startproject". What I found
> inconvenient is that in the default project layout, the templates and
> the static media are so "far away" from each other.
>
> What I mean is this: In the default structure, and also most layouts
> I've seen proposed in various blog posts etc, the file are arranged
> like this:
>
> my_site/
>    settings.py
>    urls.py
>    static/
>        css/
>            foo.css
>        js/
>            foo.js
>        images/
>    templates/
>        my_app/
>            base.html
>            foo.html
>    my_app/
>        models.py
>        views.py
>
> Now in my project there is a lot of client-side program logic, which
> means a lot of interaction between the HTML and Javascript/CSS. Say
> I'm editing the template foo.html, I'll likely need to edit foo.js and
> foo.css as well. But these are some two levels up and two levels down
> again in the directory hierarchy.
>
> Now what I'd like to do is something like this:
>
> my_site/
>    settings.py
>    urls.py
>    client/
>        base.html
>        foo/
>            foo.html
>            foo.css
>            foo.js
>        bar/
>            bar.html
>    server/
>        models.py
>        views.py
>
> That is, both MEDIA_ROOT and TEMPLATE_DIRS would point to
> my_site/client/. Of course I would forbid the webserver to serve the
> un-parsed HTML files.
>
> Are there any reasons not to organise my project like this? And at the
> risk of beating a dead horse with this topic, what are your
> suggestions to organize a small project that will not be
> redistributed/packaged/used elsewhere?
>
> -Stephan Walter
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
>
>
>
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Re: Efficient access through two manytomany layers

2010-01-18 Thread Alastair Campbell
On Mon, Jan 18, 2010 at 2:59 PM, Alex Robbins
 wrote:
> Hmm, you posted the save method for your Event model, but not the
> definition. I think you haven't gotten any feed back because no one
> really knows what you are asking. Could you show the Event model, and
> then show what a finished save should look like? What should the data
> end up like?

Thanks for the reply Alex, I hadn't posted the model definition
because there's a lot of irrelevant stuff, but point taken, here's
most of it:

class Event(models.Model):
name = models.CharField("Listings title", max_length=100)
disciplines = models.CharField(max_length=250)
classes_involved =  models.ManyToManyField("categories.Class",
blank=True, null=True)
start_date = models.DateField("First day of the event")
end_date = models.DateField("Last day of the event")
approved = models.BooleanField()
# some removed.
def __unicode__(self):
return self.name

It's fairly simple, the complex bit is filling in the disciplines. I
tried to add something to the save() to fill it in.

In the Admin area, the event form shows the classes_involved (a choice
of about 20), but doesn't show the disciplines.
I was hoping to fill in the disciplines from the classes_involved.
It's just used in listings, not for comparison, so a text string is
fine.

There are two problems:
1. The performance hit by going through 2 levels of manytomany fields.
The first to get all classes_involved and then for each of those, to
get it's parent. (I assume this is bad, my laptop seems to think so.)
2. When I edit an event, the save() doesn't seem to work from the
form-data, it works on the previously saved data. I.e. if edit the
classes_involved once and save, the discipline is not adjusted. If I
save it twice, the discipline is adjusted.

I was aiming for a cheap way to do two-level categorisation, however,
I'm now thinking I just keep the categories separate and make admin
users fill in the discipline manually.

Kind regards,

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




Re: Should Django handle uploaded files in PUT as well as POST?

2010-01-18 Thread Russell Keith-Magee
On Mon, Jan 18, 2010 at 5:23 PM, Masklinn  wrote:
> On 18 Jan 2010, at 03:04 , Russell Keith-Magee wrote:
>>
>> On Mon, Jan 18, 2010 at 8:14 AM, Malcolm Box  wrote:
>>> On Sat, Jan 16, 2010 at 4:58 AM, Russell Keith-Magee
>>>  wrote:

 On Sat, Jan 16, 2010 at 6:32 AM, Malcolm Box 
 wrote:
 
> It seems to me that Django should process POST and PUT requests the same
> -
> i.e. the request.FILES attribute should be initialised for either if a
> multipart content-type is detected.
>
> Have I fundamentally misunderstood how this stuff should work?

 On first inspection, I don't think you've got anything fundamentally
 wrong. Support for PUT and the other 'exotic' HTTP request methods is
 one area where Django support is a little bit patchy.

>>> Well that's good to know!
>>>

 This is mostly an artefact of the vast majority of browsers providing
 exactly zero support for requests other that GET and POST. As a result
 Django is (by necessity) really good at handling GET and POST; PUT,
 DELETE et al are all essential parts of the full HTTP spec, but
 support in Django isn't quite as comprehensive.

 This is one of those areas where patches are definitely welcome.

>>> I'm happy to provide some patches - presumably a bug report + patch is the
>>> way to go.
>>
>> As always.
>>
>>> Which raises the question of what the correct behaviour should be, so the
>>> bug can report that it's not happening and the patch can implement.
>>>
>>> As a first pass:
>>>
>>> "On a PUT request, Django should populate request.PUT and request.FILES in
>>> the same way as for POST requests.  FILES will be initialised if the content
>>> is multipart, and the PUT dictionary will have key/value pairs if the
>>> uploaded content included url-encoded form entries.
>>>
>>> If the format of the datastream is not understood, it will be left in
>>> _raw_post_data as previously, and req.FILES and req.PUT initialised to empty
>>> hashes."
>>>
>>> Does this sound reasonable as a bug/feature description?
>>
>> Sounds reasonable to me. I can't think of any obvious reason that the
>> handling for PUT should differ from POST.
>>
>> Yours,
>> Russ Magee %-)
>
>
> Does that mean the request object could have arbitrary HTTP_METHOD attributes 
> when it can parse the content as keys:values? At least if the MIME of the 
> request is `application/x-www-form-urlencoded`?
>
> I mean as far as I know nothing forbids creating custom HTTP methods (indeed, 
> that's what e.g. WEBDAV does) and some of these custom methods could very 
> well have the same properties as POST.

FYI, Section 5.1.1 of RFC 2616 specifically allows the definition of
extension methods.

I'm open to suggestions on how Django's handling of arbitrary
extension methods can be improved. As it stands, request.REQUEST will
contain all the query arguments that have been provided in a request,
regardless of the request method. This can already be used to support
extension request methods.

If you're looking for something more than this, feel free to make a
specific proposal. Personally I'm not sure I agree that having
request.FOOBAR is a good idea. There are many names that are legal
request methods, but aren't legal variable names, so we would need to
have a mapping scheme. We would also end up with a situation where
extension methods would only produce attributes when used, so
hasatttr(request, 'POST') would always succeed, but hasattr(request,
'FOOBAR') would only succeed if request.method == 'FOOBAR'.

However, as Malcolm notes - this is a separate issue to handling FILES
on a PUT request, so it should be handled as a separate ticket and
mailing list thread.

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




Re: no attribute 'save_m2m'

2010-01-18 Thread nek4life


On Jan 18, 10:01 am, GoSantoni  wrote:
> Hi
>
> Trying to use save_m2m as described 
> herehttp://docs.djangoproject.com/en/1.0/topics/forms/modelforms/#the-sav...
> Though in run into an attrribute error 'Post' object has no attribute
> 'save_m2m'
>
> *** Model ***
> class Post(models.Model):
>     id                     = models.AutoField(primary_key=True)
>     imagepost       = models.ManyToManyField(Image, verbose_name=_
> ('media'))
>
>     def save(self, force_insert=False, force_update=False):
>         self.updated_at = datetime.now()
>         super(Post, self).save(force_insert, force_update)
>
> *** View ***
> def new(request, form_class=BlogForm, template_name="blog/new.html"):
>     if request.method == "POST":
>         if request.POST["action"] == "create":
>             blog_form = form_class(request.user, request.POST)
>             if blog_form.is_valid():
>                 blog = blog_form.save(commit=False)
>                 blog.author = request.user
>                 if getattr(settings, 'BEHIND_PROXY', False):
>                     blog.creator_ip = request.META
> ["HTTP_X_FORWARDED_FOR"]
>                 else:
>                     blog.creator_ip = request.META['REMOTE_ADDR']
>                 blog.save()
>                 blog.save_m2m()
>                 request.user.message_set.create(message=_
> ("Successfully saved post '%s'") % blog.item)
>                 if notification:
>                     if blog.status == 2: # published
>                         if friends: # @@@ might be worth having a
> shortcut for sending to all friends
>                             notification.send((x['friend'] for x in
> Friendship.objects.friends_for_user(blog.author)), "blog_friend_post",
> {"post": blog})
>
>                 return HttpResponseRedirect(reverse
> ("blog_list_yours"))
>         else:
>             blog_form = form_class()
>     else:
>         blog_form = form_class(request.user)
>
>     return render_to_response(template_name, {
>         "blog_form": blog_form,
>
>     }, context_instance=RequestContext(request))
>
> Question 1:
> So far i found these 2 posts using map and instances in the view. Is
> that the way to solve 
> this?http://stackoverflow.com/questions/1477319/how-to-get-the-django-curr...http://haineault.com/blog/101/
>
> Question 2:
> Does the def save() in the model need alteration? Or addition of a def
> save_m2m() ? Change gives a 'super' object has no attribute 'save_m2m'
>
> Thanks

>From the link you provided.

"[..] To work around this problem, every time you save a form using
commit=False, Django adds a save_m2m() method to your ModelForm
subclass."

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




no attribute 'save_m2m'

2010-01-18 Thread GoSantoni
Hi

Trying to use save_m2m as described here
http://docs.djangoproject.com/en/1.0/topics/forms/modelforms/#the-save-method
Though in run into an attrribute error 'Post' object has no attribute
'save_m2m'

*** Model ***
class Post(models.Model):
id = models.AutoField(primary_key=True)
imagepost   = models.ManyToManyField(Image, verbose_name=_
('media'))

def save(self, force_insert=False, force_update=False):
self.updated_at = datetime.now()
super(Post, self).save(force_insert, force_update)

*** View ***
def new(request, form_class=BlogForm, template_name="blog/new.html"):
if request.method == "POST":
if request.POST["action"] == "create":
blog_form = form_class(request.user, request.POST)
if blog_form.is_valid():
blog = blog_form.save(commit=False)
blog.author = request.user
if getattr(settings, 'BEHIND_PROXY', False):
blog.creator_ip = request.META
["HTTP_X_FORWARDED_FOR"]
else:
blog.creator_ip = request.META['REMOTE_ADDR']
blog.save()
blog.save_m2m()
request.user.message_set.create(message=_
("Successfully saved post '%s'") % blog.item)
if notification:
if blog.status == 2: # published
if friends: # @@@ might be worth having a
shortcut for sending to all friends
notification.send((x['friend'] for x in
Friendship.objects.friends_for_user(blog.author)), "blog_friend_post",
{"post": blog})

return HttpResponseRedirect(reverse
("blog_list_yours"))
else:
blog_form = form_class()
else:
blog_form = form_class(request.user)

return render_to_response(template_name, {
"blog_form": blog_form,

}, context_instance=RequestContext(request))

Question 1:
So far i found these 2 posts using map and instances in the view. Is
that the way to solve this?
http://stackoverflow.com/questions/1477319/how-to-get-the-django-current-login-user
http://haineault.com/blog/101/

Question 2:
Does the def save() in the model need alteration? Or addition of a def
save_m2m() ? Change gives a 'super' object has no attribute 'save_m2m'

Thanks

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




Re: Efficient access through two manytomany layers

2010-01-18 Thread Alex Robbins
Hmm, you posted the save method for your Event model, but not the
definition. I think you haven't gotten any feed back because no one
really knows what you are asking. Could you show the Event model, and
then show what a finished save should look like? What should the data
end up like?

Alex

On Jan 17, 3:41 pm, Alastair Campbell  wrote:
> Hi everyone,
>
> I have something that works, but I'm guessing it's *very* inefficient,
> I'm guessing that nested for-loops for two layers of many to many
> fields is bad, but how could I go about this better?
>
> The aim is for my admin users to fill in the sub-categories (classes),
> and for the system to work out which parent categories (disciplines)
> are involved.
>
> I have a separate model for taxonomy, and within my 'categories'
> models.py I have:
>
> class Discipline(models.Model):
>         name = models.CharField(max_length=50)
>         slug = models.SlugField(unique=True)
>
> class Class(models.Model):
>         name = models.CharField(max_length=50)
>         slug = models.SlugField(unique=True)
>         parent_discipline = models.ManyToManyField("Discipline")
>
> Sorry about using 'Class' as the model name, but unfortunately it's
> the only thing that makes sense for this categorisation.
> (E.g. the discipline might be slalom, which has a class of amatuer within it.)
>
> This is added to the save method for my Events model:
>
> # variable the will be saved in a charfield on the event.
> disciplines = []
>  # get the related many to many field which has all the 'classes'
> classes = self.classes_involved.all()
>
>  for this_class in classes:
>       parent_disciplines = this_class.parent_discipline.all()
>       for disc in parent_disciplines:
>           disciplines.append(str(disc.name))
>
> this_set = set(disciplines)
> this_list = list(this_set)
> self.disciplines = ', '.join(this_list)
>
> super(Event, self).save(*args, **kwargs)
>
> Any ideas on how I could go about this better? I'd hoped to make
> things easier with a centrally defined taxonomy, but so far it isn't
> worked to well.
>
> Kind regards,
>
> -Alastair
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Re: Admin list_display loop though sub objects and output sum of values - newbie

2010-01-18 Thread Alex Robbins
There is also an online version of one of the django books here:
http://djangobook.com/

On Jan 17, 5:08 pm, pfwd  wrote:
> Thanks fantastic thank you
> I was also able to do:
> result = obj.task_set.aggregate(Count('id'))['id__count']
> to get the a count of the tasks for quote
>
> I don't suppose you know any good books regarding Python/Django that I
> could buy to help me learn the syntax better?
>
> Many thanks
>
> On Jan 17, 10:15 pm, Daniel Roseman  wrote:
>
>
>
> > On Jan 17, 8:28 pm, pfwd  wrote:
>
> > > Hi am very new to Django/Python and I need some help with a model
> > > method
>
> > > I have two tables Linked by a foreign key and their forms are embedded
> > > in the admin interface.
> > > One table is called Quote and one table is called Task. The task table
> > > has a field called time_taken
> > > In the Quote list I want to display the total amount of time to under
> > > go all the tasks in each quote.
>
> > > This is what I'm doing and its just displaying (None) in the list
>
> > > class QuoteAdmin(admin.ModelAdmin):
> > >         fieldset = [
> > >                 (None, {'fields': ['q_number']})
> > >         ]
> > >         inlines = [TaskInline]
>
> > >         list_display = ('q_number', 'total_time','created_date')
>
> > >         def total_time(self,queryset):
> > >                 task_objs = self.Task.objects.all()
>
> > >                 total_time = 'No time taken'
>
> > >                 for record in task_objs:
> > >                         total_time = total_time + record.time_taken
> > >                 return total_time
>
> > > I'm trying to get all the tasks for each quote by doing
> > > self.Task.objects.all() and then looping through them and adding the
> > > time_taken to the var total_time.
>
> > > I guess this syntax is just plain wrong or the method is not being
> > > called as its not showing any errors
> > > I have a javascript/PHP background and I would like to learn more
> > > Python
> > > - Please be kind :)
>
> > OK a few pointers.
>
> > * a custom list_display method takes parameters (self, obj), where obj
> > is the object being displayed in that row - here it's an instance of
> > Quote.
> > * 'self.Task' means nothing. You want to get the tasks related to the
> > Quote, which is in 'obj', so you use 'obj.task_set.all()'. With this,
> > your code would work as is.
> > * A nicer way of doing it would be to get the DB to sum the time_taken
> > values. This should work:
> >     from django.db.models import Sum
> >     return obj.task_set.aggregate(Sum('time_taken'))
> > ['time_taken__sum']
> > (the square brackets at the end are needed because 'aggregate' returns
> > a dictionary, and we just want the value from there).
> > --
> > DR.
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Re: Linked list of abstract objects

2010-01-18 Thread Alex Robbins
Also, I think you'll need to make those relations to a class that
isn't abstract. Right now you have a 'class Meta: abstract=True' That
means your model doesn't really exist for the relations to link to.

Hope that helps,
Alex

On Jan 18, 2:26 am, Kerrick  wrote:
> I'm trying to implement a linked list of abstract objects in my
> models.py; however, it is throwing an error.
> --activenotes/models.py--
> class Element(models.Model):
>     class Meta:
>         abstract = True
>     prev = models.OneToOneField('Element', null=True, blank=True)
>     next = models.OneToOneField('Element', null=True, blank=True)
>
> class Text(Element):
>     contents = models.TextField()
> --end--
> --output of python manage.py syncdb--
> Error: One or more models did not validate:
> activenotes.text: 'prev' has a relation with model Element, which has
> either not been installed or is abstract.
> activenotes.text: 'next' has a relation with model Element, which has
> either not been installed or is abstract.
> --end--
> How can I rectify the problem?
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Re: Save, Signals and Models

2010-01-18 Thread Victor Loureiro Lima
Thanks Eric, that worked like a charm. I've never got to use the update,
thus I had no idea of its existence, fair enough that is exactelly what I
needed.

Thank you very much, and other who have answered this thread.
Victor Lima

2010/1/16 Eric Chamberlain 

>
> On Jan 15, 2010, at 4:22 PM, Victor Loureiro Lima wrote:
>
> > Here is the deal:
> >
> > class MyModel ( models.Model ):
> >   title = models.CharField( max_length = 100 )
> >   only_me = models.BooleanField( default = False )
> >
> >  Question: Whats the proper way to guarantee that no matter how many
> MyModel's are available in the database, only one of them
> > will have the only_me set as True? To further clarify things: In the
> admin, whenever I check the only_me checkbox, and save my model, all other
> models of this class will have to have its own only_me field set to false.
> >
> >  As far as I know, there is no other way of doing this unless I iterate
> over all MyModel' s objects and uncheck them if they are checked, save them,
> then afterwards check the model that I am actually saving setting the
> only_me field to True.
> >
> >  I tried doing this on the actual save() of the model, no success.
> Everytime I called save on iterated objects, I, of course, got the maximum
> recursive depth error thrown at me.
> >  Fair enough, I quickly thought about signals, hooking my function to
> post_save(), however I inevitabilly stumbled upon the same
> > problem: When I called save() on the iterated objects the post_save
> signal got sent, I would step again in the same function, thus
> > no cookie for me.
> >  I jumped over to overriding AdminForm' s save() method, so that I would
> iterate there on the models unchecking them if necessary, and them returning
> the proper object, but I stopped that and I said to myself that I must be
> doing something really stupid, so Im coming to you guys: What would the
> propper way of doing this?
> >
>
> def save(self, force_insert=False, force_update=False):
>if self.only_me is True:
># if this is the new default, set others to False
>MyModel.objects.exclude(pk=self.pk).update(only_me=False)
>
>super(MyModel, self).save(force_insert, force_update) # Call the
> "real" save() method.
>
>
> --
> Eric Chamberlain, Founder
> RF.com - http://RF.com/
>
>
>
>
>
>
>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>
>
>
-- 

You received this message because you are subscribed to the Google Groups "Django users" group.

To post to this group, send email to django-us...@googlegroups.com.

To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/django-users?hl=en.



Re: Debugging Templates

2010-01-18 Thread diofeher
I think this would help you:
http://github.com/robhudson/django-debug-toolbar

On 17 jan, 14:51, oakmad  wrote:
> What is the best way to debug templates when data is not showing?
>
> Here is my problem. I'm using Google App Engine with app-engine-patch
> so I realize it may not be a Django specific issue. I have one
> property on a model that will not display on my template yet all the
> model's other properties display just fine. When I load the model
> using the shell all the properties are available and work properly, it
> just when I am interacting with them in templates I am having trouble
> with them. Are there any tools that can help me debug the template to
> see what might be going on?
>
> Thanks
>
> Adam
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Project layout: put templates and js/css together?

2010-01-18 Thread Stephan Walter
Hi,
After having Django used a long time ago, I recently started a new
project, using "django-admin.py startproject". What I found
inconvenient is that in the default project layout, the templates and
the static media are so "far away" from each other.

What I mean is this: In the default structure, and also most layouts
I've seen proposed in various blog posts etc, the file are arranged
like this:

my_site/
   settings.py
   urls.py
   static/
       css/
           foo.css
       js/
           foo.js
       images/
   templates/
       my_app/
           base.html
           foo.html
   my_app/
       models.py
       views.py

Now in my project there is a lot of client-side program logic, which
means a lot of interaction between the HTML and Javascript/CSS. Say
I'm editing the template foo.html, I'll likely need to edit foo.js and
foo.css as well. But these are some two levels up and two levels down
again in the directory hierarchy.

Now what I'd like to do is something like this:

my_site/
settings.py
urls.py
client/
base.html
foo/
foo.html
foo.css
foo.js
bar/
bar.html
server/
models.py
views.py

That is, both MEDIA_ROOT and TEMPLATE_DIRS would point to
my_site/client/. Of course I would forbid the webserver to serve the
un-parsed HTML files.

Are there any reasons not to organise my project like this? And at the
risk of beating a dead horse with this topic, what are your
suggestions to organize a small project that will not be
redistributed/packaged/used elsewhere?

-Stephan Walter

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




Re: Linked list of abstract objects

2010-01-18 Thread Gonzalo Delgado
El 18/01/10 05:26, Kerrick escribió:
> I'm trying to implement a linked list of abstract objects in my
> models.py; however, it is throwing an error.
> --activenotes/models.py--
> class Element(models.Model):
> class Meta:
> abstract = True
> prev = models.OneToOneField('Element', null=True, blank=True)
> next = models.OneToOneField('Element', null=True, blank=True)
>
> class Text(Element):
> contents = models.TextField()
> --end--
> --output of python manage.py syncdb--
> Error: One or more models did not validate:
> activenotes.text: 'prev' has a relation with model Element, which has
> either not been installed or is abstract.
> activenotes.text: 'next' has a relation with model Element, which has
> either not been installed or is abstract.
> --end--
> How can I rectify the problem?
>   
Try using 'self'[0] instead of 'Element', as in:

prev = models.OneToOneField('self', null=True, blank=True)

This will probably fail too. In that case, make sure to use the
related_name[1] option in the field definition.

[0]
http://docs.djangoproject.com/en/1.1/ref/models/fields/#recursive-relationships
[1]
http://docs.djangoproject.com/en/1.1/ref/models/fields/#django.db.models.ForeignKey.related_name

-- 
Gonzalo Delgado 

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




Re: Save inline instances first

2010-01-18 Thread Karen Tracey
On Mon, Jan 18, 2010 at 6:23 AM, Gabriel Reis  wrote:

> In the ModelAdmin using inline forms I would like to know if it is possible
> to save the inline instances first/before saving the instance edited by the
> main ModelAdmin form.
>

Why do you want to?

It can't be done when you are adding a new main model, since the inlines
have a ForeignKey to the main model and the main model needs to have a
primary key (thus needs to have been saved) before the inlines can be
saved.  (For changes it might could be made to work, but it is not the way
the admin code is written: it first saves the main model, then the inlines,
just as it does for adding.)

Karen
-- 

You received this message because you are subscribed to the Google Groups "Django users" group.

To post to this group, send email to django-us...@googlegroups.com.

To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/django-users?hl=en.



Re: null = True and blank = True in contenttypes generic relations: why not ?

2010-01-18 Thread Karen Tracey
On Mon, Jan 18, 2010 at 3:58 AM, Alessandro Pasotti wrote:

> Hello,
>
> I would like to have a table with optional pointers to other tables
> items, generic relations would do it fine, the only problem seems to
> be the fact that generic forreign keys don't accept null values.
>
> Any hint or idea about why NOT NULL is enforced in this kind of relations ?
>

What is enforced is what you specify for the underlying database fields.
Modifying the doc example to allow these to be empty:

class TaggedItem(models.Model):
tag = models.SlugField()
content_type = models.ForeignKey(ContentType, null=True, blank=True)
object_id = models.PositiveIntegerField(null=True, blank=True)
content_object = generic.GenericForeignKey('content_type', 'object_id')

allows creation of objects that have no specified contect_object:

>>> from ttt.models import TaggedItem
>>> ti = TaggedItem.objects.create(tag='Empty')
>>> ti

>>> ti.content_object
>>>

Karen
-- 

You received this message because you are subscribed to the Google Groups "Django users" group.

To post to this group, send email to django-us...@googlegroups.com.

To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/django-users?hl=en.



Re: Newbie question : passing control from one view function to another. I get a function does not return an HttpResponse object error

2010-01-18 Thread Karen Tracey
On Sun, Jan 17, 2010 at 11:47 PM, Benjamin Welton <
benjamin.r.wel...@wmich.edu> wrote:

>   Since the call structure goes similar to this Django Internals ->
> view_func1 -> authenticate_user. That return is required so that the Django
> internals see the HttpResponse Class. Without this return all thats passed
> back to django is None.
>


To clarify, it is Python the language, not Django, that requires an explicit
return value.  In Python, if a function or method wants to return something
other than None, it much have an explicit return specifying what is to be
returned.  "Running off the end of the code" results in the function/method
returning None, not (as in some languages) the value of the last evaluated
expression.

Karen
-- 

You received this message because you are subscribed to the Google Groups "Django users" group.

To post to this group, send email to django-us...@googlegroups.com.

To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/django-users?hl=en.



Linked list of abstract objects

2010-01-18 Thread Kerrick
I'm trying to implement a linked list of abstract objects in my
models.py; however, it is throwing an error.
--activenotes/models.py--
class Element(models.Model):
class Meta:
abstract = True
prev = models.OneToOneField('Element', null=True, blank=True)
next = models.OneToOneField('Element', null=True, blank=True)

class Text(Element):
contents = models.TextField()
--end--
--output of python manage.py syncdb--
Error: One or more models did not validate:
activenotes.text: 'prev' has a relation with model Element, which has
either not been installed or is abstract.
activenotes.text: 'next' has a relation with model Element, which has
either not been installed or is abstract.
--end--
How can I rectify the problem?
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Re: Should Django handle uploaded files in PUT as well as POST?

2010-01-18 Thread Malcolm Box
On Mon, Jan 18, 2010 at 9:23 AM, Masklinn  wrote:

> On 18 Jan 2010, at 03:04 , Russell Keith-Magee wrote:
> >
> > On Mon, Jan 18, 2010 at 8:14 AM, Malcolm Box 
> wrote:
> >> On Sat, Jan 16, 2010 at 4:58 AM, Russell Keith-Magee
> >> Which raises the question of what the correct behaviour should be, so
> the
> >> bug can report that it's not happening and the patch can implement.
> >>
> >> As a first pass:
> >>
> >> "On a PUT request, Django should populate request.PUT and request.FILES
> in
> >> the same way as for POST requests.  FILES will be initialised if the
> content
> >> is multipart, and the PUT dictionary will have key/value pairs if the
> >> uploaded content included url-encoded form entries.
> >>
> >> If the format of the datastream is not understood, it will be left in
> >> _raw_post_data as previously, and req.FILES and req.PUT initialised to
> empty
> >> hashes."
> >>
> >> Does this sound reasonable as a bug/feature description?
> >
> > Sounds reasonable to me. I can't think of any obvious reason that the
> > handling for PUT should differ from POST.
>
> Does that mean the request object could have arbitrary HTTP_METHOD
> attributes when it can parse the content as keys:values? At least if the
> MIME of the request is `application/x-www-form-urlencoded`?
>
> I mean as far as I know nothing forbids creating custom HTTP methods
> (indeed, that's what e.g. WEBDAV does) and some of these custom methods
> could very well have the same properties as POST.
>

I don't see why not, although that's not what I'm planning to submit patches
for - I'm just aiming to cover PUT ie to complete the support for the core
HTTP methods that are allowed entity bodies.

So the HttpRequest object will grow a new PUT attribute, but nothing else.

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-us...@googlegroups.com.

To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/django-users?hl=en.



Save inline instances first

2010-01-18 Thread Gabriel Reis
Hi,

In the ModelAdmin using inline forms I would like to know if it is possible
to save the inline instances first/before saving the instance edited by the
main ModelAdmin form.

Thanks for your consideration.

Kind regards,

Gabriel


Gabriel de Carvalho Nogueira Reis
Software Developer
+44 7907 823942
-- 

You received this message because you are subscribed to the Google Groups "Django users" group.

To post to this group, send email to django-us...@googlegroups.com.

To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/django-users?hl=en.



ANN: LFC - a CMS

2010-01-18 Thread Kai Diefenbach

Hi guys,

I would like to announce the alpha release of LFC - a CMS based on Django:

- http://pypi.python.org/pypi/django-lfc

You will also find the installation instruction there.

Some documentation can be found here:

- http://packages.python.org/django-lfc/general/overview.html

Some first impression can be found here:

- http://screencast.com/t/OWI2ODY5 (Images & Portlets)
- http://screencast.com/t/OTZlY2E0Yjgt (Templates)
- http://screencast.com/t/MjA5MjU4Mzgt (Multi languages)

A few pages are in production:

- http://www.getlfs.com
- http://www.iqpp.de
- http://www.demmelhuber.net

If you have any suggestions or questions please don't hesitate to get 
in contact.


Thanks
Kai




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




Re: Should Django handle uploaded files in PUT as well as POST?

2010-01-18 Thread Masklinn
On 18 Jan 2010, at 03:04 , Russell Keith-Magee wrote:
> 
> On Mon, Jan 18, 2010 at 8:14 AM, Malcolm Box  wrote:
>> On Sat, Jan 16, 2010 at 4:58 AM, Russell Keith-Magee
>>  wrote:
>>> 
>>> On Sat, Jan 16, 2010 at 6:32 AM, Malcolm Box 
>>> wrote:
>>> 
 It seems to me that Django should process POST and PUT requests the same
 -
 i.e. the request.FILES attribute should be initialised for either if a
 multipart content-type is detected.
 
 Have I fundamentally misunderstood how this stuff should work?
>>> 
>>> On first inspection, I don't think you've got anything fundamentally
>>> wrong. Support for PUT and the other 'exotic' HTTP request methods is
>>> one area where Django support is a little bit patchy.
>>> 
>> Well that's good to know!
>> 
>>> 
>>> This is mostly an artefact of the vast majority of browsers providing
>>> exactly zero support for requests other that GET and POST. As a result
>>> Django is (by necessity) really good at handling GET and POST; PUT,
>>> DELETE et al are all essential parts of the full HTTP spec, but
>>> support in Django isn't quite as comprehensive.
>>> 
>>> This is one of those areas where patches are definitely welcome.
>>> 
>> I'm happy to provide some patches - presumably a bug report + patch is the
>> way to go.
> 
> As always.
> 
>> Which raises the question of what the correct behaviour should be, so the
>> bug can report that it's not happening and the patch can implement.
>> 
>> As a first pass:
>> 
>> "On a PUT request, Django should populate request.PUT and request.FILES in
>> the same way as for POST requests.  FILES will be initialised if the content
>> is multipart, and the PUT dictionary will have key/value pairs if the
>> uploaded content included url-encoded form entries.
>> 
>> If the format of the datastream is not understood, it will be left in
>> _raw_post_data as previously, and req.FILES and req.PUT initialised to empty
>> hashes."
>> 
>> Does this sound reasonable as a bug/feature description?
> 
> Sounds reasonable to me. I can't think of any obvious reason that the
> handling for PUT should differ from POST.
> 
> Yours,
> Russ Magee %-)


Does that mean the request object could have arbitrary HTTP_METHOD attributes 
when it can parse the content as keys:values? At least if the MIME of the 
request is `application/x-www-form-urlencoded`?

I mean as far as I know nothing forbids creating custom HTTP methods (indeed, 
that's what e.g. WEBDAV does) and some of these custom methods could very well 
have the same properties as POST.-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Re: Send and Receive SMS from a django app

2010-01-18 Thread Alessandro Ronchi
On Sun, Jan 17, 2010 at 7:18 PM, Chris Withers wrote:

> Alessandro Ronchi wrote:
>
>> I cannot use an SMS gateway for my app (I must use a SIM and an hardware
>> modem).
>>
>
> Why? This is not a sane requirement for a web app...
>
> Chris


Because of the number of the SMS I must write. I need a web app that makes
intense use of SMS without any external dependences (like Unicef app).



-- 
Alessandro Ronchi

http://www.soasi.com
SOASI - Sviluppo Software e Sistemi Open Source

http://hobbygiochi.com
Hobby & Giochi, l'e-commerce del divertimento
-- 

You received this message because you are subscribed to the Google Groups "Django users" group.

To post to this group, send email to django-us...@googlegroups.com.

To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/django-users?hl=en.



Re: Should Django handle uploaded files in PUT as well as POST?

2010-01-18 Thread Malcolm Box
On Mon, Jan 18, 2010 at 2:04 AM, Russell Keith-Magee  wrote:

> On Mon, Jan 18, 2010 at 8:14 AM, Malcolm Box 
> wrote:
> > On Sat, Jan 16, 2010 at 4:58 AM, Russell Keith-Magee> Which raises the
> question of what the correct behaviour should be, so the
> > bug can report that it's not happening and the patch can implement.
> >
> > As a first pass:
> >
> > "On a PUT request, Django should populate request.PUT and request.FILES
> in
> > the same way as for POST requests.  FILES will be initialised if the
> content
> > is multipart, and the PUT dictionary will have key/value pairs if the
> > uploaded content included url-encoded form entries.
> >
> > If the format of the datastream is not understood, it will be left in
> > _raw_post_data as previously, and req.FILES and req.PUT initialised to
> empty
> > hashes."
> >
> > Does this sound reasonable as a bug/feature description?
>
> Sounds reasonable to me. I can't think of any obvious reason that the
> handling for PUT should differ from POST.
>
>
Ticket http://code.djangoproject.com/ticket/12635 raised.  Patches to
follow.

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-us...@googlegroups.com.

To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/django-users?hl=en.



null = True and blank = True in contenttypes generic relations: why not ?

2010-01-18 Thread Alessandro Pasotti
Hello,

I would like to have a table with optional pointers to other tables
items, generic relations would do it fine, the only problem seems to
be the fact that generic forreign keys don't accept null values.

Any hint or idea about why NOT NULL is enforced in this kind of relations ?


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




Re: django hosting

2010-01-18 Thread nostradamnit
bells-n-whistles.net appears to be dead, but www.alwaysdata.com is
alive and providing excellent hosting, with a free option.

On Jan 17, 1:59 pm, alrobeler  wrote:
> hi i ve heard you can provide with free django 
> hostinghttp://www.jjude.com/2008/06/10/a-free-but-superb-django-hosting/
> if this service is still actual
> can i afford torequest one account provided by you?
> for the Django-based cms delopment and testing
> --
> many thanks in advance and best regards
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Re: Admin list_display loop though sub objects and output sum of values - newbie

2010-01-18 Thread nostradamnit
I recommend this book - and the answer to your question is in chapter
8.
http://www.amazon.com/Practical-Django-Projects-Pratical/dp/1590599969

go ahead and get this one too
http://www.amazon.com/Python-Essential-Reference-David-Beazley/dp/0672329786/ref=pd_sim_b_4

and read http://diveintopython.org/ as well :)



On Jan 18, 12:08 am, pfwd  wrote:
> Thanks fantastic thank you
> I was also able to do:
> result = obj.task_set.aggregate(Count('id'))['id__count']
> to get the a count of the tasks for quote
>
> I don't suppose you know any good books regarding Python/Django that I
> could buy to help me learn the syntax better?
>
> Many thanks
>
> On Jan 17, 10:15 pm, Daniel Roseman  wrote:
>
> > On Jan 17, 8:28 pm, pfwd  wrote:
>
> > > Hi am very new to Django/Python and I need some help with a model
> > > method
>
> > > I have two tables Linked by a foreign key and their forms are embedded
> > > in the admin interface.
> > > One table is called Quote and one table is called Task. The task table
> > > has a field called time_taken
> > > In the Quote list I want to display the total amount of time to under
> > > go all the tasks in each quote.
>
> > > This is what I'm doing and its just displaying (None) in the list
>
> > > class QuoteAdmin(admin.ModelAdmin):
> > >         fieldset = [
> > >                 (None, {'fields': ['q_number']})
> > >         ]
> > >         inlines = [TaskInline]
>
> > >         list_display = ('q_number', 'total_time','created_date')
>
> > >         def total_time(self,queryset):
> > >                 task_objs = self.Task.objects.all()
>
> > >                 total_time = 'No time taken'
>
> > >                 for record in task_objs:
> > >                         total_time = total_time + record.time_taken
> > >                 return total_time
>
> > > I'm trying to get all the tasks for each quote by doing
> > > self.Task.objects.all() and then looping through them and adding the
> > > time_taken to the var total_time.
>
> > > I guess this syntax is just plain wrong or the method is not being
> > > called as its not showing any errors
> > > I have a javascript/PHP background and I would like to learn more
> > > Python
> > > - Please be kind :)
>
> > OK a few pointers.
>
> > * a custom list_display method takes parameters (self, obj), where obj
> > is the object being displayed in that row - here it's an instance of
> > Quote.
> > * 'self.Task' means nothing. You want to get the tasks related to the
> > Quote, which is in 'obj', so you use 'obj.task_set.all()'. With this,
> > your code would work as is.
> > * A nicer way of doing it would be to get the DB to sum the time_taken
> > values. This should work:
> >     from django.db.models import Sum
> >     return obj.task_set.aggregate(Sum('time_taken'))
> > ['time_taken__sum']
> > (the square brackets at the end are needed because 'aggregate' returns
> > a dictionary, and we just want the value from there).
> > --
> > DR.
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Re: My Own Auth Backend

2010-01-18 Thread nostradamnit
Olivier,

Look at this - 
http://stackoverflow.com/questions/1057149/django-users-and-authentication-from-external-source

I imagine your problem comes from the fact that django.contrib.auth
User is tied to the DB

Sam

On Jan 18, 12:09 am, Olivier Détour  wrote:
> up
>
> 2010/1/16 Détour Olivier :
>
>
>
> > Hi,
> > I would create my own auth backend. I tried to understand and trace
> > source code.
> > I want to create an internal DB with SHA1 and username.
> > But I cannot login, Django says me I do not set DB ENGINE. I would not
> > use something like MySQL or any DB Engine.
>
> > Here is my source code:
> > mybackend.py:
>
> > from django.contrib.auth.models import User
> > from django.contrib.auth.backends    import RemoteUserBackend
>
> > class MyUser (User):
> >  def save (self):
> >    """saving to DB disabled"""
> >    pass
>
> >  objects = None # we cannot really use this w/o local DB
> >  username = ""  # and all the other properties likewise.
> >                 # They're defined as model.CharField or similar,
> >                 # and we can't allow that
>
> >  def get_group_permissions (self):
> >    """If you don't make your own permissions module,
> >       the default also will use the DB. Throw it away"""
> >    return [] # likewise with the other permission defs
>
> >  def get_and_delete_messages (self):
> >    """Messages are stored in the DB. Darn!"""
> >    return []
>
> > class WWWBackend (RemoteUserBackend):
> >  # Create a User object if not already in the database?
> >  create_unknown_user = False
>
> >  def get_user (self, user_id):
> >    user = somehow_create_an_instance_of(MyUser, user_id)
> >    return user
>
> >  def authenticate (self, username=None, password=None):
> >    if username == "lol" and password == "lol":
> >      user = MyUser(username=username, password=password)
> >      return user
> >    return None
>
> > my view.py:
>
> > from django import forms
> > from django.core.context_processors import csrf
> > from django.template import RequestContext, loader
> > from django.http import HttpResponse, HttpResponseRedirect
> > from django.contrib.auth import authenticate, login
>
> > #! Form Upload Object
> > class LoginForm (forms.Form):
> >  user     = forms.CharField(widget = forms.TextInput)
> >  password = forms.CharField(widget = forms.PasswordInput)
>
> > def index(request):
> >  if request.method == 'POST':
> >    form = LoginForm(request.POST)
> >    if form.is_valid():
> >      # FIXME: Check if file is good.
> >      #handle_uploaded_torrent(request.FILES['file'])
> >      username = request.POST['user']
> >      password = request.POST['password']
> >      user = authenticate(username=username, password=password)
> >      if user is not None:
> >        login(request, user)
>
> >      return HttpResponseRedirect('/')
> >  else:
> >    form = LoginForm()
>
> >  t = loader.get_template('template/index.html')
> >  c = RequestContext(request, {
> >      'login_form': form,
> >  })
> >  return HttpResponse(t.render(c))
>
> > Thanks for reponses,
> > Regards,
>
> --
> Olivier Détour
> Sent from Reserved, ***
-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.




Re: permalinks from cron job

2010-01-18 Thread Andy McKay

You can set a prefix here:

http://code.djangoproject.com/browser/django/trunk/django/core/urlresolvers.py#L364
--
  Andy McKay, @clearwind
  http://clearwind.ca/djangoski

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