Re: Unit test failing with 302 instead of 200, using Django's TestCase class

2009-08-04 Thread Paulo Almeida
Hi Alex,

When I do that I get a 404 instead of a 302. I also tried changing urls.py
to have a trailing slash but that also gives me a 404. Byt the way, one of
the variables I get in response.context is:

{'request_path': u'/myflow/experiment/1/'}

Thanks for the reply,
Paulo
On Tue, Aug 4, 2009 at 5:31 PM, Alex Gaynor  wrote:

>
> On Tue, Aug 4, 2009 at 11:26 AM, palmeida
> wrote:
> >
> > Hi,
> >
> > I'm running a test that fails when using Django's TestCase class, but
> > not when running TestCase from unittest. This is my test class:
> >
> > class LoggedInUser(TestCase):
> >fixtures = ['myflow']
> >def setUp(self):
> >self.client = Client()
> >try:
> >User.objects.create_user('user', 'm...@nowhere.com', 'user')
> >except IntegrityError:
> >pass
> >self.client.login(username='user', password='user')
> >
> >def test_experiment_view(self):
> >response = self.client.get('/myflow/experiment/1')
> >print response.context
> >self.failUnlessEqual(response.status_code, 200)
> >
> > It fails with:
> >
> > AssertionError: 302 != 200
> >
> > when using Django's TestCase class, but everything is fine when using
> > unittest. Also, when it fails everything in response seems fine except
> > for response.context (and response.content, of course).
> > response.context gets lots of variables, like MEDIA_URL, LANGUAGES and
> > others. I have no idea where that is coming from.
> >
> > This is the relevant line from urls.py:
> >
> > (r'^experiment/(?P\d+)$',
> > 'bioinformatics.myflow.views.view_experiment'),
> >
> > And this is the view:
> >
> > def view_experiment(request, experiment_id):
> >contact = request.user.id
> ># Filtering on contact and pk to ensure users can only see their
> > own data
> >exp = get_object_or_404(Experiment.objects.filter
> > (exp_contact=contact),
> >pk=experiment_id)
> >
> >list = generate_list()
> >
> >files = exp.fcs_set.exclude(name__startswith='myflow_meta')
> >num_files = len(files)
> >files = files.order_by('btim')
> >fcs_list = paginate(files,'fcs_per_page',request)
> ># Create variable to include (or not) subset column in fcs file
> > list
> >if len(subsets) > 1:
> >subset_header = True
> >else:
> >subset_header = False
> >return render_to_response('myflow/view_experiment.html',
> >  {'experiment': exp,
> >   'subsets': subsets,
> >   'parameters': list,
> >   'num_files': num_files,
> >   'fcs_list': fcs_list,
> >   'subset_header': subset_header
> >  }
> > )
> >
> > Thanks for any help. I'm not sure what I can do next to find out what
> > is going on.
> > Paulo Almeida
> >
> > >
> >
>
> It looks like you have teh APPEND_SLASH setting set to True (the
> default), so Django adds a / to the end of that URL.  Try righting the
> test to that URL with a trailing slash and see if it works.
>
> Alex
>
> --
> "I disapprove of what you say, but I will defend to the death your
> right to say it." -- Voltaire
> "The people's good is the highest law." -- Cicero
> "Code can always be simpler than you think, but never as simple as you
> want" -- Me
>
> >
>

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



Re: Unit test failing with 302 instead of 200, using Django's TestCase class

2009-08-04 Thread Paulo Almeida
Hi Karen,

You're right, I had some unnecessary lines that I used only for unittest. I
commented them out now. Printing response['location'] gives me this:

http://testserver/myflow/experiment/1/

You're also right that there is no Redirect in my view, so I don't know
where that is coming from. I guess I'll have to figure it out, because it
seems to be the key to the problem.

Thanks for the reply,
Paulo Almeida

On Tue, Aug 4, 2009 at 6:18 PM, Karen Tracey  wrote:

> On Tue, Aug 4, 2009 at 12:26 PM, palmeida wrote:
>
>>
>> Hi,
>>
>> I'm running a test that fails when using Django's TestCase class, but
>> not when running TestCase from unittest. This is my test class:
>>
>
>> class LoggedInUser(TestCase):
>>fixtures = ['myflow']
>
>
> Note fixtures will not be loaded when you run this as a unittest.TestCase.
>
>
>>
>>def setUp(self):
>>self.client = Client()
>>try:
>>User.objects.create_user('user', 'm...@nowhere.com', 'user')
>>except IntegrityError:
>>pass
>>self.client.login(username='user', password='user')
>>
>
> Is there a reason, other than to allow this to run as a unittest.TestCase,
> why are you setting client yourself in setUp()?  That's done for you by
> Django's TestCase.  If you are going to be using fixtures and the test
> Client, this really should be a django.test.TestCase.  I am not sure that
> going down the road of seeing if you can't get it to run as a
> unittest.TestCase by manually doing in the test things that
> django.test.TestCase also does is the best way of debugging whatever issue
> the test is having when running as a django.test.TestCase.  I would back up
> and take out anything you have added that allows this to run as a
> unittest.TestCase and start over with trying to debug the real issue
> directly.
>
>
>>
>>def test_experiment_view(self):
>>response = self.client.get('/myflow/experiment/1')
>>print response.context
>>self.failUnlessEqual(response.status_code, 200)
>>
>> It fails with:
>>
>> AssertionError: 302 != 200
>>
>> when using Django's TestCase class, but everything is fine when using
>> unittest.
>
>
> 302 is a redirect.  It would be useful to know where it's trying to
> redirect to.  For that, you could put a:
>
> print response['location']
>
> into the test.
>
>
>> Also, when it fails everything in response seems fine except
>> for response.context (and response.content, of course).
>> response.context gets lots of variables, like MEDIA_URL, LANGUAGES and
>> others. I have no idea where that is coming from.
>>
>
> Since your view below, from a quick scan, doesn't ever return a redirect
> your GET is apparently being routed to some other view entirely.  I'd guess
> that view is including all of this other stuff in its context.
>
>
>>
>> This is the relevant line from urls.py:
>>
>> (r'^experiment/(?P\d+)$',
>> 'bioinformatics.myflow.views.view_experiment'),
>>
>
> I cannot recreate what you are seeing based on just this information.  I
> suspect there is more to your urls.py, or something, that is coming into
> play.  Finding out where you are getting redirected to would be a first step
> in figuring out what is going wrong.
>
> Karen
>
>
>> And this is the view:
>>
>> def view_experiment(request, experiment_id):
>>contact = request.user.id
>># Filtering on contact and pk to ensure users can only see their
>> own data
>>exp = get_object_or_404(Experiment.objects.filter
>> (exp_contact=contact),
>>pk=experiment_id)
>>
>>list = generate_list()
>>
>>files = exp.fcs_set.exclude(name__startswith='myflow_meta')
>>num_files = len(files)
>>files = files.order_by('btim')
>>fcs_list = paginate(files,'fcs_per_page',request)
>># Create variable to include (or not) subset column in fcs file
>> list
>>if len(subsets) > 1:
>>subset_header = True
>>else:
>>subset_header = False
>>return render_to_response('myflow/view_experiment.html',
>>  {'experiment': exp,
>>   'subsets': subsets,
>>   'parameters': list,
>>   'num_files': num_files,
>>   'fcs_list': fcs_list,
>>   'subset_header': subset_header
>>  }
>> )
>>
>> Thanks for any help. I'm not sure what I can do next to find out what
>> is going on.
>> Paulo Almeida
>>
>>
> >
>

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



Re: Unit test failing with 302 instead of 200, using Django's TestCase class

2009-08-04 Thread Paulo Almeida
Hi,

The myflow part comes from the parent urls.py, which includes myflow/urls.py
when matching ^myflow (sorry, didn't think of that). I did try to comment
out the CommonMiddleware line, in settings.py, and the error persisted, but
maybe I should try adding APPEND_SLASH = False. I will then look at
response['location'] with and without APPEND_SLASH to see if that is doing
anything.

Thanks again,
Paulo

On Tue, Aug 4, 2009 at 6:45 PM, Karen Tracey  wrote:

> On Tue, Aug 4, 2009 at 1:33 PM, Paulo Almeida  > wrote:
>
>> Hi Karen,
>>
>> You're right, I had some unnecessary lines that I used only for unittest.
>> I commented them out now. Printing response['location'] gives me this:
>>
>> http://testserver/myflow/experiment/1/
>>
>> You're also right that there is no Redirect in my view, so I don't know
>> where that is coming from. I guess I'll have to figure it out, because it
>> seems to be the key to the problem.
>>
>
> So it does appear to be APPEND_SLASH that is causing the redirect, since
> the only difference between that and what you requested is the added slash
> on the end.  Which implies the version without the added slash is not
> matching the url pattern you cited:
>
>  (r'^experiment/(?P\d+)$',
> 'bioinformatics.myflow.views.view_experiment'),
>
> even though that pattern doesn't require a trailing slash.  That pattern,
> though, also has no 'myflow' component.  Where is that coming from?  There
> seems to be more to your url configuration than you have made clear here.
>
> Karen
>
> >
>

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



Re: Login screen is always shown, i dont like it :/

2009-08-04 Thread Paulo Almeida
Hi,

If you redirect users to your login screen in views that require login (for
instance, using the login_required decorator), you don't have to give out
your /accounts/login URL to users. Of course they can still go there if they
want, but there's no reason why they should. Your login can redirect to your
start page and the 'next' variable will take care of redirecting to the
original  page, if any, so that situation you don't like would never arise.

That said, I don't know if it's possible to do what you asked without
writing your own view.

- Paulo

On Tue, Aug 4, 2009 at 7:41 PM, MiratCanBayrak wrote:

>
> hi, i am using django.contrib.auth.views.login view  at /account/login
> url, to show login screen ( as explained here :
>
> http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.views.login
> )
>
> But, when user already logged in, form is not showing any error.
> Displaying a login form to already logged user is not giving
> professional sense i think. Can i change that behaviour or should i re-
> write login view myself?
> >
>

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



Re: model upload_to

2009-08-04 Thread Paulo Almeida
For what it's worth, if all you want to do is change the upload folder, you
can also do it by overriding the form's __init__.

- Paulo

On Tue, Aug 4, 2009 at 9:28 PM, Stefan Hjelm wrote:

>
> ok don't know what typo I made yesterday but it works now, maybe
> backslash in path. Thanks.
>
> for you who want to know how:
>
> def get_path(instance, filename):
>return instance._folder
>
> My model:
> class File(models.Model):
>type = models.CharField(max_length=10)
> the_file = models.FileField(upload_to=get_path)
> def __unicode__(self):
>return self.file.name
> def save(self, force_insert=False, force_update=False):
> self._folder = "new_folder/"+self.the_file.name
> super(File, self).save(force_insert, force_update)
>
>
> On 4 Aug, 22:02, Daniel Roseman  wrote:
> > On Aug 4, 8:53 pm, caliman  wrote:
> >
> >
> >
> > > Hi!
> >
> > > I'm trying to change upload_to dynamically.
> >
> > > My model:
> > > class File(models.Model):
> > > type = models.CharField(max_length=10)
> > > the_file = models.FileField(upload_to="folder")
> > > def __unicode__(self):
> > > return self.file.name
> >
> > > Tried following:
> >
> > > 1, overwrite upload_to in save:
> > > def save(self, force_insert=False, force_update=False):
> > > the_file.upload = "new_folder"
> > > super(File, self).save(force_insert, force_update)
> >
> > > This gives:
> > > Exception Type: NameError
> > > Exception Value:global name 'the_file' is not defined
> >
> > > Also tried with slug fields and setting a function and set value in
> > > runtime with:
> > > the_file = models.FileField(upload_to=get_path)
> >
> > > that works great if I just want to change the filename but I can't
> > > change folder.
> >
> > > So what am I doing wrong?
> >
> > > Stefan
> >
> > Alex has given you the answer regarding why you're getting that
> > exception, but even when you've fixed that it won't do what you want -
> > by then it's far too late, the file has already been uploaded.
> >
> > Your second approach is the right one, making upload_to a function -
> > as explained in the documentation:
> http://docs.djangoproject.com/en/dev/ref/models/fields/#filefield
> > But I don't understand why you say you can't change the folder there.
> > On the contrary, you can return a complete file path from your
> > upload_to function and that will be used as the file location. What
> > happens when you try?
> > --
> > DR
> >
>

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



Re: Unit test failing with 302 instead of 200, using Django's TestCase class

2009-08-05 Thread Paulo Almeida
Ok, so with APPEND_SLASH = False , I get a 404 (so no response['location'])
, but the response.context still has all the variables like MEDIA_URL,
LANGUAGES, LANGUAGE_BIDI, and not the ones it should have. It still has
also:

{'request_path': u'/myflow/experiment/1'}

I also tested another view, with URL:

response = self.client.get('/myflow/experiments')

This one works, and it has a list of experiments which links to the view
that isn't working. The link in response.content is:

a href="/myflow/experiment/1"

as it should be, and as it works outside tests. Also, from that
/myflow/experiments response.content I can tell that the fixtures are being
loaded, so it should not be a problem of experiment 1 not existing.

If you can suggest anything else I may try, please do.

Thank you,
- Paulo Almeida

On Tue, Aug 4, 2009 at 9:27 PM, Paulo Almeida
wrote:

> Hi,
>
> The myflow part comes from the parent urls.py, which includes
> myflow/urls.py when matching ^myflow (sorry, didn't think of that). I did
> try to comment out the CommonMiddleware line, in settings.py, and the error
> persisted, but maybe I should try adding APPEND_SLASH = False. I will then
> look at response['location'] with and without APPEND_SLASH to see if that is
> doing anything.
>
> Thanks again,
> Paulo
>
> On Tue, Aug 4, 2009 at 6:45 PM, Karen Tracey  wrote:
>
>> On Tue, Aug 4, 2009 at 1:33 PM, Paulo Almeida <
>> igcbioinformat...@gmail.com> wrote:
>>
>>> Hi Karen,
>>>
>>> You're right, I had some unnecessary lines that I used only for unittest.
>>> I commented them out now. Printing response['location'] gives me this:
>>>
>>> http://testserver/myflow/experiment/1/
>>>
>>> You're also right that there is no Redirect in my view, so I don't know
>>> where that is coming from. I guess I'll have to figure it out, because it
>>> seems to be the key to the problem.
>>>
>>
>> So it does appear to be APPEND_SLASH that is causing the redirect, since
>> the only difference between that and what you requested is the added slash
>> on the end.  Which implies the version without the added slash is not
>> matching the url pattern you cited:
>>
>>  (r'^experiment/(?P\d+)$',
>> 'bioinformatics.myflow.views.view_experiment'),
>>
>> even though that pattern doesn't require a trailing slash.  That pattern,
>> though, also has no 'myflow' component.  Where is that coming from?  There
>> seems to be more to your url configuration than you have made clear here.
>>
>> Karen
>>
>> >>
>>
>

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



Re: Unit test failing with 302 instead of 200, using Django's TestCase class

2009-08-05 Thread Paulo Almeida
Hi,

Thanks for the suggestion. I will do that now, but in the mean time I
realized the 404 is probably happening because of the get_object_or_404 in
the view, which means the experiment really isn't there, or at least not
with id 1. I confirmed that by replacing get_object_or_404 with:

exp = Experiment.objects.get(pk=experiment_id)

which returns:

DoesNotExist: Experiment matching query does not exist.

That is weird, because the id in the href comes from experiment.id, and
everything is working fine outside testing, but the response.context is also
weird, so I'll do what you suggest to try and narrow down the problem.

Thanks,
Paulo

On Wed, Aug 5, 2009 at 10:57 AM, Malcolm Tredinnick <
malc...@pointy-stick.com> wrote:

>
> On Wed, 2009-08-05 at 10:45 +0100, Paulo Almeida wrote:
> > Ok, so with APPEND_SLASH = False , I get a 404 (so no
> > response['location']) , but the response.context still has all the
> > variables like MEDIA_URL, LANGUAGES, LANGUAGE_BIDI, and not the ones
> > it should have. It still has also:
> >
> > {'request_path': u'/myflow/experiment/1'}
> >
> > I also tested another view, with URL:
> >
> > response = self.client.get('/myflow/experiments')
> >
> > This one works, and it has a list of experiments which links to the
> > view that isn't working. The link in response.content is:
> >
> > a href="/myflow/experiment/1"
> >
> > as it should be, and as it works outside tests. Also, from
> > that /myflow/experiments response.content I can tell that the fixtures
> > are being loaded, so it should not be a problem of experiment 1 not
> > existing.
> >
> > If you can suggest anything else I may try, please do.
>
> It's time to use the scientific method. Make the smallest self-contained
> example possible that exhibits the problem. A single test case in a file
> that uses Django.TestCase. A single view that does nothing but returns a
> constant string. A single URL pattern, etc. Remove everything that you
> possibly can. If you find you cannot remove a particular chunk of
> functionality (a URL pattern or a view or a template or whatever), then
> you know where to look for the problem.
>
> You have a lot of things in flight here all at once. Throw as many
> overboard as you and eliminate the moving parts. What's left is the
> problem you're trying to solve.
>
> Regards,
> Malcolm
>
>
> >
>

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



Re: Unit test failing with 302 instead of 200, using Django's TestCase class

2009-08-05 Thread Paulo Almeida
Mystery solved.

The fixtures were not being imported after all. My list_experiments view
imports files from a certain folder, and that was the experiment data being
listed. Then the database was rolled back before the view_experiment test
started, and naturally the experiment with id 1 was not there anymore. I
suppose that rollback is the difference that made the test work with
unittest.

Thanks for all the help,
Paulo

On Wed, Aug 5, 2009 at 11:11 AM, Paulo Almeida
wrote:

> Hi,
>
> Thanks for the suggestion. I will do that now, but in the mean time I
> realized the 404 is probably happening because of the get_object_or_404 in
> the view, which means the experiment really isn't there, or at least not
> with id 1. I confirmed that by replacing get_object_or_404 with:
>
> exp = Experiment.objects.get(pk=experiment_id)
>
> which returns:
>
> DoesNotExist: Experiment matching query does not exist.
>
> That is weird, because the id in the href comes from experiment.id, and
> everything is working fine outside testing, but the response.context is also
> weird, so I'll do what you suggest to try and narrow down the problem.
>
> Thanks,
> Paulo
>
>
> On Wed, Aug 5, 2009 at 10:57 AM, Malcolm Tredinnick <
> malc...@pointy-stick.com> wrote:
>
>>
>> On Wed, 2009-08-05 at 10:45 +0100, Paulo Almeida wrote:
>> > Ok, so with APPEND_SLASH = False , I get a 404 (so no
>> > response['location']) , but the response.context still has all the
>> > variables like MEDIA_URL, LANGUAGES, LANGUAGE_BIDI, and not the ones
>> > it should have. It still has also:
>> >
>> > {'request_path': u'/myflow/experiment/1'}
>> >
>> > I also tested another view, with URL:
>> >
>> > response = self.client.get('/myflow/experiments')
>> >
>> > This one works, and it has a list of experiments which links to the
>> > view that isn't working. The link in response.content is:
>> >
>> > a href="/myflow/experiment/1"
>> >
>> > as it should be, and as it works outside tests. Also, from
>> > that /myflow/experiments response.content I can tell that the fixtures
>> > are being loaded, so it should not be a problem of experiment 1 not
>> > existing.
>> >
>> > If you can suggest anything else I may try, please do.
>>
>> It's time to use the scientific method. Make the smallest self-contained
>> example possible that exhibits the problem. A single test case in a file
>> that uses Django.TestCase. A single view that does nothing but returns a
>> constant string. A single URL pattern, etc. Remove everything that you
>> possibly can. If you find you cannot remove a particular chunk of
>> functionality (a URL pattern or a view or a template or whatever), then
>> you know where to look for the problem.
>>
>> You have a lot of things in flight here all at once. Throw as many
>> overboard as you and eliminate the moving parts. What's left is the
>> problem you're trying to solve.
>>
>> Regards,
>> Malcolm
>>
>>
>> >>
>>
>

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



Re: default blank choice on form.Form select widget

2009-08-05 Thread Paulo Almeida
Did you see this ticket?

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

Maybe you can use the patch code to customize your field.

- Paulo

On Wed, Aug 5, 2009 at 8:01 PM, JHeasly  wrote:

>
> The doc page "Creating forms from models"
> (http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#topics-
> forms-modelforms
> )
> describes how
> "If the model field has choices set ... [snip] ... The choices will
> normally include the blank choice which is selected by default. ... "
>
> I have a form that's not associated with a database model (i.e.,
> form.Form) and I'm using the USStateSelect widget, but the blank
> choice isn't included in the STATE_CHOICE list. When the form loads,
> what I get is "Alabama" selected by default. I'd like to get the
> forms.ModelForm-style blank choice default selection behavior.
>
> I'm guessing some sort of super() def __init__ trickery is called for
> but am stumped so far ...
>
> Thanks,
> John
> >
>

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



Re: Select Table or Database based on User

2009-08-05 Thread Paulo Almeida
Yeah, the way I do that is have a foreign key with the user in the table
with private data and then filter by user when retrieving data in the view.

On Wed, Aug 5, 2009 at 10:11 PM, Maksymus007  wrote:

>
> >
> > Hi everyone,
> >
> > I'm sure this has come up in the past, but I sincerely can't find it
> > in any of the Django tutorials, documentation, or websites. I
> > apologize in advance if I missed something!
> >
> > I'm trying to develop a website where different users store their own
> > sets of contacts / articles / etc. If a user logs in, I only want them
> > to have access to their own articles or contacts. As such, I'm
> > thinking that storing each individual user's data in their own table
> > is the way to go.
> >
> > However, my question is: how do I actually have Django select the
> > proper table? The models and views stay the same, but I need to make
> > sure that, given a user name, Django selects the proper table(s).
> >
> > Is there a tutorial on this? A link? Any advice would be appreciated.
> >
> > Thanks,
> > Wojciech
>
> and why not to just store user_id column for each table?
> Tylko jak to django adminowi powiedzieć...
>
> >
>

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



Re: Application decoupling - project architecture question

2009-08-06 Thread Paulo Almeida
I'm far from being an expert, but maybe you can look at the django-tagging
code for inspiration:

http://code.google.com/p/django-tagging/

What they do is to provide a TagField in the tagging application, and then
you can use that field in the form of the application using tags. You can
probably do something similar with an AvatarField.

- Paulo

On Thu, Aug 6, 2009 at 4:07 PM, Andrin Riiet  wrote:

>
> Hi, I'd like to shed some light on the "the right way" to make
> applications in django by an example and a few questions.
>
> Let's say that I have a 'users' application (acting as "user profiles"
> on the built-in user authentication system) and I want to add an
> avatar image feature to it.
> I'd like to have the avatars in a separate application in case my next
> project doesn't require them (this is the right way to do things i
> guess?)
>
> Now I want to have the user to be able to upload an avatar image in
> the "edit profile" form. The default edit-profile form is defined in
> my 'users' application of course. I'd like to "add" the avatar feature
> (form field) to it somehow. - This is part 1 of the problem
>
> The 2nd part is in the form handling: the request object is going to
> contain form field values from 2 different applications, none of which
> should be responsible for processing the other's forms.
>
> Obviously the 'avatars' application is dependent on the 'users'
> application but the 'users' application should be oblivious of the
> avatars...
>
> How would I go about doing that?
>
> Andrin
>
> >
>

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



Re: Get current user outside a view / without an request object

2009-08-06 Thread Paulo Almeida
It doesn't have to be a callable, you can just do something like:

recipientUser = ShowValidContactList(currentUser=self.currentUser)

I never used that kwargs.pop function (I didn't know you could do that),
 but I have code like this:

class ExperimentForm(ModelForm):
""" Generate form to handle experiment information. """
def __init__(self, user, *args, **kwargs):
super(ExperimentForm, self).__init__(*args, **kwargs)
try:
preferences = Preferences.objects.get(user=user)

That last 'user' is just what came from the function call in the view.

- Paulo

2009/8/6 Julián C. Pérez 

>
> My real problem it that the field should looks like:
> ---
> recipientUser = ShowValidContactList(currentUser=_something_,
> label=u'Send to')
> ---
> and if I have a form's init method like...
> ---
> def __init__(self, *args, **kwargs):
>self.currentUser = kwargs.pop('currentUser', None)
>super(SendMessageForm, self).__init__(*args, **kwargs)
> ---
> it won't change the current user already defined in the field
>
> Now, I want to make something like...
> ---
> recipientUser = ShowValidContactList(currentUser=getCurrentUser,
> label=u'Send to')
> ---
> where 'getCurrentUser' is a callable function similar to:
> ---
> def get_image_path(instance, filename):
>return 'photos/%s/%s' % (instance.id, filename)
>
> class Photo(models.Model):
>image = models.ImageField(upload_to=get_image_path)
> ---
> how can I do that?
>
> On Aug 6, 9:58 am, Daniel Roseman  wrote:
> > On Aug 6, 3:34 pm, Julián C. Pérez  wrote:
> >
> >
> >
> > > Hi
> > > I tried doing that...
> > > But it does not work
> > > For example, if I do something like...
> > > ---
> > > class SendMessageForm(forms.Form):
> > > recipientUser = ShowValidContactList(label=u'Send to')
> > > messageSubject= forms.CharField(label=u'Subject')
> > > messageContent = forms.CharField
> > > (label=u'Content',widget=forms.Textarea())
> > > def __init__(self, currentUser):
> > > self.currentUser = currentUser
> > > super(SendMessageForm, self).__init__(*args, **kwargs)
> > > ---
> > > that init method in my custom form class won't change anything in the
> > > already defined ShowValidContactList field
> >
> > Because you are clobbering the existing parameters to __init__. You
> > should do it like this:
> >
> > def __init__(self, *args, **kwargs):
> > self.currentUser = kwargs.pop('currentUser', None)
> > super(SendMessageForm, self).__init__(*args, **kwargs)
> >
> > --
> > DR.
> >
>

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



Re: Get current user outside a view / without an request object

2009-08-06 Thread Paulo Almeida
But why don't you put:

recipientUser = ShowValidContactList(currentUser=self.user)

inside the __init__?

- Paulo

2009/8/6 Julián C. Pérez 

>
> Thanks for reply, Paulo
> But if I...
> ---
> class SendMessageForm(forms.Form):
>
>recipientUser = ShowValidContactList(currentUser=self.user,
> label=u'Send to')
>messageSubject= forms.CharField(label=u'Subject')
>messageContent = forms.CharField(label=u'Content',
> widget=forms.Textarea())
>
> def __init__(self, inputUser, *args, **kwargs):
>   self.user= inputUser
>super(SendMessageForm, self).__init__(*args, **kwargs)
> ---
> the 'recipientUser = ShowValidContactList(currentUser=self.user,
> label=u'Send to')' raises error because of that 'self.user' ('self'
> wouldn't be defined and be out of scope)
>
> On Aug 6, 11:09 am, Paulo Almeida  wrote:
> > It doesn't have to be a callable, you can just do something like:
> >
> > recipientUser = ShowValidContactList(currentUser=self.currentUser)
> >
> > I never used that kwargs.pop function (I didn't know you could do that),
> >  but I have code like this:
> >
> > class ExperimentForm(ModelForm):
> > """ Generate form to handle experiment information. """
> > def __init__(self, user, *args, **kwargs):
> > super(ExperimentForm, self).__init__(*args, **kwargs)
> > try:
> > preferences = Preferences.objects.get(user=user)
> >
> > That last 'user' is just what came from the function call in the view.
> >
> > - Paulo
> >
> > 2009/8/6 Julián C. Pérez 
> >
> >
> >
> > > My real problem it that the field should looks like:
> > > ---
> > > recipientUser = ShowValidContactList(currentUser=_something_,
> > > label=u'Send to')
> > > ---
> > > and if I have a form's init method like...
> > > ---
> > > def __init__(self, *args, **kwargs):
> > >self.currentUser = kwargs.pop('currentUser', None)
> > >super(SendMessageForm, self).__init__(*args, **kwargs)
> > > ---
> > > it won't change the current user already defined in the field
> >
> > > Now, I want to make something like...
> > > ---
> > > recipientUser = ShowValidContactList(currentUser=getCurrentUser,
> > > label=u'Send to')
> > > ---
> > > where 'getCurrentUser' is a callable function similar to:
> > > ---
> > > def get_image_path(instance, filename):
> > >return 'photos/%s/%s' % (instance.id, filename)
> >
> > > class Photo(models.Model):
> > >image = models.ImageField(upload_to=get_image_path)
> > > ---
> > > how can I do that?
> >
> > > On Aug 6, 9:58 am, Daniel Roseman  wrote:
> > > > On Aug 6, 3:34 pm, Julián C. Pérez  wrote:
> >
> > > > > Hi
> > > > > I tried doing that...
> > > > > But it does not work
> > > > > For example, if I do something like...
> > > > > ---
> > > > > class SendMessageForm(forms.Form):
> > > > > recipientUser = ShowValidContactList(label=u'Send to')
> > > > > messageSubject= forms.CharField(label=u'Subject')
> > > > > messageContent = forms.CharField
> > > > > (label=u'Content',widget=forms.Textarea())
> > > > > def __init__(self, currentUser):
> > > > > self.currentUser = currentUser
> > > > > super(SendMessageForm, self).__init__(*args,
> **kwargs)
> > > > > ---
> > > > > that init method in my custom form class won't change anything in
> the
> > > > > already defined ShowValidContactList field
> >
> > > > Because you are clobbering the existing parameters to __init__. You
> > > > should do it like this:
> >
> > > > def __init__(self, *args, **kwargs):
> > > > self.currentUser = kwargs.pop('currentUser', None)
> > > > super(SendMessageForm, self).__init__(*args, **kwargs)
> >
> > > > --
> > > > DR.
> >
>

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



Re: Django TimeField Model without seconds

2009-08-06 Thread Paulo Almeida
Hi,

Streamweaver wasn't suggesting assigning 00 to every time, just hiding what
you don't want to show using views or templates. For instance:

http://docs.djangoproject.com/en/dev/ref/templates/builtins/#time

- Paulo

On Thu, Aug 6, 2009 at 6:47 PM, Hellnar  wrote:

>
> Hello,
> I need this because it is a task specific requirement for my project
> (a television broadcast flow management which only consists of HH:MM
> format).I will let the user login via the admin panel and add these
> broadcast flows includint those times thus each addition with
> assigning HH:MM:00  would be royal pain :)
> Cheers
>
> On 6 Ağustos, 20:37, Streamweaver  wrote:
> > I'm not really sure you can but I'm also not clear why this is a
> > problem.  It would seem easy to just not use seconds and filter them
> > out in the template and views as needed.  Is this practical for your
> > needs or is there a specific benefit you're seeking by filtering out
> > seconds from the field?
> >
> > On Aug 6, 1:26 pm, Hellnar  wrote:
> >
> >
> >
> > > Greetings, I am trying to implement a TimeField model which only
> > > consists of HH:MM (ie 16:46) format, I know it is possible to format a
> > > regular Python time object but I am lost about how to manage this with
> > > Django.
> >
> > > Cheers
> >
>

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



Altering object order in formsets with can_order

2010-05-05 Thread Paulo Almeida
Hi,

I'm having a hard time grasping the concept of the can_order argument, when
creating formsets. Once objects are created and saved through the formset,
is it possible to reorder them? Where does the order information get stored?
I tried just adding can_order=True when creating the formset (it's an
inline_formset) and the order fields do show up on the form, but they don't
seem to have any effect. I'm just saving the formset. Should I use "formset.
ordered_forms" to sort them and then save each one individually?

I really need to be able to reorder after saving, because some of these
objects are being created outside forms and I want the users to reorder them
if they want to. If that is not possible with can_order, I think an easy way
to do it would be to have an extra variable in that model, storing the order
(in the form it would work just like the fields created by can_order). Does
that sound reasonable?

Thanks for any help,
Paulo Almeida

-- 
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 make readonly in change but editable in add?

2010-08-04 Thread Paulo Almeida
Actually, what he wanted was just to override a field, and not the whole
form, but he can do it with slight modifications of your code. He would
override the form class he wants to modify, instead of creating a generic
one, and instead of iterating all the fields he would just set the relevant
one(s) read only.

- Paulo

On Wed, Aug 4, 2010 at 4:03 AM, shmengie <1st...@gmail.com> wrote:

> I cobbled these two classes together which work very nicely for me,
> wish they could make into django.
> Drop these two classes into a util.py and import them instead of Form
> or ModelForm.  When you want your form readonly instantiate it with
> "form=MyForm(record, readonly=True)"
>
> class roForm(forms.Form):
>def __init__(self, *args, **kwargs):
>self.readonly = False
>if kwargs.has_key('readonly'):
>if kwargs['readonly']:
>self.readonly = True
>kwargs.pop('readonly')
>super(roForm, self).__init__(*args, **kwargs)
>if self.readonly:
>for key in self.fields.iterkeys():
>self.fields[key].widget.attrs['disabled'] = True
>
>
> class roModelForm(forms.ModelForm):
>def __init__(self, *args, **kwargs):
>self.readonly = False
>if kwargs.has_key('readonly'):
>if kwargs['readonly']:
>self.readonly = True
>kwargs.pop('readonly')
>super(roModelForm, self).__init__(*args, **kwargs)
>if self.readonly:
>for key in self.fields.iterkeys():
>self.fields[key].widget.attrs['disabled'] = True
>
>
> On Aug 3, 2:36 pm, snipinben  wrote:
> > I was wondering how to make a field readonly when you click on it or want
> to
> > change the record. and i have done that with the readonly_feilds method.
> but
> > that makes it to where you cant add information to that feild when you
> add a
> > new record. is there something i can use where you are not able to edit a
> > feild in the change view, but when you add new, you are able to edit the
> > field until you press save? thanks alot
> > --
> > View this message in context:
> http://old.nabble.com/how-to-make-readonly-in-change-but-editable-in-...
> > Sent from the django-users mailing list archive at Nabble.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: problem : create form

2010-08-04 Thread Paulo Almeida
Hi,

SQL is created for models, not for forms. Maybe you should try following the
tutorial first (it's near the top of the Django documentation page), and
then move to other documentation for the specifics.

- Paulo

On Wed, Aug 4, 2010 at 9:19 AM, Jagdeep Singh Malhi  wrote:

> i follow these documentation for create form
>
> http://docs.djangoproject.com/en/dev/topics/forms/
>
> i use command for create application
> #python manage.py startapp form
>
> after this a use this code in model.py file
>
> from django import forms
>
> class ContactForm(forms.Form):
>subject = forms.CharField(max_length=100)
>message = forms.CharField()
>sender = forms.EmailField()
>cc_myself = forms.BooleanField(required=False)
>
> but nothing can be show in when a run this command
> #python manage.py sql form.
>
> where is problem ?
>  please help.
>
> --
> 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: problem : create form

2010-08-04 Thread Paulo Almeida
If possible, the easiest way would be to create a form based on a model
(subclass ModelForm). When you save the form the values will be stores in
the appropriate database fields.

To answer your final question, the 4 part tutorial I mentioned covers that.

- Paulo

On Wed, Aug 4, 2010 at 10:09 AM, Jagdeep Singh Malhi <
singh.malh...@gmail.com> wrote:

>
>
>
>
> >
> > Why do you think you would get any SQL with that? You're creating a
> > form, not a model.
> ok
> I also want to store the value in database using form.
>
> Now what i can do?
> any tutorial of that?
>
> --
> 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: Saving formsets with multiple databases

2010-08-04 Thread Paulo Almeida
Sorry if this is obvious and you're looking for a more direct way, but If
it's only the formset save that fails, I would suggest:

instances = formset.save(commit=False)
for instance in instances:
instance.save(using=database)

I have never used multiple databases though, so I don't know if that works
or if there is a better method.

- Paulo

On Tue, Aug 3, 2010 at 11:05 PM, Melanie  wrote:

> I am developing a formset for an application which uses multiple
> databases.  On load of the formset, I am able to utilize:
>
> model.objects.using(database).get(id)
>
> to get an instance of the object from the active database.  However,
> when the formset is submitted, I generate a new formset from the data
> in request.POST:
>
> formset = SampleFormSet(request.POST)
>
> When attempting to save the formset to the database, I attempted to
> pass the "using" parameter in the save method:
>
> formset.save(using=database)
>
> and got the error:
>
> save() got an unexpected keyword argument 'using'
>
> which suggests to me that the save method on the formset does not
> support multiple databases.  Is there any known way to save a formset
> when using multiple databases?
>
> --
> 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: How to get the model name of an object in template?

2010-08-05 Thread Paulo Almeida
But _meta starts with an underscore, so you can't use it in the template,
right? I'm still using Django 1.0.2, so I don't know if that has changed
along the way.

- Paulo

On Thu, Aug 5, 2010 at 8:52 AM, Daniel Roseman wrote:

> On Aug 4, 7:27 pm, "David.D"  wrote:
> > I just wonder if there's some way requires writing nothing. Just like
> > an attribute.
> >
> > thanks.
>
> Yes, there is. Each model and model instance object has a _meta
> attribute, which contains information about the model -
> the .app_label, object_name and .verbose_name will probably be useful
> to you.
> --
> DR.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-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: Need help with my Form.save() method. Trouble with ForeignKey and ManyToMany Fields.

2010-08-05 Thread Paulo Almeida
Can you check the POST data and see if 'username' is there? You can do it
easily with Firefox's Firebug extension.

- Paulo

On Thu, Aug 5, 2010 at 6:24 AM, strayhand  wrote:

> So I'm rolling out my own registration form that should update the
> following models:
>
> - User (auth module)
> - UserProfile
>
> Everything seems to be coming together but I'm having a hard time with
> the save() method for the form. My UserProfile model has a couple of
> fields that refer to other models and I'm having difficulty setting
> them up properly. I keep getting an error telling me:
>
> Exception Type: IntegrityError at /registration/
> Exception Value: auth_user.username may not be NULL
>
> I know where the problems are:
>
> new_user =
> User.objects.create_user(username=self.cleaned_data['username'],
> email=self.cleaned_data['email'],
> password=self.cleaned_data['password1'])
>
> and I'm getting this similar error for defining the user profile on
> the line below.
>
> new_profile.user =
> User.objects.get(username__exact=self.cleaned_data['username'])
>
> I'm just not sure how else to write this stuff. I'm including my form,
> model and the exact error message that I'm getting below. Any insight
> that you have is greatly appreciated. Thank you.
>
> # registration.forms.py
>
> import re
> from django import forms
> from django.db import models
> from django.contrib.localflavor.us.forms import USPhoneNumberField
> from django.contrib.auth.models import User
> from ylbbq.areas.models import Area
> from ylbbq.profiles.models import UserProfile
>
> STATES = (
>('WA', 'Washington'),
>('AK', 'Alaska'),
>('AL', 'Alabama'),
>('AR', 'Arkansas'),
>('AZ', 'Arizona'),
>('CA', 'California'),
>('CO', 'Colorado'),
>('CT', 'Connecticut'),
>('DE', 'Delaware'),
>('FL', 'Florida'),
>('GA', 'Georgia'),
>('HI', 'Hawaii'),
>('IA', 'Iowa'),
>('ID', 'Idaho'),
>('IL', 'Illinois'),
>('IN', 'Indiana'),
>('KS', 'Kansas'),
>('KY', 'Kentucky'),
>('LA', 'Louisiana'),
>('MA', 'Massachusetts'),
>('MD', 'Maryland'),
>('ME', 'Maine'),
>('MI', 'Michigan'),
>('MN', 'Minnesota'),
>('MO', 'Missouri'),
>('MS', 'Mississippi'),
>('MT', 'Montana'),
>('NC', 'North Carolina'),
>('ND', 'North Dakota'),
>('NE', 'Nebraska'),
>('NH', 'New Hampshire'),
>('NJ', 'New Jersey'),
>('NM', 'New Mexico'),
>('NV', 'Nevada'),
>('NY', 'New York'),
>('OH', 'Ohio'),
>('OK', 'Oklahoma'),
>('OR', 'Oregon'),
>('PA', 'Pennsylvania'),
>('RI', 'Rhode Island'),
>('SC', 'South Carolina'),
>('SD', 'South Dakota'),
>('TN', 'Tennessee'),
>('TX', 'Texas'),
>('UT', 'Utah'),
>('VT', 'Vermont'),
>('VA', 'Virginia'),
>('WI', 'Wisconsin'),
>('WV', 'West Virginia'),
>('WY', 'Wyoming'),
>('AB', 'Alberta'),
>('BC', 'British Columbia'),
>('MB', 'Manitoba'),
>('NB', 'New Brunswick'),
>('NL', 'Newfoundland and Labrador'),
>('NS', 'Nova Scotia'),
>('NT', 'Northwest Territories'),
>('NU', 'Nunavut'),
>('ON', 'Ontario'),
>('PE', 'Prince Edward Island'),
>('QC', 'Quebec'),
>('SK', 'Saskatchewan'),
>('YT', 'Yukon'),
> )
>
> COUNTRIES = (
>('USA', 'United States'),
>('Canada', 'Canada')
> )
>
> POSTAL_CODE_PATTERN = re.compile(r'^\d{5}-\d{4}|\d{5}|[A-Z]\d[A-Z]
> \d[A-Z]\d$')
>
> class RegisterForm(forms.Form):
>username = forms.CharField(max_length=30, help_text='Create a user
> name for this Web site.')
>first_name = forms.CharField(max_length=30)
>last_name = forms.CharField(max_length=30)
>password1 = forms.CharField(max_length=60, label='Password',
> widget=forms.PasswordInput)
>password2 = forms.CharField(max_length=60, label='Password
> Confirmation', widget=forms.PasswordInput)
>email = forms.EmailField(help_text='Enter a valid e-mail address.')
>phone = USPhoneNumberField(max_length=12, help_text='Enter your
> phone
> number in the following format: 253-123-5678.')
>address = forms.CharField(max_length=70, help_text='Enter mailing
> address.')
>city = forms.CharField(max_length=50)
>state_province = forms.ChoiceField(choices=STATES, label='State or
> Province')
>country = forms.ChoiceField(choices=COUNTRIES)
>zip_code = forms.CharField(max_length=10, label='Mailing Code',
> help_text='Enter your zip code (US or Canadian).')
>birth_date = forms.DateField(help_text='Enter your birthdate in the
> following format: 1979-09-29 (-MM-DD).')
>areas = forms.ModelMultipleChoiceField(queryset=Area.objects.all(),
> label='Preferred Areas', help_text='Select the areas that you\'d like

Re: overriding model.save()

2010-08-05 Thread Paulo Almeida
I never tried this, but I think you could just delete the value from the
form.cleaned_data dictionary, if you don't want it:

if instance.my_field == some_value:
del form.cleaned_data['my_field']

This would be in the view, before saving, so you wouldn't need to override
anything.

- Paulo

On Wed, Aug 4, 2010 at 6:05 PM, Sells, Fred wrote:

> I would like to prevent saving a new value if the database contains a
> specific value.  This is on a per field, per record basis.
>
> If I override the save() method; is there a way to find the existing (in
> the DB) values and the new (to be stored) values?
>
> --
> 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: Interpolation and comparation between 2 dates: easy and difficult at the same time

2010-08-05 Thread Paulo Almeida
In the third case, I didn't understand why you didn't divide (his_to -
his_from) / (my_to - my_from). Bearing that in mind, this made sense in my
head, but analyze it carefully:

def match(mf,mt,hf,ht):
mydiff = diff_in_seconds(mf,mt)
if (mf >= hf and mt <= ht) or (mf < hf and mt > ht):
mydiff = diff_in_seconds(mf,mt)
hisdiff = diff_in_seconds(hf,ht)
return min(1, hisdiff / mydiff)
else:
case1 = max(0, diff_in_seconds(hf, mt))
case2 = max(0, diff_in_seconds(mf, ht))
diff = min(case1, case2)
return (diff / mydiff)

def diff_in_seconds(d1,d2):
timedelta = d2 - d1
return float(timedelta)

print match(0,100,40,90)


2010/8/5 Alexandre González 

> I've develope a "simple" function to calculate the difference between 2
> dates, and the time that they are interpolated.
>
> I need it to: I arrive to a site at a hour (my_from), I go out from the
> site at a hour (my_to). Some friend arrive at the site at a hour (his_from)
> and let it at a hour (his_to)
>
> If I stay in the site after he arrives and before he goes out, the
> "probability" of match is 1, if I let the site after he arrives, the
> probability of match is 0... You can see the samples in the documentation.
>
> I need to know if this is a good way to do, and if compare all the kinds of
> matching (I've found 6). This is the code:
>
> def time_match(self, my_from, my_to, his_from, his_to):
> """
> I've found 6 general kinds of time matching. It's better to
> explain it with graphics:
>
>   (my_from)--A--(my_to)
> -
>  (his_from)--B--(his_to)
> """
>
> #|-A-|   |-A-|
> #  or 
> #   |--B--||--B--|
> if my_to < his_from or his_to < my_from:
> return 0
>
> #  |--A--|
> # 
> #  |--B---|
> elif my_from >= his_from and my_to <= his_to:
> return 1
>
> #|-A---|
> # 
> #|-B-|
> elif my_from < his_from and my_to > his_to:
> my_diff_to_reuse = diff_in_seconds(my_from, my_to)
> diff = my_diff_to_reuse - self.diff_in_seconds(his_from,
> his_to)
>
> return (diff / my_diff_to_reuse)
>
> #   |---A---|
> # 
> #   |---B---|
> elif my_from <= his_from and my_to <= his_to:
> diff = self.diff_in_seconds(his_from, my_to)
>
> return (diff / self.diff_in_seconds(my_from, my_to))
>
> # |---A---|
> # 
> #|---B---|
> elif my_from >= his_from and my_to >= his_to:
> diff  = self.diff_in_seconds(my_from, his_to)
>
> return (diff / self.diff_in_seconds(my_from, my_to))
>
> # If I'm here I have a problem
> return 0
>
>
> def diff_in_seconds(date1, date2):
> # Initial from: http://www.bytemycode.com/snippets/snippet/304/
> timedelta = date2 - date1
> diff = timedelta.days*24*3600 + timedelta.seconds
>
> return abs(float(diff))
>
> Thanks!
> --
> Please, don't send me files with extensions: .doc, .docx, .xls, .xlsx, .ppt
> and/or .pptx
> http://mirblu.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: Finding Duration: Creating a context variable from two DateField model fields

2010-08-05 Thread Paulo Almeida
A function or property in the model would do nicely. You can check this page
for more information:

http://www.b-list.org/weblog/2006/aug/18/django-tips-using-properties-models-and-managers/

-
Paulo

On Fri, Aug 6, 2010 at 12:24 AM, flowpoke  wrote:

> I have a simple model that includes two DateField fields. I have
> everything passing to the template, as I would like but i'd like to
> add one more variable, duration. I want {{ duration }} to be that of
> the delta between the two DateField fields, in years. It's simple
> arithmetic but im not sure where to implement this logic. This is on a
> per object basis but it seems to me that I'd want to apply this logic
> at the model level, since it's a constant (i'll reference it anytime i
> call on this object(s)).
>
> Any pointers on where to begin? I suppose I can break this down in a
> view but im not sure how to unpack the QuertSet, add the new context
> variable to each object and then wrap it back up into a QuerySet. If
> thats even the right way to do 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.
>
>

-- 
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: Interpolation and comparation between 2 dates: easy and difficult at the same time

2010-08-07 Thread Paulo Almeida
As I understand it, in the case of partial overlap you just divide the
overlapping portion of B by A, so the direct division here would have the
same effect. I don't understand why is that division assuming A = 2B.

In any case, your function is heavier on the ifs, but mine has to do more
with each option, so I'm not sure which would perform better. And I think
yours is more readable, although less concise.

- Paulo

2010/8/6 Alexandre González 

> M the third case coul be this, for example:
>
> |---A-| |--A|
> ---
>
>|B|   |-B|
>
> If I directly apply (his_diff/my_diff) I think that I'm assuming that A =
> 2B and it isn't the case... I need to get my range and her range and deleter
> the union between them with a substraction.
>
> range(A) - range(B)  17000s - 13000s
>  for example: --- =
> 0.2352 = 23%
>range(A)  17000s
>
> What do you think about? Perhaps I'm mading mistakes and can't understand
> your reply. Anyway, thanks for reply :)
>
> Bye!
> Álex González
>
>
> On Fri, Aug 6, 2010 at 02:09, Paulo Almeida 
> wrote:
>
>> In the third case, I didn't understand why you didn't divide (his_to -
>> his_from) / (my_to - my_from). Bearing that in mind, this made sense in my
>> head, but analyze it carefully:
>>
>>  def match(mf,mt,hf,ht):
>> mydiff = diff_in_seconds(mf,mt)
>> if (mf >= hf and mt <= ht) or (mf < hf and mt > ht):
>> mydiff = diff_in_seconds(mf,mt)
>> hisdiff = diff_in_seconds(hf,ht)
>> return min(1, hisdiff / mydiff)
>> else:
>> case1 = max(0, diff_in_seconds(hf, mt))
>> case2 = max(0, diff_in_seconds(mf, ht))
>> diff = min(case1, case2)
>> return (diff / mydiff)
>>
>> def diff_in_seconds(d1,d2):
>> timedelta = d2 - d1
>> return float(timedelta)
>>
>> print match(0,100,40,90)
>>
>>
>> 2010/8/5 Alexandre González 
>>
>>>  I've develope a "simple" function to calculate the difference between 2
>>> dates, and the time that they are interpolated.
>>>
>>> I need it to: I arrive to a site at a hour (my_from), I go out from the
>>> site at a hour (my_to). Some friend arrive at the site at a hour (his_from)
>>> and let it at a hour (his_to)
>>>
>>> If I stay in the site after he arrives and before he goes out, the
>>> "probability" of match is 1, if I let the site after he arrives, the
>>> probability of match is 0... You can see the samples in the documentation.
>>>
>>> I need to know if this is a good way to do, and if compare all the kinds
>>> of matching (I've found 6). This is the code:
>>>
>>> def time_match(self, my_from, my_to, his_from, his_to):
>>> """
>>> I've found 6 general kinds of time matching. It's better to
>>> explain it with graphics:
>>>
>>>   (my_from)--A--(my_to)
>>> -
>>>  (his_from)--B--(his_to)
>>> """
>>>
>>> #|-A-|   |-A-|
>>> #  or 
>>> #   |--B--||--B--|
>>> if my_to < his_from or his_to < my_from:
>>> return 0
>>>
>>> #  |--A--|
>>> # 
>>> #  |--B---|
>>> elif my_from >= his_from and my_to <= his_to:
>>> return 1
>>>
>>> #|-A---|
>>> # 
>>> #|-B-|
>>> elif my_from < his_from and my_to > his_to:
>>> my_diff_to_reuse = diff_in_seconds(my_from, my_to)
>>> diff = my_diff_to_reuse - self.diff_in_seconds(his_from,
>>> his_to)
>>>
>>> return (diff / my_diff_to_reuse)
>>>
>>> #   |---A---|
>>> # 
>>> #   |---B---|
>>> elif my_from <= his_from and my_to <= his_to:
>>> diff = self.diff_in_seconds(his_from, my_to)
>>

Re: Newbie Mistake Question

2010-08-07 Thread Paulo Almeida
Is your project named mysite? (That is, is the parent directory of 'polls'
named 'mysite'?)

-Paulo

On Sat, Aug 7, 2010 at 3:20 AM, HawaiiMikeD wrote:

> Hi all,
>
> Just starting out with the tutorial 1 and ran into what I hope is a
> minor mistake.  I've got my site setup to a Postgresql database and
> was running through the tutorial without any problems until I got to
> the step where you create your models and then activate them.
>
> The models you start off creating in the tutorial are the poll and
> Choice ones.  Then after creating those you edit your site root
> settings.py file and and the polls app at the bottom of the app list
> like so:
>
> INSTALLED_APPS = (
>'django.contrib.auth',
>'django.contrib.contenttypes',
>'django.contrib.sessions',
>'django.contrib.sites',
>'mysite.polls'
> )
>
> Then you run the command:
>
> python manage.py sql polls
>
> But I end up getting an error message that says:
>
> "Error:  No module named  mysite.polls.
>
> In an earlier step i created the app with the command:
>
> python manage.py startapp polls
>
> and it ran correctly and created the referenced files listed in the
> tutorial.
>
> I noticed that before adding the 'mysite.polls' line the previous line
> had a comma on the end so I've tried editing the settings.py file to
> have it with a command on the end of the 'mysite.polls' line and
> without but still get the same error.
>
> Is this a syntax error or has something changed since the tutorial was
> written that has it missing a step?
>
> --
> 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: confusing query involving time ranges

2010-08-12 Thread Paulo Almeida
Can you sequentially add the states for each foo? I'm thinking of something
like:

states = []
for foo in foos:
foo_state = State.objects.filter(foo=foo, first_dt__lte=dt,
last_dt__gte=dt)
if foo_state:
states.append(foo_state)
else:
states = State.objects.filter(foo=foo, last_dt__lte=dt):
states.append(state.latest)

Of course you would have to define latest in the model Meta.

- Paulo

On Thu, Aug 12, 2010 at 8:26 PM, Alec Shaner  wrote:

> Hopefully some django sql guru will give you a better answer, but I'll take
> a stab at it.
>
> What you describe does sound pretty tricky. Is this something that has to
> be done in a single query statement? If you just need to build a list of
> objects you could do it in steps, e.g.:
>
> # Get all State objects that span the requested dt
> q1 = State.objects.filter(first_dt__lte=dt, last_dt__gte=dt)
>
> # Get all State objects where foo is not already in q1, but have a last_dt
> prior to requested dt
> q1_foo = q1.values_list('foo')
> q2 =
> State.objects.exclude(foo__in=q1_foo).filter(last_dt__lt=dt).order_by('-last_dt')
>
> But q2 would not have unique foo entries, so some additional logic would
> need to be applied to get the first occurrence of each distinct foo value in
> q2.
>
> Probably not the best solution, but maybe it could give you some hints to
> get started.
>
>
> On Thu, Aug 12, 2010 at 12:51 PM, Emily Rodgers <
> emily.kate.rodg...@gmail.com> wrote:
>
>> Hi,
>>
>> I am a bit stuck on this and can't seem to figure out what to do.
>>
>> I have a model that (stripped down for this question) looks a bit like
>> this:
>>
>> class State(models.Model):
>>first_dt = models.DateTimeField(null=True)
>>last_dt = models.DateTimeField(null=True)
>>foo = models.CharField(FooModel)
>>bar = models.ForeignKey(BarModel, null=True)
>>meh = models.ForeignKey(MehModel, null=True)
>>
>> This is modeling / logging state of various things in time (more
>> specifically a mapping of foo to various other bits of data). The data
>> is coming from multiple sources, and what information those sources
>> provide varies a lot, but all of them provide foo and a date plus some
>> other information.
>>
>> What I want to do, is given a point in time, return all the 'states'
>> that span that point in time. This seems trivial except for one thing
>> - a state for a particular 'foo' may still be persisting after the
>> last_dt until the next 'state' for that 'foo' starts. This means that
>> if there are no other 'states' between the point in time and the start
>> of the next state for a given foo, I want to return that state.
>>
>> I have built a query that kindof explains what I want to do (but
>> obviously isn't possible in its current form):
>>
>> dt = '2010-08-12 15:00:00'
>>
>> lookups = State.objects.filter(
>>Q(
>>Q(first_dt__lte=dt) & Q(last_dt__gte=dt) |
>>Q(first_dt__lte=dt) &
>>
>> Q(last_dt=State.objects.filter(foo=F('foo')).filter(first_dt__lte=dt).latest('last_dt'))
>>)
>> )
>>
>> I know this doesn't work, but I think it illustrates what I am trying
>> to do better than words do.
>>
>> Does anyone have any advice? Should I be using annotate or something
>> to show what the last_dt for each foo is? I might be being really
>> stupid and completely missing something but I have been trying to
>> figure this out for too long!
>>
>> Cheers,
>> Emily
>>
>> --
>> 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.
>

-- 
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: confusing query involving time ranges

2010-08-13 Thread Paulo Almeida
I see. What about Alec Shaner's suggestion? If you replace 'order_by' with
'latest' it will be similar to my suggestion with just two queries.

- Paulo

On Fri, Aug 13, 2010 at 8:28 AM, Emily Rodgers  wrote:

> On Aug 12, 10:00 pm, Paulo Almeida 
> wrote:
> > Can you sequentially add the states for each foo? I'm thinking of
> something
> > like:
> >
> > states = []
> > for foo in foos:
> > foo_state = State.objects.filter(foo=foo, first_dt__lte=dt,
> > last_dt__gte=dt)
> > if foo_state:
> > states.append(foo_state)
> > else:
> > states = State.objects.filter(foo=foo, last_dt__lte=dt):
> > states.append(state.latest)
> >
> > Of course you would have to define latest in the model Meta.
> >
> > - Paulo
>
> The thing is, there could be say 3000 distinct foos in the table. It
> would take ages to return the results if I did this. I was hoping to
> do it in one query. Might have to revert to SQL if I can't do it using
> the django ORM.
>
> >
> > On Thu, Aug 12, 2010 at 8:26 PM, Alec Shaner 
> wrote:
> > > Hopefully some django sql guru will give you a better answer, but I'll
> take
> > > a stab at it.
> >
> > > What you describe does sound pretty tricky. Is this something that has
> to
> > > be done in a single query statement? If you just need to build a list
> of
> > > objects you could do it in steps, e.g.:
> >
> > > # Get all State objects that span the requested dt
> > > q1 = State.objects.filter(first_dt__lte=dt, last_dt__gte=dt)
> >
> > > # Get all State objects where foo is not already in q1, but have a
> last_dt
> > > prior to requested dt
> > > q1_foo = q1.values_list('foo')
> > > q2 =
> > >
> State.objects.exclude(foo__in=q1_foo).filter(last_dt__lt=dt).order_by('-last_dt')
> >
> > > But q2 would not have unique foo entries, so some additional logic
> would
> > > need to be applied to get the first occurrence of each distinct foo
> value in
> > > q2.
> >
> > > Probably not the best solution, but maybe it could give you some hints
> to
> > > get started.
> >
> > > On Thu, Aug 12, 2010 at 12:51 PM, Emily Rodgers <
> > > emily.kate.rodg...@gmail.com> wrote:
> >
> > >> Hi,
> >
> > >> I am a bit stuck on this and can't seem to figure out what to do.
> >
> > >> I have a model that (stripped down for this question) looks a bit like
> > >> this:
> >
> > >> class State(models.Model):
> > >>first_dt = models.DateTimeField(null=True)
> > >>last_dt = models.DateTimeField(null=True)
> > >>foo = models.CharField(FooModel)
> > >>bar = models.ForeignKey(BarModel, null=True)
> > >>meh = models.ForeignKey(MehModel, null=True)
> >
> > >> This is modeling / logging state of various things in time (more
> > >> specifically a mapping of foo to various other bits of data). The data
> > >> is coming from multiple sources, and what information those sources
> > >> provide varies a lot, but all of them provide foo and a date plus some
> > >> other information.
> >
> > >> What I want to do, is given a point in time, return all the 'states'
> > >> that span that point in time. This seems trivial except for one thing
> > >> - a state for a particular 'foo' may still be persisting after the
> > >> last_dt until the next 'state' for that 'foo' starts. This means that
> > >> if there are no other 'states' between the point in time and the start
> > >> of the next state for a given foo, I want to return that state.
> >
> > >> I have built a query that kindof explains what I want to do (but
> > >> obviously isn't possible in its current form):
> >
> > >> dt = '2010-08-12 15:00:00'
> >
> > >> lookups = State.objects.filter(
> > >>Q(
> > >>Q(first_dt__lte=dt) & Q(last_dt__gte=dt) |
> > >>Q(first_dt__lte=dt) &
> >
> > >>
> Q(last_dt=State.objects.filter(foo=F('foo')).filter(first_dt__lte=dt).latest('last_dt'))
> > >>)
> > >> )
> >
> > >> I know this doesn't work, but I think it illustrates what I am trying
> > >> to do better than words do.
> >
> > >> Does a

ManagementForm validation error in unit test

2010-03-18 Thread Paulo Almeida
Hi,

I have a function in tests.py that tests the editing of a form, and it
worked fine until I added an inline formset to the form. Now it fails with
this error:

ValidationError: [u'ManagementForm data is missing or has been tampered
with']

I added these lines to the test function:

new['image_form-TOTAL_FORMS'] = 1
new['image_form-INITIAL_FORMS'] = 0
new['table_form-TOTAL_FORMS'] = 1
new['table_form-INITIAL_FORMS'] = 0

new is the dictionary that is being passed to the post function:

response = self.client.post('/myflow/experiment/2/edit', new)

image_form and table_form are the 'prefix' I am passing when creating
image_formset and table_formset.

I chose those values for TOTAL_FORMS and INITIAL_FORMS because they are in
the request POST when I do it on the web, using Firefox. I also tried
strings instead of ints (with u'1' , etc).

Is it obvious what is wrong from just this information? If not, what other
information would be useful to debug this?

The simplest test I have done on the command line was this:

>> ImageFormset = inlineformset_factory(Experiment, Image, ImageForm,
extra=1)

>> data = {
'image_form-INITIAL_FORMS': u'0',
'image_form-TOTAL_FORMS': u'1'
}

>> formset = ImageFormset(data,prefix='image_form')

This works, but if I leave out the prefix in the last command then the same
ValidationError is raised.

Thank you for any help,
Paulo

-- 
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 e-mail with large files from form attached

2010-03-18 Thread Paulo Almeida
I can't help you with the technical part, but a couple of suggestions:

* Sum the size of the images and send two (or more) e-mails if it exceeds a
threshold
* Forget attachments and just zip the images and make them accessible in an
URL that is e-mailed to the site admin

- Paulo

On Wed, Mar 17, 2010 at 8:57 AM, tezro  wrote:

> Hello everyone. I need some help or advice.
>
> I've got a form with 20 ImageFields - such a form for sending photos
> to the site admin as a request for a new user. Well, Django certainly
> handles and uploads the, that's OK. But when it comes to sending all
> the files as an attachment - I got stuck.
>
> Here's a simple example of how I tried to do that:
> 
> from django.core.mail import EmailMessage
>
> email = EmailMessage()
> for (k, v) in request.FILES.items():
>email.attach(v.name, v.read())
> 
>
> Small files are read nicely. But when someone "clever" fills out all
> the form files (all the twenty) with images each one at least 10 Mb -
> Django consumes so much memory... so I'm not in knowledge to handle
> that.
>
> Please, guide me how to handle big files from a form and send them
> without memory leaks. Thanks ahead.
>
> --
> 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: ManagementForm validation error in unit test

2010-03-18 Thread Paulo Almeida
Hi Rajeesh,

Thanks for the reply, but I still didn't manage to make it work. On the one
hand, I couldn't find the get_default_prefix function (I'm using Django
1.02, which may explain that), but on the other hand, I do provide a prefix
argument when I generate the formset, in my view:

image_formset = ImageFormset(request.POST,
 request.FILES,
 instance=exp,
 prefix='image_form'
 )

I do that both for POST and non-POST creation of formsets.

Also, I searched google for get_default_prefix and it seems that all it does
is return the string 'form' (or at least it did, I don't know how recent is
the documentation I found).

Thanks,
Paulo

On Thu, Mar 18, 2010 at 5:18 PM, raj  wrote:

>
> > This works, but if I leave out the prefix in the last command then the
> same
> > ValidationError is raised.
>
> You've almost worked it out yourself. This error usually occurs when
> the given prefix does not match with what django expected. When you
> don't provide any prefix argument on generating formset, django
> expects the default prefix. Try ImageFormset.get_default_prefix() to
> get that value and use it in your data dictionary
>
>
>
> Rajeesh.
>
> --
> 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: ManagementForm validation error in unit test

2010-03-18 Thread Paulo Almeida
Mystery solved. Thanks for your help, and sorry for the waste of time, but
the problem was that I missed a previous form submission in the same test
function, that was used just to test validation. I hadn't added the
ManagementForm variables there, so that was the problem.

Best regards,
Paulo

On Thu, Mar 18, 2010 at 5:18 PM, raj  wrote:

>
> > This works, but if I leave out the prefix in the last command then the
> same
> > ValidationError is raised.
>
> You've almost worked it out yourself. This error usually occurs when
> the given prefix does not match with what django expected. When you
> don't provide any prefix argument on generating formset, django
> expects the default prefix. Try ImageFormset.get_default_prefix() to
> get that value and use it in your data dictionary
>
>
>
> Rajeesh.
>
> --
> 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: models.TextField --> \r\n in DB

2010-03-18 Thread Paulo Almeida
Hi Thomas,

Django's normalize_newlines function should do the trick. You can import it
from django.utils.text. See this page for an example:

http://www.palewire.com/posts/2009/09/01/django-recipe-remove-newlines-text-block/

Best,
Paulo

On Thu, Mar 18, 2010 at 4:27 PM, Thomas Guettler  wrote:
>
> Hi,
>
> I just discovered that I have a random mix auf rows
> some with \r\n and some with only \n.
>
> I guess it depends on using a windows or linux browser
> to access the app.
>
> I use models.TextField (with django 1.0).
>
> Has someone seen this, too?
>
> What do you do?
>
>  Thomas
>
> --
> Thomas Guettler, http://www.thomas-guettler.de/
> E-Mail: guettli (*) thomas-guettler + de
>
> --
> 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: Send e-mail with large files from form attached

2010-03-19 Thread Paulo Almeida
Hi,

My suggestion to zip the files was to provide a single download link with
all the files.

- Paulo

On Fri, Mar 19, 2010 at 1:43 PM, tezro  wrote:

> Thanks for reply. I tried both variants before the post :) Nothing
> suited me and the customer.
>
> When a-mailng files are uploaded to RAM anyway, zipping files just
> don't really help on binary data. I chosed to save them to a web-
> visible location.
>
> On Mar 18, 7:59 pm, Paulo Almeida  wrote:
> > I can't help you with the technical part, but a couple of suggestions:
> >
> > * Sum the size of the images and send two (or more) e-mails if it exceeds
> a
> > threshold
> > * Forget attachments and just zip the images and make them accessible in
> an
> > URL that is e-mailed to the site admin
> >
> > - Paulo
> >
> > On Wed, Mar 17, 2010 at 8:57 AM, tezro  wrote:
> > > Hello everyone. I need some help or advice.
> >
> > > I've got a form with 20 ImageFields - such a form for sending photos
> > > to the site admin as a request for a new user. Well, Django certainly
> > > handles and uploads the, that's OK. But when it comes to sending all
> > > the files as an attachment - I got stuck.
> >
> > > Here's a simple example of how I tried to do that:
> > > 
> > > from django.core.mail import EmailMessage
> >
> > > email = EmailMessage()
> > > for (k, v) in request.FILES.items():
> > >email.attach(v.name, v.read())
> > > 
> >
> > > Small files are read nicely. But when someone "clever" fills out all
> > > the form files (all the twenty) with images each one at least 10 Mb -
> > > Django consumes so much memory... so I'm not in knowledge to handle
> > > that.
> >
> > > Please, guide me how to handle big files from a form and send them
> > > without memory leaks. Thanks ahead.
> >
> > > --
> > > 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.
>
>

-- 
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: UnicodeDecodeError Solution?

2010-03-19 Thread Paulo Almeida
I had a similar problem and I used two approaches. First I used Django's
smart_str:

from django.utils.encoding import smart_str
text = smart_str(text)

Then I had the same problem with fields using the csv module and I used
these functions that I found on the web:

def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
# csv.py doesn't do Unicode; encode temporarily as UTF-8:
csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
dialect=dialect, **kwargs)
for row in csv_reader:
# decode UTF-8 back to Unicode, cell by cell:
yield [unicode(cell, 'utf-8') for cell in row]

def utf_8_encoder(unicode_csv_data):
for line in unicode_csv_data:
yield line.encode('utf-8')

I'm not sure I fully understand your problem, so maybe they won't suit you,
but possibly doing something with the encode function or smart_str will help
you.

Good luck,
Paulo


On Fri, Mar 19, 2010 at 2:44 PM, Steven L Smith  wrote:

> We have a freelance designer that, for various political reasons, we need
> to
> give access to our templates directory. The problem is, he frequently
> pastes
> from Microsoft Word, and other sources, and then we're seeing HTTP 500
> errors
> because the output contains unescaped UTF-8 / unicode characters.
>
> For example, "UnicodeDecodeError: 'utf8' codec can't decode byte 0x94 in
> position 30076: unexpected code byte".
>
> Is there a way to prevent these errors, other than revisiting the level of
> access we give folks like this? Some kind of middleware that would filter
> these characters out? Some kind of way to replace weird characters with a
> bright pink blinking exclamation point? Something else?
>
> Thanks!
>
> Steven L Smith
> Web Developer
> Nazareth College of Rochester
> http://www.naz.edu/
>
> --
> 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: login() and 'unicode' object is not callable error

2010-03-19 Thread Paulo Almeida
I think what's happening is you are assigning a string to the 'login'
variable:

login = request.POST['login']

So when you get to:

login(request, user)

login is the text and not the function.

HTH,
Paulo

On Fri, Mar 19, 2010 at 3:15 PM, Martin Tiršel  wrote:

> Hello,
>
> can somebody help me with this error? I am a Django beginner but I don't
> see any errors in the code:
>
> Environment:
>
> Request Method: POST
> Request URL: http://127.0.0.1:8000/administration/
> Django Version: 1.1.1
> Python Version: 2.6.4
> Installed Applications:
> ['django.contrib.auth',
>  'django.contrib.contenttypes',
>  'django.contrib.sessions',
>  'django.contrib.sites',
>  'ibase.administration']
> Installed Middleware:
> ('django.middleware.common.CommonMiddleware',
>  'django.contrib.sessions.middleware.SessionMiddleware',
>  'django.contrib.auth.middleware.AuthenticationMiddleware')
>
>
> Traceback:
> File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in
> get_response
>  92. response = callback(request, *callback_args,
> **callback_kwargs)
> File
> "/home/bruce/Projects/ibasedev/trunk/ibase/../ibase/administration/views.py"
> in login
>  23. login(request, user)
>
> Exception Type: TypeError at /administration/
> Exception Value: 'unicode' object is not callable
>
>
>
>
> Code:
>
> # -*- coding utf-8 -*-
>
> from django.contrib.auth import authenticate, login
> from django.shortcuts import render_to_response
> from ibase.administration.forms import LoginForm
>
> def login(request):
>def error_handler(error):
>form = LoginForm()
>return render_to_response('pages/login.html', {
>'error' : error,
>'form' : form,
>})
>
>if request.method == 'POST':
>form = LoginForm(request.POST)
>if form.is_valid():
>login = request.POST['login']
>password = request.POST['password']
>user = authenticate(username=login, password=password)
>if user is not None:
>if user.is_active:
>login(request, user)
>return render_to_response('pages/logged.html', {
>'login' : login,
>})
>else:
>return error_handler(u'Account disabled')
>else:
>return error_handler(u'Invalid login or password')
>else:
>return error_handler(u'Invalid input')
>else:
>form = LoginForm()
>return render_to_response('pages/login.html', {
>'form' : form,
>})
>
>
> Thanks,
> Martin
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

-- 
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 e-mail with large files from form attached

2010-03-19 Thread Paulo Almeida
Oh, I missed that part. I'm not an expert, so you may want to investigate
alternatives, but with the shutil module you can copy files or entire
directories:

http://docs.python.org/library/shutil.html

Look for copy and copytree.

Best,
Paulo

On Fri, Mar 19, 2010 at 2:32 PM, tezro  wrote:

> Oh. I get it, sorry. Any suggestions on my next question about
> file.read() would be thankful.
>
> On Mar 19, 5:20 pm, Paulo Almeida  wrote:
> > Hi,
> >
> > My suggestion to zip the files was to provide a single download link with
> > all the files.
> >
> > - Paulo
> >
> > On Fri, Mar 19, 2010 at 1:43 PM, tezro  wrote:
> > > Thanks for reply. I tried both variants before the post :) Nothing
> > > suited me and the customer.
> >
> > > When a-mailng files are uploaded to RAM anyway, zipping files just
> > > don't really help on binary data. I chosed to save them to a web-
> > > visible location.
> >
> > > On Mar 18, 7:59 pm, Paulo Almeida  wrote:
> > > > I can't help you with the technical part, but a couple of
> suggestions:
> >
> > > > * Sum the size of the images and send two (or more) e-mails if it
> exceeds
> > > a
> > > > threshold
> > > > * Forget attachments and just zip the images and make them accessible
> in
> > > an
> > > > URL that is e-mailed to the site admin
> >
> > > > - Paulo
> >
> > > > On Wed, Mar 17, 2010 at 8:57 AM, tezro  wrote:
> > > > > Hello everyone. I need some help or advice.
> >
> > > > > I've got a form with 20 ImageFields - such a form for sending
> photos
> > > > > to the site admin as a request for a new user. Well, Django
> certainly
> > > > > handles and uploads the, that's OK. But when it comes to sending
> all
> > > > > the files as an attachment - I got stuck.
> >
> > > > > Here's a simple example of how I tried to do that:
> > > > > 
> > > > > from django.core.mail import EmailMessage
> >
> > > > > email = EmailMessage()
> > > > > for (k, v) in request.FILES.items():
> > > > >email.attach(v.name, v.read())
> > > > > 
> >
> > > > > Small files are read nicely. But when someone "clever" fills out
> all
> > > > > the form files (all the twenty) with images each one at least 10 Mb
> -
> > > > > Django consumes so much memory... so I'm not in knowledge to handle
> > > > > that.
> >
> > > > > Please, guide me how to handle big files from a form and send them
> > > > > without memory leaks. Thanks ahead.
> >
> > > > > --
> > > > > You received this message because you are subscribed to the Google
> > > Groups
> > > > > "Django users" group.
> > > > > To post to this group, send email to django-users@googlegroups.com
> .
> > > > > To unsubscribe from this group, send email to
> > > > > django-users+unsubscr...@googlegroups.com
> 
> >
> > > 
> 
> >
> >
> > > > > .
> > > > > For more options, visit this group at
> > > > >http://groups.google.com/group/django-users?hl=en.
> >
> > > --
> > > 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.
>
>

-- 
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: Two user account types and login_required decorator

2010-03-19 Thread Paulo Almeida
Hi,

This ticket is pretty old, but if it turns out you need a new decorator you
can try the patch:

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

Regards,
Paulo

On Fri, Mar 19, 2010 at 9:57 PM, Martin Tiršel  wrote:

> Hello,
>
> I am programming an application where one part is customer database with
> accounts and settings for internal access, the second part is customer
> access with different interface and functionality. For internal access I am
> using django.contrib.auth and login_required decorator. This decorator
> redirect the user to settings.LOGIN_URL in case the user is not logged in
> and tries to access login required part. But I can not use this decorator
> for customer part because I need another settings.LOGIN_URL and afaik
> settings.py are project specific, not application specific (administration
> and customer parts are applications). Is there a way how to use Django's
> features or I have to create custom decorator to check if the user is logged
> in? Or I have to create separate project for internal and customer access
> sharing the same database?
>
> Thanks,
> Martin
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Re: Forms with read only fields

2010-03-20 Thread Paulo Almeida
You can also do that by overriding the form's  __init__ :

http://stackoverflow.com/questions/324477/in-a-django-form-how-to-make-a-field-readonly-or-disabled-so-that-it-cannot-be

You can pass the user to init and disable fields depending on that
parameter.

- Paulo

On Sat, Mar 20, 2010 at 4:02 PM, Thierry Chich wrote:

> Le samedi 20 mars 2010 16:05:20, Peter Reimer a écrit :
> > Hi Folks,
> >
> > I'm looking for a way to get the following done:
> > Depending on different things (user, groups, rights, etc.) I want to
> > show a form with fields that can either be changed or not. For
> > example, a form with two fields for name and hobby, an admin can
> > change both fields, a normal user can only change hobby.
> >
> > One solution that came to mind: Create a form for both groups and
> > exclude in the user's form the fields, he mustn't change. But I want
> > two things:
> > 1. Show the read-only values at the position where the admin sees the
> > writeable fields because a user can be an admin (at another place) and
> > it would be confusing to have different positions here and there.
> > 2. Have something reusable: E.g. form = MySpecialForm(deactivated =
> > [name]).
> >
> > I checked to docu and googled around, not only some minutes... and
> > found nothing.
> > Has somebody here a hint for me? I don't want a solution, I'm thankful
> > for some little hints.
> >
>
> I am not sure, but for me, you should have something like
> 
> If you want it appear only when you give rights, you could put a condition
> in
> the template
> 
>
> I don't know if it answer to your question or if you think at something
> more
> complex.
>
> Thierry
> > Thanks & have a nice weekend
> > Peter
> >
>
> --
> 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: Strings in page in []

2010-03-21 Thread Paulo Almeida
It's not a matter of stripping the brackets, the problem is you are getting
a list.

I suppose you would get the result you want with the following code:

{% if flash %}
   {% for key, value in flash.items %}
   
   {% for v in value %}
   {{ v }}
   {% endfor%}
   
   {% endfor %}
{% endif %}

 Is 'value' always just one value? If it is, you can try:

request.flash['key'] = 'value'

  instead of:

request.flash.add('key', 'one')


I haven't used flash, so I don't know if that works, but the documentations
says it works like a plain dict, so I would expect it to not return a list.

- Paulo

On Sun, Mar 21, 2010 at 11:26 PM, serek  wrote:

> Hi
>
> I use djangoflash http://djangoflash.destaquenet.com/
> and after add message to flash
>request.flash.add('message', 'test')
> and redirect
> i receive
> ['test']
> instead
> test
>
> code which display this:
>
> {% if flash %}
>{% for key, value in flash.items %}
>
>{{ value }}
>
>{% endfor %}
> {% endif %}
>
> Does someone know how strip [' and '] in 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.
>
>

-- 
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: installation question

2010-03-21 Thread Paulo Almeida
You should run that on the Terminal (not Python, just regular shell), in the
folder where you downloaded Django-1.1.1.tar.gz .

- Paulo

On Sun, Mar 21, 2010 at 10:39 PM, yangyang  wrote:

> I'm trying to download Django on my Mac OS X 10.4.11. I have download
> Python 2.6.4. And then the online Tutorial says this:
>
> tar xzvf Django-1.1.1.tar.gz
> cd Django-1.1.1
> sudo python setup.py install
>
> I wonder where should I run this? By Python Shell or what? Sorry if
> this seems to be a stupid question but I'm a programming beginner...
>
> 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.
>
>

-- 
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: Tagging - Extending by adding a rating?

2010-03-21 Thread Paulo Almeida
A possible solution would be to create a Many To Many relationship between
articles and companies, with an intermediary model holding the ratings:

http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships

- Paulo

On Mon, Mar 22, 2010 at 2:41 AM, Victor Hooi  wrote:

> heya,
>
> I have a small Django app we're writing to hold reviews of newspaper
> articles.
>
> With each article, there's an arbitrary number of companies or
> keywords associated with those articles. And for each of those
> companies/keywords, there's either a rating (out of 10), or possibly
> no rating (i.e. Null).
>
> I was thinking of using django-tagging to add tags to each article,
> but I'm not sure how on the best way to extend it to add in the
> ratings. Should I somehow add a field to the tag model? I have a
> feeling that's a very broken/improper way of doing things. Or is there
> a better way of achieving what I want to do within Django?
>
>
> Cheers,
> Victor
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

-- 
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: Tagging - Extending by adding a rating?

2010-03-22 Thread Paulo Almeida
I know django-tagging has the Tag model and the TaggedItem model. I wonder
if it would be possible to create the Many to Many relationship between your
Articles and this TaggedItem model, through a Ratings intermediary table. I
have no idea if that would work (and keep all the django-tagging features),
but that's something you can look into.

Best,
Paulo

On Mon, Mar 22, 2010 at 3:21 AM, Victor Hooi  wrote:

> Paolo,
>
> Thanks for the quick reply =).
>
> I did think of that, just using a M2M, however, that means I lose all
> of the inherent features of django-tagging. For our case, that would
> probably be things like helpers to do auto-complete for tags,
> automatically parsing form inputs with commas into tags, tag-clouds
> etc.
>
> Is there any way to somehow leverage off django-tagging? Or am I
> better of starting from scratch on this?
>
> Cheers,
> Victor
>
> On Mar 22, 1:54 pm, Paulo Almeida  wrote:
> > A possible solution would be to create a Many To Many relationship
> between
> > articles and companies, with an intermediary model holding the ratings:
> >
> > http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-o...
> >
> > - Paulo
> >
> >
> >
> > On Mon, Mar 22, 2010 at 2:41 AM, Victor Hooi 
> wrote:
> > > heya,
> >
> > > I have a small Django app we're writing to hold reviews of newspaper
> > > articles.
> >
> > > With each article, there's an arbitrary number of companies or
> > > keywords associated with those articles. And for each of those
> > > companies/keywords, there's either a rating (out of 10), or possibly
> > > no rating (i.e. Null).
> >
> > > I was thinking of using django-tagging to add tags to each article,
> > > but I'm not sure how on the best way to extend it to add in the
> > > ratings. Should I somehow add a field to the tag model? I have a
> > > feeling that's a very broken/improper way of doing things. Or is there
> > > a better way of achieving what I want to do within Django?
> >
> > > Cheers,
> > > Victor
> >
> > > --
> > > You received this message because you are subscribed to the Google
> Groups
> > > "Django users" group.
> > > To post to this group, send email to django-us...@googlegroups.com.
> > > To unsubscribe from this group, send email to
> > > django-users+unsubscr...@googlegroups.com
> 
> >
> > > .
> > > For more options, visit this group at
> > >http://groups.google.com/group/django-users?hl=en.
>
> --
> 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: Event more complicated forms / templates

2010-03-22 Thread Paulo Almeida
You could use inline formsets (have CustomerContactAnswer be a formset of
CustomerContactQuestion) and then render the Answer forms as a table in the
template.

- Paulo

On Mon, Mar 22, 2010 at 1:31 PM, ALJ  wrote:

> Is there any to have a table type form will variable rows and columns?
>
> I have events. For each event there might be several appointment days.
> And a set of questions to measure how many people the rep had contact
> with.
>
> My expected form output would be something like:
>
> Question,  Day1, Day2,
> Day3
> How many people did you see?   20, 30, 40
> How many bought stuff? 2,   1,   4
> How many samples did you give away?   15, 17, 20
>
> ... which they could fill in and submit.
>
> Has anyone else done anything like this?
>
> (Again, I think I might have bitten off more than I can chew here!)
>
> ALJ
>
>
> ..
> models.py
>
> class Appointment(models.Model):
>event = models.ForeignKey(Event)
>date = models.DateField("Date")
>time_start = models.TimeField("Start Time")
>time_end = models.TimeField("End Time")
>
>class Meta:
>ordering = ['date','time_start']
>
> class CustomerContactQuestion(models.Model):
>description = models.CharField("Question",max_length=200)
>order = models.IntegerField("Presentation Order", null=True,
> blank=True)
>
>class Meta:
>ordering = ['order','description']
>
> class CustomerContactAnswer(models.Model):
>event= models.ForeignKey(Event)
>customer_contact_question =
> models.ForeignKey(CustomerContactQuestion)
>appointment = models.ForeignKey(Appointment)
>amount = models.IntegerField()
>
>
> --
> 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: Remove session on browser close

2010-03-22 Thread Paulo Almeida
Maybe I'm missing something obvious, but can't you pass the user to the
template and use:

{% if user.is_authenticated %}

instead of:

{% if form.thanks %}

It doesn't solve the problem of logging out, but you don't have to handle
the session manually.

- Paulo

On Mon, Mar 22, 2010 at 9:40 PM, grimmus  wrote:

> Basically all i want to do is the following :
>
> Have a newsletter signup form. When the user signs up successfully the
> area where the form was has a thanks message instead of the form.
>
> The form or thanks message is displayed on every page of the site, so
> I thought using a session would be the best way handle whether to show
> the form or the thanks message.
>
> Here is my form
>
> 
>
>{% if form.errors %}
>Please enter a valid email address.
>{% endif %}
>{% if form.thanks %}
>Thanks for signing up
>{% endif %}
>{% if form.alreadyexists %}
>The email address already exists
>{% endif %}
>{% if not form.thanks %}
>   value="Email
> address" onfocus="this.select()" />
>   value="Go"/>
>{% endif %}
>
>  
>
> And my view
>
> if request.POST:
>form = SignUp(request.POST)
>
>if form.is_valid():
>
>email = request.POST.get('email', '')
>
>try:
>entry = MailingList.objects.get(email=email)
>
>form.alreadyexists = True
>
>except (KeyError, MailingList.DoesNotExist):
>
>entry = MailingList()
>entry.email = email
>entry.date_added = datetime.now()
>entry.save()
>
>request.session['signed_up'] = True
>form.thanks = True
>
>return HttpResponseRedirect(request.get_full_path())
>
>else:
>print form.errors
>
>else:
>
>form = SignUp()
>
>t = loader.get_template('home/page.html')
>c = RequestContext(request,{
>'form':form,
>})
>
>if request.session.get('signed_up', True):
>form.thanks = True
>
>return HttpResponse(t.render(c))
>
>
> Any help is greatly appreciated.
>
> On Mar 22, 3:13 pm, Bill Freeman  wrote:
> > And if the user disables javascript, or kills the browser without
> > normal exit, or loses
> > his connection, or pulls the ethernet cable, or has a power failure?
> >
> > On Mon, Mar 22, 2010 at 10:06 AM, Wiiboy  wrote:
> > > Couldn't you use Javascript for this? For example, on the
> > > onbeforeunload event, delete the sessionid cookie?
> >
> > > --
> > > 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.
>
>

-- 
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: Negate querysets

2010-03-23 Thread Paulo Almeida
Is there some way you can keep track of the queryset? I understand it's
dynamic, and maybe complex, for you to be looking for this kind of solution,
but if it were possible to have a variable or dictionary keeping track of
what you add to the queryset, it might be possible to use it to build the
inverse.

- Paulo

On Tue, Mar 23, 2010 at 1:23 PM, Vinicius Mendes | meiocodigo.com <
vbmen...@gmail.com> wrote:

> Ok. The code proposed by Tim Shaffer works and gives only one query.
> But it makes use of subselects, what is heavy for the database. Take a
> look at the generated SQL:
>
> 'SELECT `auth_user`.`id`, `auth_user`.`username`,
> `auth_user`.`first_name`, `auth_user`.`last_name`,
> `auth_user`.`email`, `auth_user`.`password`, `auth_user`.`is_staff`,
> `auth_user`.`is_active`, `auth_user`.`is_superuser`,
> `auth_user`.`last_login`, `auth_user`.`date_joined` FROM `auth_user`
> WHERE NOT (`auth_user`.`id` IN (SELECT U0.`id` FROM `auth_user` U0
> WHERE U0.`first_name` = vinicius )) LIMIT 21'
>
> I was thinking of something like:
>
> 'SELECT `auth_user`.`id`, `auth_user`.`username`,
> `auth_user`.`first_name`, `auth_user`.`last_name`,
> `auth_user`.`email`, `auth_user`.`password`, `auth_user`.`is_staff`,
> `auth_user`.`is_active`, `auth_user`.`is_superuser`,
> `auth_user`.`last_login`, `auth_user`.`date_joined` FROM `auth_user`
> WHERE NOT `auth_user`.`first_name` = vinicius  LIMIT 21'
>
> Why hit the database if I can do this with boolean login? Why not
> negate the filter condition instead of doing a subselect?
>
> On Mar 22, 7:15 pm, Tim Shaffer  wrote:
> > It depends. This will only run one query, when negated_queryset is
> > used.
> >
> > queryset = User.objects.filter(first_name='vinicius')
> > negated_queryset = User.objects.exclude(id__in=queryset.values("id"))
> >
> > Since the first queryset is not evaluated until it's used in the
> > negated_queryset (as a subquery).
> >
> > On Mar 22, 5:55 pm, Matt Schinckel  wrote:
> >
> >
> >
> > > On Mar 23, 6:17 am, Phlip  wrote:
> >
> > > > > Just create another queryset that excludes everything in your first
> > > > > queryset:
> >
> > > > > negated_queryset =
> User.objects.exclude(id__in=queryset.values("id"))
> >
> > > > QuerySets are already so easy to plug-n-play... Ain't there a way to
> > > > do it without whacking the database twice?
> >
> > > Are you sure it hits the db twice? I seem to recall a similar case
> > > where I thought I was, but since the queryset evaluation is lazy, the
> > > ORM potentially has the ability to make this into a single query.
> >
> > > (I can't recall if when I did this sort of thing I was using
> > > SQLAlchemy, but I _think_ it was pure django).
> >
> > > Matt.
>
> --
> 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: Can't perform chmod on django-admin.py

2010-03-23 Thread Paulo Almeida
You should run the command as an administrator, as mentioned. In any case,
if you type something like:

python /usr/bin/django-admin.py startproject project_name

it should work (where /usr/bin/ is the path to the django executable).

- Paulo

On Tue, Mar 23, 2010 at 10:05 PM, irishsteve  wrote:

> Hi
>
> I've caused myself some problems by updating python then trying to
> change back.
>
> I'm nearly back up and running now, except I'm getting permission
> denied errors when I try to run django-admin.py commands. For example:
>
> $ django-admin.py syncdb
> -bash: /usr/bin/django-admin.py: Permission denied
>
> So, I tried this:
> $ chmod +x django-admin.py
> chmod: Unable to change file mode on django-admin.py: Operation not
> permitted
>
> I'm pretty sure the symbolic link is created correctly. Has anyone any
> ideas? I'm reasonably new to OSX so I'm struggling a bit.
>
> Many thanks,
> Steve
>
> --
> 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: More PYTHONPATH issues

2010-03-23 Thread Paulo Almeida
Just to clarify: if you run a python shell in
/Library/Python/2.6/site-packages you can import django, but if you run
anywhere else you can't?

It seems weird that you can't cd into django's directory.

- Paulo

On Tue, Mar 23, 2010 at 9:13 PM, Riley  wrote:

> Hey all,
>
> I've done some extensive searching around this site, but no one's
> advice seems to apply/fix the problem :(
>
> Basically, I have python 2.6 and 2.5 installed on my mac (snow
> leopard).  I installed django from a tarball, using 'sudo python
> setup.py install'.  I'm pretty sure that this uses python2.6 b/c when
> I run the command python -V it tells me 2.6.1.
>
> I can 'import django' from a python shell inside the directory where
> django is installed, but not anywhere else.  When I print sys.path, I
> see that /Library/Python/2.6/site-packages is listed as part of the
> path, and when I go to that directory to check I see both a
> Django**.egg file and a django directory.  (Interestingly enough,
> however, I am unable to 'cd' into this directory, even with sudo).
>
> It seems as though the error is simply in python's path, but I can't
> find it anywhere.
>
> Thanks in advance,
> Riley
>
> --
> 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: Overriding admin Media class

2010-03-23 Thread Paulo Almeida
I don't have a working sample (never did this), but you may be looking for
something like this:

class Media:
   js = get_path()

And in the class where you keep use_editor:

def get_path(self)
if self.use_editor:
return path1
else:
return path2

This is just an idea, you'd probably have to tweak the details.

- Paulo

On Tue, Mar 23, 2010 at 9:36 PM, Scot Hacker  wrote:

> Given an admin media class that sets up a rich text editor, like:
>
> class TutorialAdmin(admin.ModelAdmin):
>
>fields...
>
>class Media:
>js = ['/paths/...',]
>
> I would like the ability to selectively override js. I've added a
> "use_editor" boolean to the Tutorial model. The question is, how can I
> detect whether the current instance has that bool set? I'd like to end
> up with something like:
>
>class Media:
>if self.use_editor:
>js = ['/paths',]
>else:
>js = ''
>
> But can't find a way to make this work. Anyone have a working sample?
> 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.
>
>

-- 
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: More PYTHONPATH issues

2010-03-24 Thread Paulo Almeida
Ok, that makes more sense. You probably can't import django from anywhere
else because the django folder cannot be read. Try going to
/Library/Python/2.6/site-packages and type 'ls -l' to see the permissions. I
presume you don't have e(x)ecute permission in the django folder. These
commands might do the trick:

cd /Library/Python/2.6/site-packages
sudo chmod 0755 django

Now you should be able to cd into django and maybe import it from anywhere.

I'm not sure the chmod command has the same syntax in OS X, but what you
need to do is have execute permission in all the directories of the django
folder and read permission in all the files within (if it's a symlink those
permissions are set in the target folder, but it seems those are alright).

- Paulo

On Wed, Mar 24, 2010 at 1:18 AM, Riley  wrote:

> No when I run the shell in the directory where django lives I can
> import.  I untared django into a sub-directory of the desktop and
> installed it there because I'm just starting and I feel like when I
> figure it out I'm going to want to start from scratch.
>
> Ya it is really weird, it just silently fails and leaves me in the
> current directory even with sudo
>
> On Mar 23, 7:53 pm, Paulo Almeida  wrote:
> > Just to clarify: if you run a python shell in
> > /Library/Python/2.6/site-packages you can import django, but if you run
> > anywhere else you can't?
> >
> > It seems weird that you can't cd into django's directory.
> >
> > - Paulo
> >
> > On Tue, Mar 23, 2010 at 9:13 PM, Riley  wrote:
> > > Hey all,
> >
> > > I've done some extensive searching around this site, but no one's
> > > advice seems to apply/fix the problem :(
> >
> > > Basically, I have python 2.6 and 2.5 installed on my mac (snow
> > > leopard).  I installed django from a tarball, using 'sudo python
> > > setup.py install'.  I'm pretty sure that this uses python2.6 b/c when
> > > I run the command python -V it tells me 2.6.1.
> >
> > > I can 'import django' from a python shell inside the directory where
> > > django is installed, but not anywhere else.  When I print sys.path, I
> > > see that /Library/Python/2.6/site-packages is listed as part of the
> > > path, and when I go to that directory to check I see both a
> > > Django**.egg file and a django directory.  (Interestingly enough,
> > > however, I am unable to 'cd' into this directory, even with sudo).
> >
> > > It seems as though the error is simply in python's path, but I can't
> > > find it anywhere.
> >
> > > Thanks in advance,
> > > Riley
> >
> > > --
> > > 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.
>
>

-- 
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: Templates: Looping, ifs and defaults

2010-03-24 Thread Paulo Almeida
I don't understand why is it obvious that an 'else' won't work. If a single
{% else %} is not what you want, you can nest {% if %} clauses. But if you
are doing this it can also mean that you should move this logic to the view
and just pass the final table to the template.

- Paulo

On Wed, Mar 24, 2010 at 12:20 PM, ALJ  wrote:

> I have a template that shows a matrix table of form text input boxes.
> When the form is new, then it should be just empty text boxes. If data
> already exists, then the form gets repopulated with data.
>
> What I am looking for it this:
>
> PRODUCTS | DAY1 | DAY2 | DAY3
> POLO | Empty text box | 3 |  3
> PASSAT | 1 | 0 | 0
> SCIROCCO | Empty text box | Empty text box |  1
>
> What I get is this:
>
> PRODUCTS | DAY1 | DAY2 | DAY3
> POLO | No box | 3 |  3
> PASSAT | 1 | 0 | 0
> PASSAT | No box | No box |  1
>
> My template is:
>
> 
> 
>{{ rate.cost_item.name }}
>{% for appointment in appointments %}
>
>{% for sale in sales %}
>{% if sale.appointment.id == appointment.id and
> rate.cost_item.id == sale.cost_rate.cost_item.id %}
> style="text-align:center" />
>{% endif %}
>{% endfor %}
>
>{% endfor %}
> 
> 
>
> Obviously, if try to put an 'else' anywhere in that sales loop to say
> put an empty text input box, I'll get as many boxes as there are sales
> within each table cell.
>
> Is there anyway to get around this?
> Or with I need to create my own filter to do this?
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

-- 
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: Templates: Looping, ifs and defaults

2010-03-24 Thread Paulo Almeida
Sorry, I hadn't understood your original problem, now I see why the nested
ifs wouldn't work.

Regarding your last question, I think a list of lists would be easier than
dictionaries. You can append the product as the first item in each sublist
and then iterate the list to get the rows and columns of the HTML table.

- Paulo

On Wed, Mar 24, 2010 at 2:13 PM, ALJ  wrote:

> Just as a matter of interest ... is there a 'best way' of formatting
> the data if you do decide to process it all in the view and then pass
> to the template? I seem to have dictionaries coming out of my ears if
> I construct the data myself.
>
> --
> 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: change modelform values after POST

2010-03-29 Thread Paulo Almeida
It depends on what you want. You can set 'created_by' to blank=True and
null=False, so it doesn't have to be filled but it is still mandatory in the
database. Or, if you never want to set it in the form, you can make it
'editable=False' and it doesn't show up in the form, but it can still be NOT
NULL. Of course, you must make sure it is filled in some way.

- Paulo

On Sat, Mar 27, 2010 at 4:20 PM, tc  wrote:

>
>
> On 21 mar, 22:38, Bjunix  wrote:
> > You probably want to change the attributes of the model object
> > directly.
> >
> > "If you call save() with commit=False, then it will return an object
> > that hasn't yet been saved to the database."
> > Source:
> http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-sav...
> >
> > So I would do something like this:
> >
> > def my_change_view(request, id):
> > #get instance based on id here
> > #
> > if request.method == 'POST':
> > form = MyModelForm(request.POST, instance=instance)
> > if form.is_valid():
> > obj = form.save(commit=False)
> > obj.created_by = request.user
> > obj.save()
> > form.save_m2m()
> > return redirect('/somewhere')
> > else:
> > form = MyModelForm(instance=instance)
> > return render_to_response.
> >
> > I hope this helps. Remember to call form.save_m2m() if your model has
> > any many-to-many relations. I also would suggest to (re-)read django's
> > excellent documentation forms.
> >
>
> I see that the problem I have had today is exactly the same. The only
> problem of the solution you are
> proposing here is that created_by could not be mandatory. If it is,
> the form would be not valid.
>
>
> > On Mar 21, 10:00 pm, Cesar Devera  wrote:
> >
> > > hi.
> >
> > > I have a ModelForm based on an Model like this:
> >
> > > class MyModel(models.Model):
> > >   attr1 = models.CharField()
> > >   attr2 = models.CharField()
> > >   attr3 = models.CharField()
> > >   createdby = models.ForeignKey(User, related_name='createdby',
> > > db_column='createdbyid')
> > >   calculatedfield = models.CharField()
> >
> > > class MyModelForm(ModelForm):
> > > class Meta:
> > > model = MyModel
> >
> > > the attribute fields attr1, attr2 and attr3 are properly shown on my
> > > html page, and correctly restored on my server-side view like this:
> >
> > > def save(request,id):
> > > user = request.user
> > > try:
> > > mymodel = MyModel.objects.get(pk=id)
> > > except:
> > > mymodel = MyModel()
> > > form = MyModelForm(request.POST, instance=mymodel)
> >
> > > now comes the problem: I want to set the createdby attribute only on
> > > my view, AFTER the html page Post. I want to set the createdby and any
> > > other calculated field on server side. is it possible?
> >
> > > I tried:
> >
> > > form['createdby'] = request.user
> >
> > > but it didn't seem to work.
> >
> > > this field (createdby) is NOT NULL and so I wouldn't like to set it to
> > > NULL, save the form with form.save() and later recover the entity
> > > again and manipulate the remaining fields...
> >
> > > any ideas?
> >
> > > thanks in advance.
> >
> >
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to
> django-users+unsubscr...@googlegroups.com
> .
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>
>

-- 
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: I am having issues with django test

2010-03-29 Thread Paulo Almeida
This doesn't answer your question, but it may help you solve the problem. I
have this class in my tests:

class LoggedInUser(TestCase):
def setUp(self):
user = User.objects.create_user(USER, 'm...@nowhere.com', PASS)
self.client.login(username=user.username, password=PASS)
response = self.client.get('/experiment/import')

def test_experiment_list(self):
response = self.client.get('/experiments')
self.failUnlessEqual(response.status_code, 200)

This works for me... I haven't tried it your way, so I don't know what is
going wrong there.

- Paulo

On Sun, Mar 28, 2010 at 5:17 AM, Rolando Espinoza La Fuente <
dark...@gmail.com> wrote:

> On Sat, Mar 27, 2010 at 9:30 PM, Mohamed Ainab  wrote:
> > I have this test case
> >
> >def test_loginin_student_control_panel(self):
> >c = Client()
> >c.login(username="tauri", password="gaul")
> >response = c.get('/student/')
> >self.assertEqual(response.status_code, 200)
>
> Was the user created?
> Has is_active flag?
> You have django.contrib.sessions in your INSTALLED_APPS?
>
> c.login() returns False is login was unsuccessful.
>
> Hope it helps. Regards,
>
> ~Rolando
>
> --
> 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: Use admin widgets in inlineformset_factory

2010-03-30 Thread Paulo Almeida
This may point you in the right direction:

http://stackoverflow.com/questions/559361/inline-formset-in-django-removing-certain-fields

Take home message is that you can pass a ModelForm subclass to the fomset
constructor, so you can have a custom form. There is no example in that link
though, and I don't know what the syntax/parameter name is.

- Paulo

On Mon, Mar 29, 2010 at 7:43 PM, Fredrik  wrote:

> Hi,
> I have this forms.py file
>
>
> ---
>  # -*- coding: utf-8 -*-
> from django.contrib.admin.widgets import FilteredSelectMultiple
> from django.forms.models import inlineformset_factory
> from django.forms.models import BaseInlineFormSet
>
> from django.forms import ModelForm
> from django import forms
> from django.conf import settings
>
> from models import *
>
> class ScenariosForm(ModelForm):
>
> Contacts=forms.ModelMultipleChoiceField(Contacts.objects.all(),widget=FilteredSelectMultiple("Mottakere",False,attrs={'rows':'4'}))
>   class Meta:
>model = Scenarios
>exclude = ('deleted', 'contacts')
>
> class SMSform(ModelForm):
>class Meta:
>model = SMSs
>
>
> ---
>
> But I want to add this
> ScenariosFormSet = inlineformset_factory(Scenarios, SMSs, extra=4,
> max_num=10),
>
> to create a form width scenarios and sms, where sms has a foreign key
> to scenarios...
>
> But then I miss this functionality:
>
> forms.ModelMultipleChoiceField(Contacts.objects.all(),widget=FilteredSelectMultiple("Mottakere",False,attrs={'rows':'4'}))
>
>
> How can I add this widget to inlineformset_factory ?
>
> Regards
> Fredrik
>
> --
> 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: django, reportlab and basedoctemplate | simpledoctemplate

2010-03-30 Thread Paulo Almeida
I'm using Platypus (part of reportlab) to generate pdfs without
micromanagement of Canvas elements. reportlab's documentation was very
helpful to learn how to work with Paragraph, Table, Image, etc. Some code:

# views.py
@login_required
def view_pdf(request, experiment_id):
experiment =
get_object_or_404(Experiment.objects.filter(pk=experiment_id))
response = HttpResponse(mimetype='application/pdf')
filename = slugify(experiment.title) + '.pdf'
response['Content-Disposition'] = 'filename=' + filename
generate_pdf([experiment], response)
return response

# functions.py
def generate_pdf(experiments, output):
doc = SimpleDocTemplate(output, pagesize=A4)
Document = []
for experiment in experiments:
Document.extend(pdf_elements(experiment))
doc.build(Document)

pdf_elements is a function that adds bits and pieces... This is just an
excerpt:

def pdf_elements(experiment):
styles = getSampleStyleSheet()
Document = [Paragraph(escape(experiment.title), styles["Title"])]
Document.append(Spacer(1,50))
date = unicode(experiment.date.strftime("%B %d, %Y"))
Document.append(Paragraph("Acquired on " + date, styles["Normal"]))
date_now = unicode(datetime.now().strftime("%B %d, %Y"))
Document.append(Paragraph("PDF created on " + date_now,
styles["Normal"]))
Document.append(Spacer(1,10))
return Document

Read the Platypus documentation for many more elements and options.

These are my reportlab imports:

from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer,
TableStyle
from reportlab.platypus import KeepTogether
from reportlab.platypus import Table as Platypus_Table
from reportlab.platypus import Image as Platypus_Image
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet

- Paulo


On Tue, Mar 30, 2010 at 5:08 PM, Sven Richter wrote:

> Hi everybody,
>
> i am looking for a way to get BaseDocTemplate from the reportlab
> library working, connected with a httpresponse.
> I found the documentation for a simple reportlab page, using canvas.
> But to me it seems, that i need more options than basic Canvas offers.
> Like a page header or footer, tables continuing over pages etc.
> I have not found a working example to use httpresponse:
>
> response = HttpResponse(mimetype='application/pdf')
> response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'
>
> in conjunction with:
>
> BaseDocTemplate('basedoc.pdf',showBoundary=1)
>
> So if somebody could provide some working code, or a hint to
> repository or an application with some working code, i'd really
> appreciate that.
>
>
> Greetings
> Sven
>
> --
> 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: django, reportlab and basedoctemplate | simpledoctemplate

2010-03-30 Thread Paulo Almeida
Ok, that is not easy to debug with so little information. Is the IndexError
in views.py? Maybe there is a mistake in urls.py, caused by adding the url
for the generate_pdf view?

- Paulo

On Tue, Mar 30, 2010 at 7:57 PM, Sven Richter wrote:

> On Tue, Mar 30, 2010 at 8:21 PM, palmeida 
> wrote:
> > Is that all your code? I don't see a line like this (from my
> > generate_pdf function):
> >
> > doc = SimpleDocTemplate(response, pagesize=A4)
> I missed that one out of my example. You're right.
>
> But it doesnt generate a pdf like that, it just complains about that
> IndexError.
>
>
> Greetings
> Sven
>
> --
> 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: django, reportlab and basedoctemplate | simpledoctemplate

2010-03-30 Thread Paulo Almeida
Cool, you're all set then. Documentation on Platypus should help you do what
you want. I know it can do tables flow between pages, repeating the header
in the beginning of each page if desired, and I'm sure there are ways of
creating headers and footers, although I have never tried them.

Best,
Paulo

On Tue, Mar 30, 2010 at 11:52 PM, Sven Richter wrote:

> Shame on me. The problem was that i mixed SimpleDocTemplate (which the
> examples were based on), with BaseDocTemplate, which i used. And
> BaseDocTemplate needs an extra PageTemplate defined. So this code
> basically works:
>
> def generate_pdf(request):
>response = HttpResponse(mimetype='application/pdf')
>response['Content-Disposition'] = 'attachment;
> filename=somefilename.pdf'
> template = PageTemplate('normal',  [Frame(2.5*cm, 2.5*cm, 15*cm,
> 25*cm, id='F1')])
>doc =
> BaseDocTemplate(filename=response,pagesize=A4,pageTemplates=template)
>
>styles = getSampleStyleSheet()
>
>Document = [Paragraph('rd', styles["Title"])]
>Document.append(Spacer(1,50))
>
> doc.build(Document)
>
>return response
>
> Thanks all for the help!
> Sven
>
> On Wed, Mar 31, 2010 at 12:23 AM, Sven Richter 
> wrote:
> > Hm, what makes me wonder is this one:
> > IndexError at /office/job//admin/job/offer/generate/pdf/
> > This is a url that is not accessible, cause it does not exist, at
> > least i never defined it in any urls.py.
> > Maybe thats the problem? Django tries to access a url which doesnt exist?
> >
> >
> > Greetings
> > Sven
> >
> > On Tue, Mar 30, 2010 at 10:55 PM, Sven Richter 
> wrote:
> >> On Tue, Mar 30, 2010 at 9:08 PM, Paulo Almeida
> >>  wrote:
> >>> Ok, that is not easy to debug with so little information. Is the
> IndexError
> >>> in views.py? Maybe there is a mistake in urls.py, caused by adding the
> url
> >>> for the generate_pdf view?
> >>
> >> Hm, its indeed hard. I really dont know what that Error will tell me.
> >> My Application is a very basic one. Up to now i do everything in the
> >> admin interface. The only url defined is the one to view the pdf file:
> >>
> >> urls.py:
> >> urlpatterns = patterns('',
> >># Example:
> >># (r'^eiwomisa/', include('eiwomisa.foo.urls')),
> >>
> >># Uncomment the admin/doc line below and add
> 'django.contrib.admindocs'
> >># to INSTALLED_APPS to enable admin documentation:
> >># (r'^admin/doc/', include('django.contrib.admindocs.urls')),
> >>
> >># Uncomment the next line to enable the admin:
> >>(r'^admin/', include(admin.site.urls)),
> >>(r'^project/task/', include('project.task.urls')),
> >>(r'^office/job/', include('office.job.urls')),
> >> )
> >>
> >> offic/job/urls.py:
> >>
> >> from django.conf.urls.defaults import *
> >>
> >> urlpatterns = patterns('office.job.views',
> >>(r'/offer/generate/pdf/$', 'generate_pdf', '',
> >> 'office_job_generate_offer_pdf'),
> >> )
> >>
> >> and here is my views.py:
> >>
> >> def generate_pdf(request):
> >>response = HttpResponse(mimetype='application/pdf')
> >>response['Content-Disposition'] = 'attachment;
> filename=somefilename.pdf'
> >>
> >>doc = BaseDocTemplate(filename=response,pagesize=A4)
> >>styles = getSampleStyleSheet()
> >>Document = [Paragraph('rd', styles["Title"])]
> >>Document.append(Spacer(1,50))
> >>date_now = unicode(datetime.now().strftime("%B %d, %Y"))
> >>Document.append(Paragraph("PDF created on " + date_now,
> styles["Normal"]))
> >>Document.append(Spacer(1,10))
> >>doc.build(Document)
> >>
> >> I have tried the same "setup" with the canvas.Canvas example from the
> >> django documentation, and it worked. All i changed here is from canvas
> >> to document.
> >>
> >> Greetings
> >> Sven
> >>
> >
>
> --
> 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.



Accessing request.user in a ModelAdmin function

2012-06-14 Thread Paulo Almeida
Hi,

I would like to access the request.user in a ModelAdmin function, so I can 
filter the results of a query based on the logged in user. I have these 
models:

class Speaker(models.Model):
name = models.CharField(max_length=50)
endorsements = models.ManyToManyField(User,
   
 through="Endorsement")

class Endorsement(models.Model):
speaker = models.ForeignKey('Speaker')
user = models.ForeignKey(User)
endorsed = models.NullBooleanField()

class Meta:
unique_together = ("speaker", "user")

User comes from django.contrib.auth.models. In the ModelAdmin, I would like 
to have this:

class SpeakerAdmin(admin.ModelAdmin):
def is_endorsed(self, obj):

endorsement = Endorsement.objects.get(speaker=obj,
  
user=request.user)
return endorsement.endorsed

So then I could just add "is_endorsed" to the list_display variable to have 
the endorsement status for that user in the Speaker list, in the Admin 
site. Of course, this doesn't work because request isn't available in the 
is_endorsed function. I googled around and saw solutions for similar 
problems involving overrides of save_model, queryset or 
formfield_for_manytomany, but I couldn't adapt them to list_display, 
because I'm creating a function in the ModelAdmin, where I only know how to 
pass self and obj. Suggestions?

Thanks,
Paulo Almeida

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



Re: Accessing request.user in a ModelAdmin function

2012-06-14 Thread Paulo Almeida
Hi Melvyn,

I've only been reading the Django 1.2 docs, because it's what's immediately 
available in my Linux distribution, but that would be an excellent reason 
to upgrade, if I can get it to work. 

Thanks,
Paulo

On Thursday, June 14, 2012 12:33:34 PM UTC+1, Melvyn Sopacua wrote:
>
> On 14-6-2012 13:04, Paulo Almeida wrote: 
>
> > So then I could just add "is_endorsed" to the list_display variable to 
> have 
> > the endorsement status for that user in the Speaker list, in the Admin 
> > site. Of course, this doesn't work because request isn't available in 
> the 
> > is_endorsed function. I googled around and saw solutions for similar 
> > problems involving overrides of save_model, queryset or 
> > formfield_for_manytomany, but I couldn't adapt them to list_display, 
> > because I'm creating a function in the ModelAdmin, where I only know how 
> to 
> > pass self and obj. Suggestions? 
>
> In 1.4 you have ModelAdmin.list_filter and can subclass 
> SimpleListFilter. These get passed the request and the documentation 
> provides a full example of what you're trying to do. 
>
> -- 
> Melvyn Sopacua 
>

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



Re: Accessing request.user in a ModelAdmin function

2012-06-14 Thread Paulo Almeida
Hi again,

>From what I read in the 1.4 docs, the SimpleListFilter example is for 
list_filter and not list_display. To clarify what I wrote before, if a user 
endorses Speaker A and opposes Speaker B, I want the Speaker list in the 
admin site to show:

|Name | Is endorsed |
|A   | True|
|B   |  False |

Having a filter on "Is Endorsed" might be a nice addition, but the main 
goal is to have that table. Would there be a way to get the result of a 
SimpleListFilter into a callable that can be used in list_display? I didn't 
see that in the docs, and it's not obvious to me how to do it.

Thanks,
Paulo

On Thursday, June 14, 2012 1:09:58 PM UTC+1, Paulo Almeida wrote:
>
> Hi Melvyn,
>
> I've only been reading the Django 1.2 docs, because it's what's 
> immediately available in my Linux distribution, but that would be an 
> excellent reason to upgrade, if I can get it to work. 
>
> Thanks,
> Paulo
>
> On Thursday, June 14, 2012 12:33:34 PM UTC+1, Melvyn Sopacua wrote:
>>
>> On 14-6-2012 13:04, Paulo Almeida wrote: 
>>
>> > So then I could just add "is_endorsed" to the list_display variable to 
>> have 
>> > the endorsement status for that user in the Speaker list, in the Admin 
>> > site. Of course, this doesn't work because request isn't available in 
>> the 
>> > is_endorsed function. I googled around and saw solutions for similar 
>> > problems involving overrides of save_model, queryset or 
>> > formfield_for_manytomany, but I couldn't adapt them to list_display, 
>> > because I'm creating a function in the ModelAdmin, where I only know 
>> how to 
>> > pass self and obj. Suggestions? 
>>
>> In 1.4 you have ModelAdmin.list_filter and can subclass 
>> SimpleListFilter. These get passed the request and the documentation 
>> provides a full example of what you're trying to do. 
>>
>> -- 
>> Melvyn Sopacua 
>>
>

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



Re: Accessing request.user in a ModelAdmin function

2012-06-14 Thread Paulo Almeida
Hi Alireza,

Yes, that did the trick!

Thank you,
Paulo

On Thursday, June 14, 2012 2:26:46 PM UTC+1, Alireza Savand wrote:
>
>
>
> On Thursday, June 14, 2012 3:04:54 PM UTC+4, Paulo Almeida wrote:
>>
>> Hi,
>>
>> I would like to access the request.user in a ModelAdmin function, so I 
>> can filter the results of a query based on the logged in user. I have these 
>> models:
>>
>> class Speaker(models.Model):
>> name = models.CharField(max_length=50)
>> endorsements = models.ManyToManyField(User,
>>
>>  through="Endorsement")
>>
>> class Endorsement(models.Model):
>> speaker = models.ForeignKey('Speaker')
>> user = models.ForeignKey(User)
>> endorsed = models.NullBooleanField()
>>
>> class Meta:
>> unique_together = ("speaker", "user")
>>
>> User comes from django.contrib.auth.models. In the ModelAdmin, I would 
>> like to have this:
>>
>> class SpeakerAdmin(admin.ModelAdmin):
>> def is_endorsed(self, obj):
>> 
>> endorsement = Endorsement.objects.get(speaker=obj,
>>   
>> user=request.user)
>> return endorsement.endorsed
>>
>> So then I could just add "is_endorsed" to the list_display variable to 
>> have the endorsement status for that user in the Speaker list, in the Admin 
>> site. Of course, this doesn't work because request isn't available in the 
>> is_endorsed function. I googled around and saw solutions for similar 
>> problems involving overrides of save_model, queryset or 
>> formfield_for_manytomany, but I couldn't adapt them to list_display, 
>> because I'm creating a function in the ModelAdmin, where I only know how to 
>> pass self and obj. Suggestions?
>>
>> Thanks,
>> Paulo Almeida
>>
>
> I think you looking for this app
> http://pypi.python.org/pypi/django-cuser/
>
> Small piece of middleware to be able to access authentication data from
>  everywhere in the django code.
>
>
> Right ?
>
>
On Thursday, June 14, 2012 2:26:46 PM UTC+1, Alireza Savand wrote:
>
>
>
> On Thursday, June 14, 2012 3:04:54 PM UTC+4, Paulo Almeida wrote:
>>
>> Hi,
>>
>> I would like to access the request.user in a ModelAdmin function, so I 
>> can filter the results of a query based on the logged in user. I have these 
>> models:
>>
>> class Speaker(models.Model):
>> name = models.CharField(max_length=50)
>> endorsements = models.ManyToManyField(User,
>>
>>  through="Endorsement")
>>
>> class Endorsement(models.Model):
>> speaker = models.ForeignKey('Speaker')
>> user = models.ForeignKey(User)
>> endorsed = models.NullBooleanField()
>>
>> class Meta:
>> unique_together = ("speaker", "user")
>>
>> User comes from django.contrib.auth.models. In the ModelAdmin, I would 
>> like to have this:
>>
>> class SpeakerAdmin(admin.ModelAdmin):
>> def is_endorsed(self, obj):
>> 
>> endorsement = Endorsement.objects.get(speaker=obj,
>>   
>> user=request.user)
>>     return endorsement.endorsed
>>
>> So then I could just add "is_endorsed" to the list_display variable to 
>> have the endorsement status for that user in the Speaker list, in the Admin 
>> site. Of course, this doesn't work because request isn't available in the 
>> is_endorsed function. I googled around and saw solutions for similar 
>> problems involving overrides of save_model, queryset or 
>> formfield_for_manytomany, but I couldn't adapt them to list_display, 
>> because I'm creating a function in the ModelAdmin, where I only know how to 
>> pass self and obj. Suggestions?
>>
>> Thanks,
>> Paulo Almeida
>>
>
> I think you looking for this app
> http://pypi.python.org/pypi/django-cuser/
>
> Small piece of middleware to be able to access authentication data from
>  everywhere in the django code.
>
>
> Right ?
>
>

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



Re: 'ascii' codec can't encode character u'\xe4'

2012-06-14 Thread Paulo Almeida
Hi,

Have you tried using SetEnv directives in .htaccess to change the locale? 
I'm not sure how that would interact with wsgi, but maybe something like 
this:

http://drumcoder.co.uk/blog/2010/nov/12/apache-environment-variables-and-mod_wsgi/

Of course you'd have to do it in .htaccess instead of Virtual Hosts.

Paulo

On Thursday, June 14, 2012 11:35:40 AM UTC+1, lawgon wrote:
>
> hi, 
>
> I have an application which runs on a webfaction hosting. I also have 
> the same app running on my devel machine. The code in the two machines 
> are pulled from the same repo. Django versions are identical. Python 
> versions are identical. I try to upload a file called Lisäinfo 
> kummeille.pdf in the dev machine. No problem. When I try the same file 
> in webfaction, I get the above error. I have checked and find I can use 
> python to open and save a file of the same name from the python prompt 
> in the webfaction shell. In templates, admin and and generated pdfs, 
> these non ascii characters are handled perfectly. Has anyone got any 
> clues about this? The full traceback is given below: 
>
> Environment: 
>
>
> Request Method: POST 
> Request URL: http://kenyakids.info/admin/web/download/add/ 
>
> Django Version: 1.4a1 
> Python Version: 2.7.3 
> Installed Applications: 
> ('django.contrib.auth', 
>  'django.contrib.contenttypes', 
>  'django.contrib.sessions', 
>  'django.contrib.sites', 
>  'django.contrib.admin', 
>  'django.contrib.staticfiles', 
>  'sorl.thumbnail', 
>  'south', 
>  'kenyakids.web', 
>  'modeltranslation', 
>  'rosetta') 
> Installed Middleware: 
> ('django.middleware.common.CommonMiddleware', 
>  'django.contrib.sessions.middleware.SessionMiddleware', 
>  'django.middleware.locale.LocaleMiddleware', 
>  'django.contrib.auth.middleware.AuthenticationMiddleware', 
>  'django.middleware.doc.XViewMiddleware', 
>  'django.contrib.messages.middleware.MessageMiddleware') 
>
>
> Traceback: 
> File 
> "/home/kenyakids/webapps/django/lib/python2.7/django/core/handlers/base.py" 
> in get_response 
>   111. response = callback(request, 
> *callback_args, **callback_kwargs) 
> File 
> "/home/kenyakids/webapps/django/lib/python2.7/django/contrib/admin/options.py"
>  
> in wrapper 
>   367. return self.admin_site.admin_view(view)(*args, 
> **kwargs) 
> File 
> "/home/kenyakids/webapps/django/lib/python2.7/django/utils/decorators.py" 
> in _wrapped_view 
>   91. response = view_func(request, *args, **kwargs) 
> File 
> "/home/kenyakids/webapps/django/lib/python2.7/django/views/decorators/cache.py"
>  
> in _wrapped_view_func 
>   88. response = view_func(request, *args, **kwargs) 
> File 
> "/home/kenyakids/webapps/django/lib/python2.7/django/contrib/admin/sites.py" 
> in inner 
>   192. return view(request, *args, **kwargs) 
> File 
> "/home/kenyakids/webapps/django/lib/python2.7/django/utils/decorators.py" 
> in _wrapper 
>   25. return bound_func(*args, **kwargs) 
> File 
> "/home/kenyakids/webapps/django/lib/python2.7/django/utils/decorators.py" 
> in _wrapped_view 
>   91. response = view_func(request, *args, **kwargs) 
> File 
> "/home/kenyakids/webapps/django/lib/python2.7/django/utils/decorators.py" 
> in bound_func 
>   21. return func(self, *args2, **kwargs2) 
> File 
> "/home/kenyakids/webapps/django/lib/python2.7/django/db/transaction.py" 
> in inner 
>   209. return func(*args, **kwargs) 
> File 
> "/home/kenyakids/webapps/django/lib/python2.7/django/contrib/admin/options.py"
>  
> in add_view 
>   955. self.save_model(request, new_object, form, False) 
> File 
> "/home/kenyakids/webapps/django/lib/python2.7/django/contrib/admin/options.py"
>  
> in save_model 
>   709. obj.save() 
> File 
> "/home/kenyakids/webapps/django/lib/python2.7/django/db/models/base.py" 
> in save 
>   464. self.save_base(using=using, force_insert=force_insert, 
> force_update=force_update) 
> File 
> "/home/kenyakids/webapps/django/lib/python2.7/django/db/models/base.py" 
> in save_base 
>   552. result = manager._insert([self], fields=fields, 
> return_id=update_pk, using=using, raw=raw) 
> File 
> "/home/kenyakids/webapps/django/lib/python2.7/django/db/models/manager.py" 
> in _insert 
>   203. return insert_query(self.model, objs, fields, **kwargs) 
> File 
> "/home/kenyakids/webapps/django/lib/python2.7/django/db/models/query.py" 
> in insert_query 
>   1576. return 
> query.get_compiler(using=using).execute_sql(return_id) 
> File 
> "/home/kenyakids/webapps/django/lib/python2.7/django/db/models/sql/compiler.py"
>  
> in execute_sql 
>   909. for sql, params in self.as_sql(): 
> File 
> "/home/kenyakids/webapps/django/lib/python2.7/django/db/models/sql/compiler.py"
>  
> in as_sql 
>   872. for obj in self.query.objs 
> File 
> "/home/kenyakids/webapps/django/lib/python2.7/django/db/mod