Re: Getting an AttributeError while creating a Django project

2013-03-27 Thread Tom Evans
On Wed, Mar 27, 2013 at 4:39 PM, Olga Zasenko  wrote:
> Hi, everybody!
> I'm following the instructions on website docs.djangoproject.com and trying
> to create my very first Django project.
> The only result I get is a confusing error:
>
> AttributeError: 'module' object has no attribute '_handlerList'.
>
> My Django version is 1.5, Python - 2.7.3.
> I completely deleted and reinstalled Django, but it didn't help.
> Maybe the attached screenshot will help.
>
> Thank you.
>

I expect that the django-admin.py you are running is not the one you
have just installed. Check your PATH and see which is being run.

Cheers

Tom

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




Re: Django 1.5 tutorial error: 'module' has no attribute 'StackedInLine'

2013-03-27 Thread Tom Evans
On Wed, Mar 27, 2013 at 3:32 PM, +Emmanuel  wrote:
> Hello there,
>
> I am working through the django tutorial at djangoproject.com. So far
> everything works out fine until Section 2.4.6 (customizing the admin form).
> Django throws an error:  'module' has no attribute 'StackedInLine'. I
> checked around and this seems to work:
> if you use import to include a module, make sure you don’t have a file named
> just the same as the module you are trying to include in current directory.
> It seems python takes preference for local files over modules thus import
> fails.

Mmmm, yes, but this is not what is happening. If you have this structure:

polls
├── __init__.py
├── admin.py
├── models.py
└── views.py

and in the admin.py write "from django.contrib import admin", it will
not get confused about the "admin.py" in the same directory. If you
had a file called "django.py", then that would confuse the importing.

> Problem is, how now do I call the Poll admin module if it's name has been
> changed to say admin2.py since naming it admin.py conflicts with the main
> django admin.

The admin file in your poll app must be called admin.py, else it will
not be discovered.

The easiest way to work out why you are getting this error, would be
to give us the complete error message - there should be multiple lines
-  and the contents of your admin.py.

Cheers

Tom

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




Re: Avoiding Sessions

2013-03-27 Thread Tom Evans
On Wed, Mar 27, 2013 at 1:35 PM, Venkatraman S  wrote:
> So, if i am right, usage of sessions makes an extra call to the DB for every
> view with login_required.
>
> SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login",
> "auth_user"."is_superuser", "auth_user"."username",
> "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email",
> "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined"
> FROM "auth_user" WHERE "auth_user"."id" = 3
>
> ..app\debug_toolbar\utils\tracking/db.py in execute(118)
>   stacktrace = tidy_stacktrace(reversed(get_stack()))
>
> I do not want to be finicky about this 'extra' DB call, but was wondering if
> someone has used the cookie-based approach and has avoided sessions
> altogether. I just wanted to understand the implications on security and
> what i need to be aware of when using cookies in this way. Any experiences?
>
> -Venkat
> http://twitter.com/venkasub
>

This query has mostly nothing to do with sessions. This query occurs
when the authentication middleware populates request.user for logged
in users. The only thing that comes from the session is the user id
and the auth backend that authorized them, which is persisted in there
at login.

The cookie based approach does not avoid sessions, it inserts the
session data into a cookie and makes it tamper proof. If using the
cookie based session, the query above would still happen at exactly
the same point in the request.

Using the cookie based session backend would only avoid a SELECT query
at the start of the request to populate the session, and a UPDATE
query at the end of the request iff the data was modified.

The downsides of using cookie based sessions is that you are limited
to how much content you can place in there, and the session contents
are visible (but not modifiable) by the user. You lose control over
storage of the session, meaning you cannot change things in the
session (or even delete it) without the user presenting themselves at
your website.

Most of these are documented in the docs for cookie based sessions:

https://docs.djangoproject.com/en/1.5/topics/http/sessions/#using-cookie-based-sessions

Cheers

Tom

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




Re: Using values_list and extra on same queryset

2013-03-27 Thread Tom Evans
On Wed, Mar 27, 2013 at 12:38 PM, Larry Martell  wrote:
> Ignore my last message - I was seriously sleep deprive3d when I made
> it. But my original question remains - how can I use values_list and
> extra on same queryset?

It just seems to WFM:

Foo.objects.all().extra(select={'wibble': '1'}).values_list('pk', 'wibble')
[(611L, 1L), (612L, 1L), (613L, 1L), (614L, 1L), (615L, 1L), (616L, 1L)]

Works fine on my 1.3 and 1.4 sites, I don't have a 1.5 site handy..

Cheers

Tom

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




Re: Django problem:AttributeError:Manage isn't accessible via Link instances

2013-03-21 Thread Tom Evans
On Thu, Mar 21, 2013 at 7:49 AM, simon xue  wrote:
> Hi,When I read the book named "Learning Website Development With
> Django",step by step to doing the example,When I read to page 31,"To get an
> object by ID,type the following:>>>Link.object.get(id=1)   " I got this
> error: "Traceback :
> File "",line 1,in
> File"c:\python27\lib\site-packages\django\db\models\managers.py",line 232,in
> __get__
> raise AttributeError("manager isn't accessible via %s instances" %
> type.__name__)
> AttributeError: Manage isn't accessible via Link instances"
>
> How can I solve this problem?
>
> Thank U
>

You cannot access the 'objects' attribute through an instance of a
class, you must do it through the class method.

In addition to what Matt said ('objects', not 'object'), this could
happen if you typed exactly what you had said if you had redefined
what 'List' refers to. Eg:

>>> Link.objects.get(id=1)

>>> Link = Link.objects.get(id=1)
>>> Link.objects.get(id=1)
Traceback (most recent call last):
  File "", line 1, in 
  File "…/django/db/models/manager.py", line 219, in __get__
raise AttributeError("Manager isn't accessible via %s instances" %
type.__name__)
AttributeError: Manager isn't accessible via Link instances


If you are still having problems, copy and past your entire console
session so that we can see what you have done!

Cheers

Tom

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




Re: PostgresSQL or MySql with django?

2013-03-21 Thread Tom Evans
On Thu, Mar 21, 2013 at 1:06 PM, frocco  wrote:
> Has anyone used this?
>
> https://github.com/lanyrd/mysql-postgresql-converter/
>
> I cannot get this working, says cannot find the file
>

Why not use dumpdata as I suggested? Add your postgresql database
connection in Django as 'postgres', and do this:

python manage,py syncdb --database postgres
python manage.py dumpdata -a > data.json
python manage.py loaddata --database postgres data.json

Then edit settings.py, change the 'postgres' connection to be named
'defaut' and remove your existing mysql default.

This is much easier than messing around trying to get a script which
knows nothing about your database to convert everything correctly.

Cheers

Tom

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




Re: Looking for best practices regarding Development and production server paths

2013-03-21 Thread Tom Evans
On Thu, Mar 21, 2013 at 11:35 AM, DJ-Tom  wrote:
> Hi,
>
> I'm still a beginner and currently I'm trying to get more familiar with
> Django.
>
> I'm looking for any more detailed best-practices-type description on how the
> development cycle is meant to be managed.
>
> In settings.py, there are paths like TEMPLATE_DIRS and STATICFILE_DIRS, how
> is this supposed to work when paths on the development machine differ from
> the production server?
>
> I suppose I do not have to adjust those paths every time I upload a new
> version of my application?

The easiest way to do this is to specify them in terms of relative
path to the settings file.

Eg, I have this structure for my projects

websitename
├── app1
├── app2
├── manage.py
├── project
│   ├── settings.py
│   └── urls.py
├── static
└── templates

In my settings.py, I set the path to the project template folder and
project static files like so:

import os.path
ROOT = os.path.abspath(__file__).rsplit(os.path.sep, 2)[0]
TEMPLATE_DIRS = (
  os.path.join(ROOT, 'templates'),
  )
STATICFILES_DIRS = (
  os.path.join(ROOT, 'static'),
  )

This then works in both dev, test and live, since the structure is the
same on all three.

>
> Another point, how do I manage the time until the database schemes are
> updated to a new version (I'm planning to use south for database scheme
> maintenance) and nobody is supposed to use the application until
> everything's able to work again?
>

Easiest way is to stop people accessing your web app when you don't
want them to, and re-enable it afterwards. Depending on how you are
hosting Django, there can be a number of different solutions. Eg, for
my sites, hosted with Apache and FCGI, I simply stop the FCGI app, and
Apache shows an appropriately pretty 500 page.

Cheers

Tom

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




Re: PostgresSQL or MySql with django?

2013-03-20 Thread Tom Evans
On Wed, Mar 20, 2013 at 1:54 PM, frocco  wrote:
> Hello,
>
> I know this is not django related, but can someone help me with the syntax
> to port mysql to postgresql?
> I tried the mysqldump command with the postgresql compatibility option, but
> I still cannot import the data.
>
> Thanks
>
>

Django itself has mechanisms for importing and exporting data in a
database independent format:

https://docs.djangoproject.com/en/1.5/ref/django-admin/#django-admin-dumpdata

If you are not dealing with huge amounts of data, this can be the
simplest way forward.

Cheers

Tom

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




Re: Trouble in getting django session on app engine

2013-03-20 Thread Tom Evans
On Wed, Mar 20, 2013 at 10:19 AM, Suja C Varghese  wrote:
> I have read this and tried using django sessions. And i got error -
> ImproperlyConfigured: settings.DATABASES is improperly configured. Please
> supply the ENGINE value. Check settings documentation for more details.
>

You need to specify your database backend.

If you specify that sessions are stored in the database, then you must
specify the database in your settings.

Please note that Django on app engine is not officially supported.
There are two ways of using it, using a branch/fork of django called
django-nonrel, or by using Google's Cloud SQL driver.

django-nonrel is a fork of Django 1.3 with support for appengine. It
has significant differences to django.

https://github.com/django-nonrel/django/tree/nonrel-1.3

CloudSQL I think you have to pay for:

https://developers.google.com/appengine/docs/python/cloud-sql/django

You will have to use one of these two solutions if you want to run
django on appengine.

Cheers

Tom

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




Re: save as

2013-03-20 Thread Tom Evans
On Wed, Mar 20, 2013 at 11:28 AM, Larry Martell  wrote:
> Yes, I have convinced them to not require this. Now my issue is how to
> cause a file to be saved and to also render a template. When I return
> this:
>
> response = HttpResponse('This is what I want to save')
> response['Content-Type'] = 'application/gzip'
> response['Content-disposition'] = 'Attachment; filename=export.gzip'
> return response
>
> my template is obviously not rendered. How can I do this and also
> render my template at the same time?
>

Use render() shortcut to generate a response and set the appropriate
attributes on it before returning the response. Eg:

  response = render(request, 'my_template.html', { })
  response['Content-Type'] = 'application/gzip'
  response['Content-disposition'] = 'Attachment; filename=export.gzip'
  return response

Cheers

Tom

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




Re: Can't create an object with a foreign key

2013-03-20 Thread Tom Evans
On Tue, Mar 19, 2013 at 5:13 PM, Cody Scott  wrote:
> I get the error when I try to make an object.
>
>> Cannot assign "u'Category object'": "Course.category" must be a "Category"
>> instance.
>
>
> here is my admin form
>
> admin.py
>
> admin.site.register(Category, list_display = ('name',))
>
>
> CATEGORIES = [(category, category.name) for category in
> Category.objects.all()]

This will get calculated the first time the file is executed. This
means if you add any additional categories after that point, they
would not be reflected in this list.

>
> class CourseAdminForm(forms.ModelForm):
> class Meta:
> model = Course
> category = forms.ChoiceField(choices=CATEGORIES)

You cannot do that. If 'category' on the model is a foreign key to a
Category model, then the form field representing it must eventually
produce a Category instance. Choice fields always coerce their values
to return a string. This is the error warned about here (see the end
of the 'Note' section):

https://docs.djangoproject.com/en/1.5/topics/forms/modelforms/#overriding-the-default-field-types-or-widgets

The real question is why you are doing this. It seems like you are
trying to replicate the behaviour of a ModelChoiceField, without using
a ModelChoiceField. Is this because you want to customize how the
choices appear? There is an easier way of doing so, you can customize
the field to display your instance however you wish:


class CategoryChoiceField(forms.ModelChoiceField):
def label_from_instance(self, instance):
return instance.name

class CourseAdminForm(forms.ModelForm):
class Meta:
model = Course
category = CategoryChoiceField()

https://docs.djangoproject.com/en/1.5/ref/forms/fields/#django.forms.ModelChoiceField

Cheers

Tom

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




Re: Session values (occasionally) not being persisted

2013-03-18 Thread Tom Evans
On Mon, Mar 18, 2013 at 11:30 AM, Philip Goh  wrote:
> Dear list,
>
> This is a question that was asked on Stackoverflow more than a week ago, but
> I haven't had an answer so I am posting this to the Django mailing list as
> well.
> http://stackoverflow.com/questions/15338103/django-session-values-occasionally-not-persisted
>
> I have the following REST method that update the value of the session every
> time a jQuery tab is clicked to store the active tab.
>
> @csrf_exempt
> def update_active_tab_request(request):
>   """
>   Stores the active tab for a given tab item
>   """
>   for tab, active in request.GET.iteritems():
> request.session[tab] = int(active)
>
>   return HttpResponse("OK", status=200)
>
>
> It's a fairly simple routine, and the issue I'm having is that it that the
> value is not always stored in the session. I have viewed the web server
> logs, and I've sprinkled logging statements to verify that the code is being
> called. Everything appears to be working, but I've found that there is a
> chance that the session has not been updated when this method returns. I'm
> using the default database session engine, though I have tried others and
> have not met with much success.

Have you tried logging request.session.modified at the end of these
functions? Is it False when the data is not persisted?

>
> I came up with a work around that involved by passing the session and
> writing the values directly into the cache. This works, but I'm unhappy with
> this work around. Not only that, this week I've discovered that there are
> other values in the session that are occasionally not being persisted
> correctly.
>
> Am I hitting a size limit somewhere? I originally discounted this as I'm
> using the database session engine and the session text is stored in a "text"
> column that can grow indefinitely. Perhaps I'm wrong?
>
> Could the contents of the session be invalidated somehow and thus revert to
> an old/stale copy? The values are only ever stored in the session in one
> location, and I've surrounded it with breakpoints and logging statements and
> I can verify that it looks OK.
>

What DB are you using? MySQL + MyISAM + concurrent requests could be
interesting.

Just as a POV, have you thought of storing tab state in a client side
cookie? This avoids the need for the web server to do work solely to
remember client state.

This is how I've done it on my sites using jquery, the most recently
activated tab for a particular tab section is stored in a client side
cookie. The cookie is read on page load, and the indicated tab loaded.
When a tab is clicked, the cookie is immediately rewritten to reflect
the new state.

The contents of the cookie are a list of tuples of (url, tab section
id, active tab id), so one cookie supports remembering state on any
number of pages, and you can have any number of tab sections on a
page.

This is all derived from jqueryui's tabs interface, hooking in to the
'select' handler. Just an idea to think about!

Cheers

Tom

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




Re: Settings object has no attribute 'ROOT_URLCONF' while deploying using apache and mod_wsgi

2013-03-18 Thread Tom Evans
On Sun, Mar 17, 2013 at 9:20 AM, Navid Shaikh  wrote:
> Hi folks,
>
> (Before posting I searched in archive and the question is kind of similar to
> thread [1].)
>
> I am getting error:
> AttributeError: 'Settings' object has no attribute 'ROOT_URLCONF'

Hi Navid

Can you show the structure of your project, where it is on disk and so
on. I suspect that in mysite.wsgi, you are inserting the wrong paths
into sys.path, and then Django cannot find your correct settings.

> Below are my some config file excerpts:
> (I renamed my actual site name with mysite)

It can be very hard to determine whether your settings are correct if
you are editing the data you are sending to us. Eg, you have edited
the DJANGO_SETTINGS_MODULE line in your wsgi script, it is not really
'mysite.settings', since your site is not actually called 'mysite'.

If you have typos in this line, eg "secretprojectname.settinsg", and
you overwrite that with "mysite.settings" when you send it to us, we
will find it difficult to determine that! Please consider whether the
secret name of your project is worth this amount of hiding!

Cheers

Tom

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




Re: plugin for selecting files

2013-03-15 Thread Tom Evans
On Fri, Mar 15, 2013 at 12:59 PM, Larry Martell  wrote:
> On Thu, Mar 14, 2013 at 5:08 PM, Shawn Milochik  wrote:
>> On Thu, Mar 14, 2013 at 6:03 PM, Larry Martell  
>> wrote:
>>>
>>> I have been googing this for 2 days and trying lots of different
>>> things, without success. I really appreciate your help - I've made
>>> more progress in the last hour then in the previous 48.
>>
>>
>> Glad I could help, but you really should search the Django docs and
>> Google first. This is definitely one you would have found in the
>> Django docs.
>>
>> https://docs.djangoproject.com/en/1.5/topics/http/file-uploads/
>
> Thanks. I've found some examples, but they all use an upload button in
> addition to the 'choose file' button. Is there some way to have it
> upload the files as soon as the user click on open in the file picker?
>

To be honest, I'm not sure. You could set an onchange event to
automatically submit the form as soon as that control changes, but I'm
fairly certain that  should not throw any change
events or make the name of the file available to JS, for reasons of
security.

Auto submitting the form would not allow the user to correct
mistakenly selecting the wrong file, or rather, forms usually allow
you to change a field and verify before submitting, so automatically
submitting would violate POLA, and I could see browsers potentially
disallowing that.

You would need to test - can you auto-submit the form on change of the
file field? Try it and let us know.

Cheers

Tom

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




Re: Django on Mediatemple DV (4.0) in Virtualenv

2013-03-15 Thread Tom Evans
On Thu, Mar 14, 2013 at 9:37 PM, Tim Walzer  wrote:
> I am currently trying to install Django on a Mediatemple DV (4.0) server and
> have the installation be within a virtualenv.  The django app will be run
> from a subdomain, parts.domain.com, while the root domain domain.com is
> serving a wordpress site.
>
> I have django installed inside the virtualenv at
> /var/www/vhosts/domain.com/parts/env/ The virtual environment is 'env'.  The
> server is running python 2.4.3, but I needed at least 2.6, so I installed
> 2.6 inside the virtual env and that worked perfectly for setting up the
> initial django site.  Now the problem comes with the running of django.
>
> I created a vhost.conf file under /var/www/vhosts/parts.domain.com/conf
>
> 
>SetHandler python-program
> PythonPath "['/var/www/vhosts/domain.com/parts/env/bin',
> '/var/www/vhosts/domain.com/parts/env/store'] + sys.path"
> PythonHandler virtualproject
> SetEnv DJANGO_SETTINGS_MODULE store.settings
> 
>
>  The path to virtualproject, referenced in the PythonHandler line, is
> /var/www/vhosts/domain.com/parts/env/bin/virtualproject.py.
>
> The contents of that file are:
>
> activate_this = '/var/www/vhosts/domain.com/parts/env/bin/activate_this.py'
> execfile(activate_this, dict(__file__=activate_this))
>
> from django.core.handlers.modpython import handler
>
> The activate_this.py file is the one that comes with the virtualenv
> installation
>
> When I go to the site parts.domain.com, I get the following error in the
> apache logs:
>
> [Thu Mar 14 17:29:45 2013] [error] [client ] PythonHandler virtualproject:
> Traceback (most recent call last):
> [Thu Mar 14 17:29:45 2013] [error] [client ] PythonHandler virtualproject:
> File "/usr/lib64/python2.4/site-packages/mod_python/apache.py", line 287, in
> HandlerDispatch\nlog=debug)
> [Thu Mar 14 17:29:45 2013] [error] [client ] PythonHandler virtualproject:
> File "/usr/lib64/python2.4/site-packages/mod_python/apache.py", line 464, in
> import_module\nmodule = imp.load_module(mname, f, p, d)
> [Thu Mar 14 17:29:45 2013] [error] [client ] PythonHandler virtualproject:
> File "/var/www/vhosts/domain.com/parts/env/bin/virtualproject.py", line 4,
> in ?\nfrom django.core.handlers.modpython import handler
> [Thu Mar 14 17:29:45 2013] [error] [client ] PythonHandler virtualproject:
> ImportError: No module named django.core.handlers.modpython
>
> I can only think that this is happening because apache is attempting to use
> the system default python2.4 instead of the one in my virtualenv where
> django is installed.  How do I fix this?
>

mod_python uses the version of python that it is compiled and linked
against, it does not care about anything else.

The solution is to not use mod_python, which is an outdated,
inefficient, buggy and deprecated way of serving python applications,
and instead use mod_wsgi. This would allow you to use a different
python version for each app if you so desired.

Cheers

Tom

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




Re: Problem with ManyToManyField related table search

2013-03-13 Thread Tom Evans
On Wed, Mar 13, 2013 at 4:57 PM, Frank Schima  wrote:
>
> Hello,
>
>
> I'm clearly missing something obvious with a ManyToManyField. I just want to 
> return a result list for the related table in a View.
>
> So here is my Model:
>
> class Supply(models.Model):
>
> name = models.CharField(max_length=200)
>
>...
>
> class Tool(models.Model):
>
> ...
>
> supplies = models.ManyToManyField(Supply, related_name='supplies', 
> blank=True)
>
>
> I want to get a list of Tools for each Supply.
>
> Here is my View code:
>
> def supplies(request, page='chemicals'):
>
>
> renderdict = build_renderdict(request)
>
> 
>
> items = Supply.objects.filter(type__exact = type).order_by('name')
>
> if len(items)!=0:
>
> itemlist=[]
>
> for item in items:
>
> #sortedtools = item.tool_set.order_by('shortnamename')
>
> print item.name
>
> sortedtools = item.tool_set.all()  # <--- ERROR HERE
>
> itemlist.append({'id':item.id,'name':item.name, 
> 'minimum':item.minimum, 'current':item.current, 'reorder':(item.current < 
> item.minimum),
>
>
> 'minimum_bmf':item.minimum_bmf,'current_bmf':item.current_bmf, 
> 'reorder_bmf':(item.current_bmf < item.minimum_bmf), 'status': item.status,
>
>'tools':sortedtools})
>
>...
>
> Here is the runtime error:
>
> 'Supply' object has no attribute 'tool_set'
>
> Request Method:GET
> Request URL:http://127.0.0.1:8000/qff/whiteboard/chemicals/
> Django Version:1.2.3
> Exception Type:AttributeError
> Exception Value:
>
> 'Supply' object has no attribute 'tool_set'
>
> Exception Location:/usr/local/django-apps/qff/../qff/whiteboard/views.py in 
> supplies_general, line 924
> Python Executable:/usr/bin/python
> Python Version:2.6.6
> Python Path:['/usr/local/django-apps/qff', 
> '/usr/local/lib/python2.6/dist-packages/icalendar-3.1-py2.6.egg', 
> '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', 
> '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', 
> '/usr/lib/python2.6/lib-dynload', '/usr/local/lib/python2.6/dist-packages', 
> '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', 
> '/usr/lib/python2.6/dist-packages/gst-0.10', '/usr/lib/pymodules/python2.6', 
> '/usr/lib/pymodules/python2.6/gtk-2.0', 
> '/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode']
> Server time:Wed, 13 Mar 2013 10:30:19 -0600
>
> What am I doing wrong?
>
>
> TIA,
> Frank
>
>

You gave the M2M a related_name of 'supplies'. The related name refers
to the 'other side' of the relationship, it defines what the attribute
is called on the related model.

Without a related_name, Django would automatically add an attribute to
Supplies called 'tool_set', however since you have defined it, Django
adds an attribute called 'supplies', which is obviously not what you
intended. Simply remove the related_name argument, the only time it is
actually required is when you have one model that has two
relationships to the same model.

Cheers

Tom

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




Re: django templates and tex/latex

2013-03-13 Thread Tom Evans
On Wed, Mar 13, 2013 at 2:43 PM, Tom Evans <tevans...@googlemail.com> wrote:
> On Wed, Mar 13, 2013 at 2:01 PM, Ken <t...@anl.gov> wrote:
>> I would like to write a tex/latex file with django tags in it.  Load it with
>> the template loader and render it with a context.  The problem is that my
>> tex/latex file has quite a few '{%' in them.   They are conventional in TeX
>> for writing readable macros and are used to escape the newline.  I could try
>> rewriting them but before I do, I thought I'd ask if this is even worth
>> tackling.  TeX uses curly braces as grouping and percent signs as a comment.
>>
>> The TeX file would look rather confusing but the more important question is
>> what the loader does when it sees braces and brace comments.  Is it possible
>> to reassign the block and variable tags?
>>
>> Thanks
>>
>
> Nope. Well, of course, you can fork and change Django itself, but
> there be many edge cases where
>


Damn:

… but there may be many edge cases where simply changing the tokens
where they are defined (django/templates/base.py) may not work
correctly.

Cheers

Tom

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




Re: django templates and tex/latex

2013-03-13 Thread Tom Evans
On Wed, Mar 13, 2013 at 2:01 PM, Ken  wrote:
> I would like to write a tex/latex file with django tags in it.  Load it with
> the template loader and render it with a context.  The problem is that my
> tex/latex file has quite a few '{%' in them.   They are conventional in TeX
> for writing readable macros and are used to escape the newline.  I could try
> rewriting them but before I do, I thought I'd ask if this is even worth
> tackling.  TeX uses curly braces as grouping and percent signs as a comment.
>
> The TeX file would look rather confusing but the more important question is
> what the loader does when it sees braces and brace comments.  Is it possible
> to reassign the block and variable tags?
>
> Thanks
>

Nope. Well, of course, you can fork and change Django itself, but
there be many edge cases where

If you want to do this without changing Django, you would need to
replace all of TeX's curly braces - in fact, any of these strings
'{%', '%}', '{{', '}}', '{', '}', '{#' and '#}' - with "{% templatetag
'openblock' %}".

https://docs.djangoproject.com/en/1.5/ref/templates/builtins/#templatetag

Cheers

Tom

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




Re: Django 1.5 and url tag ( {% url 'django.contrib.auth.views.login' %})

2013-03-13 Thread Tom Evans
On Wed, Mar 13, 2013 at 1:33 PM, VVilku  wrote:
> Hello,
>
> I have problem with:
>
> Reverse for 'django.contrib.auth.views.login' with arguments '()' and
> keyword arguments '{}' not found.
>
>
> Request Method: GET
> Request URL: http://www.django-phpbb.pl:8000/blog/accounts/login/
> Django Version: 1.5
> Exception Type: NoReverseMatch
> Exception Value:
>
> Reverse for 'django.contrib.auth.views.login' with arguments '()' and
> keyword arguments '{}' not found.
>
>
> blog/urls.py:
> urlpatterns = patterns('',
>url(r'^accounts/login/$',
> 'django.contrib.auth.views.login', name='login1'),
>url(r'^accounts/logout/$',
> 'django.contrib.auth.views.logout'),
> )
>
> blog/templates/registration/login.html:
> 
>
> I try without quotes, but I receive another error (I know, in django 1.5 are
> a some changes in url tag):
>
> 'url' requires a non-empty first argument. The syntax changed in Django 1.5,
> see the docs.
>
> I tried to use only name ("login" -> {% url 'login1' %} and {% url 'login1'
> %} ). Also, it does not work.
> (Reverse for 'login1' with arguments '()' and keyword arguments '{}' not
> found.)
>
>
> Any suggestions?
>
> regards,
> VVilku
>

Did you omit to add 'blog' to settings.INSTALLED_APPS?

Cheers

Tom

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




Re: how do I run a django script from command line or Pycharm?

2013-03-13 Thread Tom Evans
On Wed, Mar 13, 2013 at 12:42 AM, frocco  wrote:
> I want to run the code below in a file called migration.py
>

3 options:

1) Setup the django environment manually in your scripts:

https://docs.djangoproject.com/en/1.5/topics/settings/#either-configure-or-django-settings-module-is-required

2) Write a management command

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

3) Use an extension like django-extensions as mentioned by Andy

Cheers

Tom

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




Re: Access Model data from a ModelFormset form

2013-03-12 Thread Tom Evans
On Tue, Mar 12, 2013 at 2:24 PM, Jim Kalafut  wrote:
> Hi,
>
> I often want to use a ModelFormset by showing some editable fields, and then
> showing some static data that is from the related model instance. For
> example, I want to bulk edit a group of Person object phone numbers and
> email address, but I'd also like to show (not edit) the person's name by
> each form.  Is there a straightforward way to get at that data, or configure
> the ModelFormset in a way that I can accomplish this?  My hack approaches so
> far are ugly to the point that it is cleaner to just create a set of
> form/model pairs myself and send them to the template.
>
> Thanks,
> Jim
>

Hi Jim

In a ModelForm (also applies to the individual forms in a
ModelFormSet), the instance that the form corresponds to will be
aailable in the attribute 'instance'. Eg, in your template, you can do
something like this:

{% for form in formset %}
  {{ form.title }}
  {{ form.name }}
  
  {{ form.instance.name }}
{% endfor %}

The docs only say that forms bound to a particular instance will have
the attribute:

https://docs.djangoproject.com/en/1.4/topics/forms/modelforms/#overriding-the-clean-method

But from code inspection it seems that an empty instance would be
created for any non bound model form - its the first thing
BaseModelForm does when instantiated without a supplied instance.

Cheers

Tom

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




Re: error- A server error occurred. Please contact the administrator.

2013-03-12 Thread Tom Evans
On Tue, Mar 12, 2013 at 3:26 PM, Mike Doroshenko II
 wrote:
> I thought the error was "A server error occurred. Please contact the
> administrator."
>
> I hate when errors say to contact your system administrator, I am my system
> administrator and am frustrated by invalid instructions.
>
> django-facebook?
>

"A server error occurred. Please contact the administrator" is the
stock client error page displayed by django when it cannot run.

As the adminstrator, you have access to logs which should show you why
this is happening.

It's not appropriate to put this information into the client message.
It's not appropriate to email the admins about this; this error is
displayed when, eg, we cannot read settings.py.
It is appropriate to dump the necessary information to fix this into
the error log

The most common cause of this error is incorrect middleware settings.

Cheers

Tom

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




Re: Is there any database ( or other ) magic going on with django properties?

2013-03-12 Thread Tom Evans
On Tue, Mar 12, 2013 at 6:09 AM, Doug S  wrote:
> I'm considering using django properties on some models that are mostly 
> tabulated numerical data.
> I'm want to derive some numerical scores from some of the columns of data I'm 
> using as input.
> If I use properties for these derived scores, what is actually happening. 
> Does Django put these into my models as fields and compute each score when a 
> model instance is saved,
> Or is simply calling the property function when I ask for the property?
> Or is is evaluated when a query set is evaluated?
> i am dealing with a large amount of data so efficiency is important
> I may not need to score every row in my DB,
> But being able to have indexed lookup by my derived scores would be nice
> Should I define these scores as fields in my model to get them into the DB
> Or will propterties do something like this for me?
> Are properties anything else than python functions defined on a Class
> Or does django build in some special functionality for them?
> Doug

Django doesn't do any magic with properties on models (or any
properties, IIRC). If you want a model to have a field, you need to
define a field in that model, not a property.

Cheers

Tom

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




Re: How to display large data by scrolling html page using python and django?

2013-03-11 Thread Tom Evans
On Mon, Mar 11, 2013 at 2:47 PM, Avnesh Shakya  wrote:
> ya i m trying  to display data from database on html page, but it's showing
> 20-25 rows of data from database..Actually i want to display 25 rows of data
> after that i want show 25 rows of data,that time last 20 rows should be
> flushed by scrolling and it should be repeat again-2
> thanks
>

Do you mean infinite scrolling, like Google Image search?

It's quite easy to do in Django:

http://dustinfarris.com/2012/4/django-jquery-and-infinite-scroll/

Cheers

Tom

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




Re: django login/registration validation error message issue

2013-03-11 Thread Tom Evans
On Mon, Mar 11, 2013 at 1:28 PM, sri  wrote:
> Hi,
>
> I am relatively new to Django and trying to create a Django application
> using 1.5 and created a pop up modal login and registration form using
> twitter bootstrap. The example i used to create the drop down
> login/registration form
> ishttp://mifsud.me/adding-dropdown-login-form-bootstraps-navbar/[1] .Now,
> the problem i am having is that, how do i show any error messages (password
> invalid etc) on the pop up login/registration drop down modal box.
>
> Here is my base.html file:
>
> 
>   
>  data-toggle="dropdown">Login
> 
>  method="post" class="form-horizontal">{% csrf_token %}
>  style="margin-bottom: 15px;" type="text" name="email" size="30" />
>  style="margin-bottom: 15px;" type="password" name="password" size="30" />
>  value="Sign In" />
> 
> 
>   
>   
>  data-toggle="dropdown">Register
> 
>  method="post" class="form-horizontal" name="register_form">{% csrf_token %}
> {{ register_form.non_field_errors }}
>  style="margin-bottom: 15px;" type="text" name="email" size="30" />
>  style="margin-bottom: 15px;" type="password" name="password1" size="30" />
>  placeholder="Password Again" style="margin-bottom: 15px;" type="password"
> name="password2" size="30" />
>  value="Register" />
> 
> 
>   
>
> And my views.py looks like below for login and registration views:
>
> def login_view(request):
>   if request.method == 'POST':
>  username = request.POST['email']
>  password = request.POST['password']
>  user = authenticate(username=username, password=password)
>  if user is not None and user.is_active:
> login(request, user)
> return HttpResponseRedirect(request.GET.get("next"))
>   else:
> return  HttpResponseRedirect(reverse('homepage'))
>
> def register_view(request):
>if request.method == 'POST':
>   form = UserCreationForm(data=request.POST, files=request.FILES)
>   if form.is_valid():
> new_user = form.save()
> new_user = authenticate(username=request.POST['username'],
> password=request.POST['password1'])
> login(request, new_user)
>  return HttpResponseRedirect(request.GET.get("next"))
>else:
>   return HttpResponseRedirect(reverse('homepage'))
>
> def homepage(request):
>form = UserCreationForm()
>return render_to_response('base.html',
> {
>  'register_form': form},
>context_instance=RequestContext(request))
>
> And my forms.py looks like below for registration:
>
>  class UserCreationForm(forms.ModelForm):
>
>password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
>password2 = forms.CharField(label='Password confirmation',
> widget=forms.PasswordInput)
>
>class Meta:
> model = MyUser
> fields = ('email',)
>
>def clean_password2(self):
> # Check that the two password entries match
> password1 = self.cleaned_data.get("password1")
> password2 = self.cleaned_data.get("password2")
> if password1 and password2 and password1 != password2:
> raise forms.ValidationError("Passwords don't match")
> return password2
>
>def save(self, commit=True):
> # Save the provided password in hashed format
> user = super(UserCreationForm, self).save(commit)
> user.set_password(self.cleaned_data["password1"])
> if commit:
> user.save()
> return user
>
> Can anyone help me how i can pass the registration validation error messages
> into the drop down modal form and also the login password validation error
> messages. What i would like to do is displat the error message in the drop
> down login/registration box itself.
>
> Thanks
>

Hi Sri

Django's form objects have individual field objects, accessible in the
template. These field objects have attributes for any validation error
messages, and the form itself has an attribute for any non field
related validation error messages.

Normally, Django would output these for you when you output the form.
However, you've hard-coded the HTML for the form, which makes it
impossible for Django to output the related error messages.

This page shows how forms are normally output:

https://docs.djangoproject.com/en/1.5/topics/forms/#displaying-a-form-using-a-template

And this section of the same page outlines what you must do if you
choose not to allow Django to do most of it for you:

https://docs.djangoproject.com/en/1.5/topics/forms/#customizing-the-form-template

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop 

Re: Upgrade to 1.5 issues

2013-03-11 Thread Tom Evans
On Mon, Mar 11, 2013 at 2:21 PM, Tom Evans <tevans...@googlemail.com> wrote:
> On Mon, Mar 11, 2013 at 2:00 PM, jayhalleaux <jay.halle...@gmail.com> wrote:
>>>> Any ideas on question 1? how to use named urls in settings.py?
>>
>
> The problem with having named URLs in settings.py (also some other
> places, models.py for instance) is that at this point, the URL
> resolving architecture has not yet been completed.
>
> There is a simple solution - you do not actually want the URL in
> settings.py at the time settings.py is parsed. When you actually want
> the URL, everything is properly set up. Therefore, you can use a
> simply lazy evaluation of your reverse call:
>
>   from django.utils.functional import lazy
>   from django.core.urlresolvers import reverse
>
>   lazy_reverse = lazy(reverse, str)
>
>   FOO_URL = lazy_reverse('mysite:my-named-url')
>
> The downside of lazy is that this url will get re-generated each time
> you access FOO_URL. There is a bit of magic for that too, you can
> memoize the result:
>
>   from django.utils.functional import lazy, memoize
>   from django.core.urlresolvers import reverse
>
>   _reverse_memo_cache = { }
>   lazy_memoized_reverse = memoize(lazy(reverse, str), _reverse_memo_cache, 1)
>
>   FOO_URL = lazy_memoized_reverse('mysite:my-named-url')
>
> Cheers
>
> Tom

Just noticed, I have my memoize and lazy the wrong way around, so it
has the wrong effect! The correct way should be:

  lazy_memoized_reverse = lazy(memoize(reverse, c2, 1), str)

IE, memoize the return value of reverse, and lazy evaluate it, not
memoize the lazily evaluated reverse function!

How embarrassing :)

Cheers

Tom

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




Re: Upgrade to 1.5 issues

2013-03-11 Thread Tom Evans
On Mon, Mar 11, 2013 at 2:00 PM, jayhalleaux  wrote:
>>> Any ideas on question 1? how to use named urls in settings.py?
>

The problem with having named URLs in settings.py (also some other
places, models.py for instance) is that at this point, the URL
resolving architecture has not yet been completed.

There is a simple solution - you do not actually want the URL in
settings.py at the time settings.py is parsed. When you actually want
the URL, everything is properly set up. Therefore, you can use a
simply lazy evaluation of your reverse call:

  from django.utils.functional import lazy
  from django.core.urlresolvers import reverse

  lazy_reverse = lazy(reverse, str)

  FOO_URL = lazy_reverse('mysite:my-named-url')

The downside of lazy is that this url will get re-generated each time
you access FOO_URL. There is a bit of magic for that too, you can
memoize the result:

  from django.utils.functional import lazy, memoize
  from django.core.urlresolvers import reverse

  _reverse_memo_cache = { }
  lazy_memoized_reverse = memoize(lazy(reverse, str), _reverse_memo_cache, 1)

  FOO_URL = lazy_memoized_reverse('mysite:my-named-url')

Cheers

Tom

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




Re: python

2013-03-11 Thread Tom Evans
On Mon, Mar 11, 2013 at 1:05 PM, Bill Freeman  wrote:
> I wouldn't call that "compiling", but it is a step that many people take in
> order to make it slightly more convenient to run.
>
> While "compiling" does happen, it is done automatically as a side effect of
> running the program.
>
> You are apparently not on Windows, since you have a chmod command.
>
> You can always run the program using:
>
>python filename.py
>
> As the python interpreter reads filename.py, it is "compiled" into "byte
> codes" which is actually what the python interpreter interprets.

I'd call it compiling, since python itself does!

Python ships with a module called 'compileall' to recursively compile
all python files within a directory tree. Use it like this:

python -m compileall /path/to/directory

http://docs.python.org/2/library/compileall.html

You can use this to ensure that your pyc files are fresh and
pre-compiled before deployment. I normally update files, remove all
.pyc/.pyo files, then run compileall as part of a deployment. Removing
pyc files may be necessary if you have removed a module, you do not
want old stale pyc files.

Cheers

Tom

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




Re: Template inheritance

2013-03-11 Thread Tom Evans
On Sat, Mar 9, 2013 at 10:28 AM, Tomas Ehrlich  wrote:
> Hi Nenad,
> you can wrap your meta-refresh line in another block and then delete
> it's content in templates which shouldn't be refreshed.
>
> # base_site.html
> {% block extrahead %}
> {% block extrahead-refresh %}
> 
> {% endblock %}
> {% endblock %}
>
> # change_form.html -- deletes content of block extrahead-refresh
> {% block extrahead-refresh %}{% endblock %}


This approach is exactly what the docs are warning about. This is
putting all of the logic of whether to display something into the
template, and not the view.

Cheers

Tom

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




Re: Template inheritance

2013-03-11 Thread Tom Evans
On Sat, Mar 9, 2013 at 9:41 AM, Nenad Cikic  wrote:
> Hello,
> I am using django admin for my project so I am not writing much templates by
> myself, therefore I am not very skilled with them, so excuse me if I ask
> dumb question.
> I have extended base_site.html to add browser refresh in block extrahead.
> I do not want however to do refresh while I am inserting data.
> In my change_form.html I have something as
> {% block extrahead %}{{ block.super }}
>
> What I would need is the possiblity to have some template variable that is
> True for base_site.html and that I set to False only in change_form.html,
> and then I could use that in base_site.html something as
>
> base_site.html
> {% block extrahead %}
> {% if do_refresh %}
> 
> {% endif %}
> {% endblock %}
>
> I understand that the template is only for presentation and not logic, as
> found in docs, but this I do see as logic of presentation:)
> I am looking in docs but can not see anythign useful for my scenario, which
> should not be so uncommon.
>
> What's the proper way to solve this.
> Thanks
> Nenad
>

Depends, which happens more frequently, wanting to override the
default or allow the default to happen?

I would handle all this with a context variable, 'no_meta_refresh'. By
default, this context variable would be unset, and the meta refresh
would be written out by the base template.

If a child template does not want the meta refresh, then it would add
'no_meta_refresh': True to it's context.

If you only wanted the refresh on 1-2 pages, and did not want it on
all the others, invert the logic. Have a variable called
'meta_refresh', by default not present, and force views requiring meta
refresh to set it.

The docs talk about separating presentation and logic. This doesn't
mean "do not put logic in the template", it is more about determining
the decisions about what to display in the view, and passing that
information on to the template. The view sets the context variable,
and the template acts upon it - this is the perfect separation of
presentation and logic.

Cheers

Tom

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




Re: Error: App with label world could not be found. Are you sure your INSTALLED_APPS setting is correct?

2013-03-11 Thread Tom Evans
On Mon, Mar 11, 2013 at 11:35 AM, jesmine chaudhuri
 wrote:
> Error: App with label polls could not be found. Are you sure your
> INSTALLED_APPS setting is correct? in django 1.3 project and mysql.
>
> I am new in Django and Python. Please anyone help me.
>
> Thanks in advance.
>
> Jesmine C
>

Please don't hijack old threads with your new problems, IE send a new
email to django-users@googlegroups.com instead of replying to an old
one. You will need to include more details as well if you want
assistance!

Cheers

Tom

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




Re: Question modelformset_factory with initial values

2013-03-08 Thread Tom Evans
On Fri, Mar 8, 2013 at 4:42 AM, carlos  wrote:
>
> Hi
> is posible fill forms with initial values for example
>
> -- models.py -
> class Model1(models.Model):
> field1 = models.CharField()
> field2 =models.CharField()
>
> CHOICE_ONE = (
>   (1,'one'),
>   (2, 'two'),
>   (3, 'three'),
>   (4, 'four')
> )
> class Model2(models.Model):
>  field_fk = fk(Model1)
>  field2 = models.IntegerField(choices=CHOICE_ONE)
>  field3 = IntegerField()
>  field4 = IntegerField()
>
> - forms.py ---
>
> class Model2Form(forms.ModelForm):
>
> class Meta:
> model = Model2
> exclude = ('field_fk',)
>
> -- views.py --
>
> def name_views(request):
> initial_one = [{'field2':'one'},
> {'field2':'two'},
> {'field2':'three '},
> {'field2':' four'},
>]
> form1FormSet = modelformset_factory(Model2, formModel2Form=,extra=4)
> if request.method == "POST":
> form1 = Model2Form(request.POST)
> if form1.is_valid():
> form1.save()
>else:
> form1 = form1FormSet(initial=initial_one)
>
> return render_to_response('template_form1.html',{'form1':form1},
>   context_instance=RequestContext(request))
>
> -- template_form1.html 
>
>{% csrf_token %}
>   {{form1.management_form}}
>
>   {%for fila in form1.forms%}
>{{ fila }}
>   {%endfor%}
>
> but this no working the output is
>
>
> but i need to appear so
>
>
>
> the words in red are the options
>
> which is the right way to do better and if possible do that
>
> additionally I read this but it's not like my model
> https://docs.djangoproject.com/en/dev/topics/forms/formsets/#using-initial-data-with-a-formset
>
> Cheers

Your initial values possibly don't appear because they are not valid
choices for that field - you've given it the text value of the choice,
it is expecting the data value, eg 1, not 'One'.

Additionally, your formset handling appears to be incorrect. Before
submission, you create an instance of your formset, yet after
submission you create an instance of your model form to try and save
it.

Cheers

Tom

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




Re: How do i set div dynamically in template?

2013-03-08 Thread Tom Evans
On Fri, Mar 8, 2013 at 2:34 PM, frocco  wrote:
> Hello
>
> I need to have a div set the on the first pass and then changed on the
> second pass
>
> for row in data
>first row
>
>   
>
>second row
> endfor
>
> in PHP I could just assign a variable to the div and change it.
> How would I do this in django?
>
> Thanks

Presumably, in a template?

https://docs.djangoproject.com/en/1.4/ref/templates/builtins/#for

Cheers

Tom

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




Re: p.choice_set.all() error

2013-03-08 Thread Tom Evans
On Fri, Mar 8, 2013 at 3:39 AM, Hugo Guzman  wrote:
> Hey there. I'm working through Part I of the "Writing your first Django app"
> tutorial and everything was going smoothly until I tried executing the
> following command:
>
 p.choice_set.all()
>
> When I try running it I get the proceeding errors (below). I've attached my
> models.py file for context. Any help or guidance would be much appreciated.
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File
> "/home/hugodev/dev/lib/python2.7/site-packages/django/db/models/query.py",
> line 72, in __repr__
> data = list(self[:REPR_OUTPUT_SIZE + 1])
>   File
> "/home/hugodev/dev/lib/python2.7/site-packages/django/db/models/query.py",
> line 87, in __len__
> self._result_cache.extend(self._iter)
>   File
> "/home/hugodev/dev/lib/python2.7/site-packages/django/db/models/query.py",
> line 291, in iterator
> for row in compiler.results_iter():
>   File
> "/home/hugodev/dev/lib/python2.7/site-packages/django/db/models/sql/compiler.py",
> line 763, in results_iter
> for rows in self.execute_sql(MULTI):
>   File
> "/home/hugodev/dev/lib/python2.7/site-packages/django/db/models/sql/compiler.py",
> line 818, in execute_sql
> cursor.execute(sql, params)
>   File
> "/home/hugodev/dev/lib/python2.7/site-packages/django/db/backends/util.py",
> line 40, in execute
> return self.cursor.execute(sql, params)
>   File
> "/home/hugodev/dev/lib/python2.7/site-packages/django/db/backends/mysql/base.py",
> line 114, in execute
> return self.cursor.execute(query, args)
>   File "/home/hugodev/dev/lib/python2.7/site-packages/MySQLdb/cursors.py",
> line 201, in execute
> self.errorhandler(self, exc, value)
>   File
> "/home/hugodev/dev/lib/python2.7/site-packages/MySQLdb/connections.py", line
> 36, in defaulterrorhandler
> raise errorclass, errorvalue
> DatabaseError: (1054, "Unknown column 'polls_choice.choice_text' in 'field
> list'")

This means that the database table exists, but it is missing a field
that is in your models.py.

This normally means you have changed your model after you created the table.

Django cannot automatically modify your DB tables when you change your
models.py (although there are packages like django-south that help you
manage making the changes), so you need to either manually modify the
table, or remove the table and re-run 'python manage.py syncdb', which
will re-create it (without any data).

Cheers

Tom

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




Re: How to order queries by exact match first

2013-03-06 Thread Tom Evans
On Wed, Mar 6, 2013 at 11:58 AM, Alexander Todorov
 wrote:
> Hi guys,
> I have this type of query:
>
> .filter(name__icontains='celery')
>
> and will possibly replace it with
>
> .filter(Q(name='celery') | Q(name__icontains='celery'))
>
>
> I want to get the results ordered by exact match first. Is this possible or
> I need to sort the results in my code?
>

Use .extra() to additionally select out 'name = "celery"' and order by
that extra field (followed by whatever else you wanted to order by).

Eg, something like:

q = 'Broken'
TVEpisode.objects.filter(
Q(title=q) | Q(title__contains=q)
  ).extra(
  select={'match': 'title = %s'},
  select_params=(q,)
  ).order_by('-match', 'title')

=>

[, , , , , ,  .. ]

Cheers

Tom

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




Re: Extending the base file depending on User type

2013-03-06 Thread Tom Evans
On Tue, Mar 5, 2013 at 9:06 PM, Sandeep kaur  wrote:
> I want to extend the base template file into the child file depending
> on the condition, like if the user is superuser or staff or active
> user, the file to extended should ll be different.
> For Eg :
>
> {% if user.is_superuser %}
> {% extends "base.html" %}
> {% else if user.is_active %}
> {% extends "base_client.html" %}
> {% else %}
> {% extends "base_noclient.html" %}
>
>
> However this code doesn't work.
> What should be done. Your help will be highly appreciated.
> Thank you.
>

{% extends %} can either take a string literal, or a variable. Move
the logic to decide which base template to use into your view, pass
the variable to the template in the context, and use that as the
argument to {% extends %}.

Cheers

Tom

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




Re: How to pass a value from a Django View to a JQuery Slider bar.

2013-03-06 Thread Tom Evans
On Tue, Mar 5, 2013 at 6:48 PM,  <7equivale...@gmail.com> wrote:
> Alright guys, thanks for the input, I need something a bit more specific to
> my case due to my ignorance on the subject at hand, so I am posting the code
> for my View, Template, and JQuery.  So, basically I want to take the slider1
> object value in the View, and place it in the Javascript where value = 37
> has been coded.
>
> // Here is my view
> //
> def slider_page(request):
>
>   slider1 = Slider.objects.get(sliderID=1)
>   variables = RequestContext(request, {'slider1': slider1})
>   return render_to_response('slider_page.html', variables)
>
> / Here is my Template
> //
>
> {% block external %}
>   
> {% endblock %}
>
> {% block content %}
>   
>   
> Intensity:
> 
>   
>   
>   
> {% endblock %}
>
> // Here is my JQuery
> //
>
>   $(function (){
> $( "#slider_1" ).slider({
>   range: "min",
>   value: 37,
>   min: 0,
>   max: 100,
>   slide: function( event, ui ) {
> $( "#power" ).val(ui.value );
>   }
> });
> $( "#power" ).val($( "#slider_1" ).slider( "value" ) );
> return false;
>   });
>

Er, just put your jquery into your template. The JS is specific to
that page (or pages with a #slider_1 on it, I suppose), so simply
include it into the page:

{% block content %}
  
  
Intensity:

  
  
  
  

Re: Impossible? Django with NTLM SSO auth on windows?

2013-03-06 Thread Tom Evans
On Tue, Mar 5, 2013 at 9:45 PM, Anton  wrote:
> Hmmm
>
> the bad support (as you mention "it hasn't been updated in quite some time")
> seems to be a major problem in this domain.

The NTLM/SSPI protocols haven't changed in a long time. Why should the
projects that support this tech need 'activity' on something that
works?

>
> I just looked at (for apache)
> http://mod-auth-sspi.sourceforge.net/docu/mod_ntlm/
>
> Here they say mod_ntlm is obsolete and
> " mod_auth_sspi is the version of mod_ntlm for Apache-2.0"
>
> but on the other side mod_auth_sspi seems to be dead too,

Indeed. There is more to life as an apache module than authentication,
in Apache 2.2 there is optionally authorization, and in 2.4 there is
no 'optional' about it. So mod_auth_sspi will never exist for Apache
2.4. Instead, there is (alpha) mod_authnz_sspi

https://www.apachehaus.net/modules/mod_authnz_sspi/

which seems to be supplied as a binary module, with no source code...

> so actually I am still not sure if its possible,
> if you don't want to use pure Microsoft technologies
> (like asp.net IIS server & other tools from ms)
>
> I am looking ..
>

The software you want is not compatible with your choice of web
server. The way I see it, you have four choices:

1) Use Apache 2.2 and mod_auth_sspi
2) Use Apache 2.4, port mod_auth_sspi to Apache 2.4
3) Use Apache 2.4, use binary mod_authnz_sspi, live with the security issues
4) Continue looking!

Cheers

Tom

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




Re: How to pass a value from a Django View to a JQuery Slider bar.

2013-03-05 Thread Tom Evans
On Tue, Mar 5, 2013 at 4:57 PM,  <7equivale...@gmail.com> wrote:
> Well, I definitly can't just throw a variable into the Javascript using the
> {{ }} tags. I tried it and it didn't work. I'm sure Shawn Milochik is
> correct about consuming the view with AJAX, however that is going to take
> sometime to learn and explore, as I am novice at this. It seems there should
> be an easy way for something so simple, I can pass a variable from a view to
> a template, but not from a view to a javascript file.
>

This is not true. You can render your javascript using a template if
you like, templates can be used to generate any textual format. A view
is simply a function that takes a request and produces a single
resource as a response.

However people don't normally dynamically generate their JS. This is
because it is not necessary, you simply include the data you want into
the HTML that the javascript will run against. You then use standard
JS methods to extract the data that you need and use it.

Eg, if you wanted to trigger an AJAX request each time someone clicked
a , you might do something like this:


  Hello World
  Wibble


Your JS file may have something like this:

$('ul li').click(function(ev) {
  $.getJSON( '{{ some-url }}', json_handler);
}

Obviously the "{{ some-url }}" would not work. Instead, the data can
be inserted in to the HTML element to which it refers:


  Hello World
  Wibble


and now the JS can be written to query that data:

$('ul li').click(function(ev) {
  $.getJSON(ev.target.data('json-uri'), json_handler);
}

tl;dr - if you need data in your javascript files, insert it into the
HTML doc and extract it when you need it.

Cheers

Tom

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




Re: how to add prefix in generic_inlineformset_factory?

2013-03-05 Thread Tom Evans
On Tue, Mar 5, 2013 at 11:40 AM, Witold Greń  wrote:
> I need to create two formset (generic_inlineformset_factory). When i create
> formset in template used formset_create_company and formset_create_private,
> field names are the same.
>
> c['form_create_company'] = User1()
>
> c['form_create_private'] = User2()
>
> c['formset_create_company'] = generic_inlineformset_factory(SpecialData,
> form=SpecialDataForm, extra=1, max_num=2)
>
> c['formset_create_private'] = generic_inlineformset_factory(SpecialData,
> form=SpecialDataForm, extra=1, max_num=2)
>
>
> {{ form_create_company.name }} = created: ' id="id_core-specialdata-content_type-object_id-0-name" maxlength="200"
> name="core-specialdata-content_type-object_id-0-name" type="text">'
> {{ formset_create_private.name }} = created: ' id="id_core-specialdata-content_type-object_id-0-name" maxlength="200"
> name="core-specialdata-content_type-object_id-0-name" type="text">'
>
> I need:
>
> {{ form_create_company.name }} = created: ' id="id_my_name1-specialdata-content_type-object_id-0-name" maxlength="200"
> name="my_name1-specialdata-content_type-object_id-0-name" type="text">'
> {{ formset_create_private.name }} = created: ' id="id_my_name2-specialdata-content_type-object_id-0-name" maxlength="200"
> name="my_name2-specialdata-content_type-object_id-0-name" type="text">'
>
>

Ah, I see. generic_inline_formset returns a type, not an instance, so
I'm not sure how your "c['formset_create_company']", which is a type,
not an actual form instance, is used. However, the simple answer is
that a type derived from FormSet will take 'prefix' as an argument
during construction. So, wherever you are constructing the formset,
provide the prefix.

Eg:

SpecialDataInlineFormSet = generic_inlineformset_factory(SpecialData,
form=SpecialDataForm, extra=1, max_num=2)

c['formset_create_company'] = SpecialDataInlineFormSet(prefix='company')
c['formset_create_private'] = SpecialDataInlineFormSet(prefix='private')


Cheers

Tom

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




Re: how to add prefix in generic_inlineformset_factory?

2013-03-05 Thread Tom Evans
On Tue, Mar 5, 2013 at 9:20 AM, Witold Greń  wrote:
> How to add prefix in generic_inlineformset_factory()? This is posible?
>

I don't understand precisely what you mean, but two of the arguments
to generic_inlineformset_factory() are 'form' and 'formset', allowing
you to specify a different class for the form objects created, and a
different base class for the formset created. This is generally true
for all formset_factory() functions.

This allows you almost unlimited flexibility in controlling how the
forms are generated, how they behave and so forth. Eg, if I wanted the
formset to take an additional argument on construction, and set that
argument on each instance the formset creates/modifies, I could do
something like this:


  class TeamBaseFormset(BaseModelFormSet):
def __init__(self, *args, **kwargs):
  self.manager = kwargs.pop('manager')
def save(self, commit=True, *args, **kwargs):
  instances = super(TeamBaseFormset, self).save(commit=False,
*args, **kwargs)
  for team in instances:
team.manager = self.manager
if commit:
  team.save()
  return instances

  TeamFormset = modelformset_factory(Team, formset=TeamBaseFormset)

  form = TeamFormset(manager=manager)

Since you have control over the formset class and the form, you can
override or change any behaviour that you want.

Cheers

Tom

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




Re: empty static_url

2013-03-04 Thread Tom Evans
On Sat, Mar 2, 2013 at 4:47 PM, Phil  wrote:
> Hi,
>
> I'm using django1.4.3
>
> I have a django project with 3 apps. All 3 apps templates extend 'app.html'.
> On 2 of my projects the CSS loads fine, but on third one the CSS doesn't get
> loaded because it's not adding '/static/' to the url to the CSS. So instead
> of '/static/css/style.css' I'm getting '/css/style.css' ...
>
> 

Technically speaking, if that is your template, and you end up with
"/css/style.css", then STATIC_URL is not empty, it is '/'.

>
> STATIC_URL is working on the 2 projects that use generic views, but not on
> the other one. So how can 'STATIC_URL' be blank and how can this be fixed? I
> tried adding the following to my index.html template but no joy...
>
> {% load static %}
> {% get_static_prefix as STATIC_PREFIX %}
>

To clarify - you only have one project, with three apps in it. In two
of the apps, which only use generic views, STATIC_URL works correctly,
but in third app it does not.

Do these views in the third app use RequestContext to render the
templates? Generic views do…

Cheers

Tom

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




Re: Getting only the models related to my queryset.

2013-03-04 Thread Tom Evans
On Fri, Mar 1, 2013 at 7:11 PM, Gabriel Koscky  wrote:
> Hi, I've been having some trouble with filtering the related models of a
> queryset,
> and I'm not sure if I'm approaching this wrong or if Django can't actually
> do it.
>
> Basically I have some models with ManyToMany relationships, like:
>
> class User(models.Model):
> name = models.CharField()
>
> class Product(models.Model):
> name = models.CharField()
>
> class Order(models.Model):
> user = models.ForeignKey(User)
>
> status = models.CharField()
>
> products = models.ManyToManyField(Product, through='OrderProduct')
>
> class OrderProduct(models.Model):
> product = models.ForeignKey(Product)
> order = models.ForeignKey(Order)
> amount = models.IntegerField()
>
>
> And I want to get all the products bought by User1, so I'd do something like
>
> Product.objects.filter(order__status='completed', order__user=User1)
>
> Which then returns just Product1, but now I want the amount the user bought,
>
> but it seems wrong to make another query like:
>
> Product1.orderproduct_set.filter(order__user=User1)
>
> And hit the database again to get data my first query can already bring
> me...
>
>
> So what I want to know is, based on a queryset that filters by related
> models,
>
> is there a way to get just the actual related models of my result?
>
>
> Thanks,
>
> Gabriel
>

Hi Gabriel

Read about select_related() and start from the appropriate point:

https://docs.djangoproject.com/en/1.4/ref/models/querysets/#select-related

Eg, this will result in only one query:

  qs = OrderProduct.objects.filter(order__user=user).select_related('product')
  for op in qs:
print u'%d x %s' % (op.amount, op.product.name)

Cheers

Tom

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




Re: Daemonize django server

2013-03-01 Thread Tom Evans
On Thu, Feb 28, 2013 at 6:23 PM, Tim Johnson  wrote:
> I'm having a hell of a time getting fastcgi to work on my mac, so
> for the time being I'll just stick with using the django server.
>
> Is it possible to daemonize the server? I would prefer that in some
> cases.
>
> From https://docs.djangoproject.com/en/dev/ref/django-admin/
> I see daemonize as an option for runfcgi but not for runserver.
>
> thanks

I didn't reply to your fastcgi posts yesterday, as you were attempting
to have everything spawned by the web server, which is not how I have
my fastcgi sites setup. If you are happy with running the web app
separately yourself, then this recipe will work:

Apache httpd with mod_fastcgi:

RewriteCond %{REQUEST_URI} !^/media
RewriteCond %{REQUEST_URI} !^/
# repeat for any other directories you want httpd to serve
RewriteRule ^/(.*)$ /app.fcgi/$1 [QSA,L]
FastCGIExternalServer /path/to/your/htdocs/app.fcgi -socket
/path/to/your/webapp/run/app.socket

Then simply ensure you have started your app:

python project/manage.py runfcgi \
socket=/path/to/your/webapp/run/app.socket \
pidfile=/path/.../run/app.pid \
errlog=... outlog=... \
minspare=.. maxspare=...

For absolute clarity, there is *no* real file named 'app.fcgi'. It
does not exist, it has no contents, it is merely a location in
urlspace - although you specify it as a filespace location! - that is
used to specify to fastcgi to take over the request. This is the
opposite of wsgi!

Is there a reason you are not using wsgi by the way? This is the
preferred method of hosting python apps, we used fastcgi as we are not
only hosting python apps.

Cheers

Tom

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




Re: os.system() is not working in django while working on server centos

2013-03-01 Thread Tom Evans
On Fri, Mar 1, 2013 at 11:29 AM, JAI PRAKASH SINGH
 wrote:
> import sys,os
> sys.stderr = open('/dev/null')
> import paramiko
> sys.stderr = sys.__stderr__
>
> os.system("echo \'s3\' >> myfile.txt ")  #debug first in ssh2
> def ssh2_connect(host, user, pswd, port=22):
> try:
> ssh = paramiko.SSHClient()
> ssh.load_system_host_keys()
> ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
> ssh.connect(host, port, user, pswd)
> return ssh
>
> except Exception, e:
> return str(e) + "Error. Failed to connect. Wrong
> IP/Username/Password"
>
>
> def ssh2_exec(ssh, cmd, sudo=False):
> result = []
> try:
> channel = ssh.get_transport().open_session()
> if sudo:
> channel.get_pty()
> except:
>   return result
>
> stdin = channel.makefile('wb')
> stdout = channel.makefile('rb')
>
> channel.exec_command(cmd)
>
> exit_status = channel.recv_exit_status()
>
> if exit_status == 0:
> for line in stdout:
> result.append(line)
> channel.close()
> return result
>
>
> def ssh2_close(ssh):
> ssh.close()
> return
>
>
> def ssh2_copyToFile(ssh, local_file, remote_file):
> sftp = paramiko.SFTPClient.from_transport(ssh.get_transport())
> sftp.put(local_file, remote_file)
> return
>

This doesn't seem related to Django… try a python mailing list.

Cheers

Tom

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




Re: Announcement: django-quickview 0.3 - putting the nitro in rapid web development

2013-02-28 Thread Tom Evans
On Wed, Feb 27, 2013 at 7:39 PM, Thomas Weholt  wrote:
> pypi : https://pypi.python.org/pypi/django-quickview/
> Source at https://bitbucket.org/weholt/django-quickview
>
> Documentation and tutorial at
> https://bitbucket.org/weholt/django-quickview/src/fde97a0a0befaeda0ab2317035f8e7cd9c311511/docs/basic.md?at=default
> for details.
>
> Bring on the flames ;-)
>

Not a flame :)

It would be cooler if you did not have to pollute model classes by
decorating them with view information. I'd prefer to denote that
FooModel has fast views *not* in models.py :)

For updating instances, you could make it compulsory to list the
changed attributes. Then, only the listed attributes are updated.

Apart from that, looks great. Will probably use this as scaffolding in
my next HTML5 app.

Cheers

Tom

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




Re: Use variable in my template?

2013-02-28 Thread Tom Evans
On Thu, Feb 28, 2013 at 2:40 PM, Maria  wrote:
> No I dont have a problem to find the images, i already used a variable to
> insert images from the static folder. Its just that I cant use my "marke"
> variable because it is in an external .py file and I would like to learn how
> to use that external variable in my template.
>

Put the variable in the context that you use to render the template.
The variables available in your template are the variables in the
context you supply when rendering your template.

All the template rendering functions take both a Context object and a
raw dictionary. The Context object is created if none is supplied, and
updated with the values in the dictionary (and any template context
processors if using a RequestContext). Eg for the render() shortcut:

https://docs.djangoproject.com/en/1.4/topics/http/shortcuts/#render

If it is still clear, this concept is explained further in the tutorial.

Cheers

Tom

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




Re: Problem with two databases

2013-02-28 Thread Tom Evans
On Thu, Feb 28, 2013 at 1:45 PM, MoonWolf  wrote:
> I'm making simple application to manage equipment. I've
> used django-ldapdb
> (http://opensource.bolloretelecom.eu/projects/django-ldapdb/) for user
> management (not for authentication, for which i'm using PAM). After
> heavy googling i've managed to connect all this together - LDAP as
> second database), so i can use LDAP-based users as owners of equipment
> (here are most important parts of models):
>
> class LdapUser(ldapdb.models.Model):
> """
> Class for representing an LDAP user entry.
> """
> class Meta:
> managed = False
> [...]
> full_name = CharField(db_column='cn')
> username = CharField(db_column='uid', primary_key=True)
>
> class Equipment(models.Model):
> number = models.CharField(unique=True, max_length=13)
> state = models.ForeignKey(State)
> model = models.CharField(max_length=255)
> owner = ForeignKeyAcrossDb(LdapUser)
> description = models.CharField(blank=True, max_length=255)
> type = models.ForeignKey(Type)
> place = models.ForeignKey(Place)
>
> def __unicode__(self):
> return u"%s (%s)" % (self.type, self.number)
>
> i googled out ForeignKeyAcrossDb, it's not my code. Also i have googled
> out database router (for main database):
>
> class DefRouter(object):
> def db_for_read(self, model, **hints):
> if model._meta.app_label == 'equipment_control':
> return 'default'
> return None
>
> def db_for_write(self, model, **hints):
> if model._meta.app_label == 'equipment_control':
> return 'default'
> return None
>
> def allow_relation(self, obj1, obj2, **hints):
> if obj1._meta.app_label == 'equipment_control' or
> obj2._meta.app_label == 'equipment_control':
> return True
> return None
>
> def allow_syncdb(self, db, model):
> if db == 'default':
> if model._meta.app_label == 'equipment_control':
> return True
> elif model._meta.app_label == 'equipment_control':
> return False
> return None
>
> And basically it works - i can edit users and also i can use LDAP-based
> users in my Equipments. But there are some issues:
>
> * i can't filter Equipments using 'owner' field:
> Equipment.objects.filter(owner__full_name__contains="name")
> ERROR:  relation "equipment_control_ldapuser" does not exists
> (which is true of course, because engine tries to find name in database
> - postgresql in my example)
>
> * i can't customize Admin panel - for example (in admin.py):
>
> class EquipmentModelAdmin(reversion.VersionAdmin):
> list_display = ("owner", "type", "number", "description")
>
> and i have "ERROR:  relation "equipment_control_ldapuser" does not
> exists" error.
>
> Is there any possibility to use LDAP transparently? Or maybe some
> workaround exists? I'm pretty new to Django (it's my first "true"
> application) and my knowledge of python is not very high also, so i
> can't figure out any solution. Thanks in advance for any help.
>

I'd do this in a different way, I'd have the user model in the main
database, with an attribute named 'cn', reflecting their LDAP cn.
Authentication is done against LDAP, but using an LDAP auth backend,
rather than trying to pretend LDAP is a django-supported DB. (In fact,
where I have done LDAP auth, I have done it exactly like this)

Any LDAP properties that you require could be added as python
properties to the user model, looking up the info in LDAP on demand,
perhaps caching it.

You then do not need any complex routing or multi DB weirdness.

Cheers

Tom

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




Re: default filtering model admin (crud) using user obj attribute

2013-02-28 Thread Tom Evans
On Thu, Feb 28, 2013 at 7:37 AM, Bino Oetomo  wrote:
> Dear All..
>
> Currently I have custom authentication backend,
> This backend return user-object with additional attributes
>
> START
> Python 2.7.3 (default, Aug  1 2012, 05:16:07)
> [GCC 4.6.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> (InteractiveConsole)
 from l2auth.models import Company
 from csm.models import L2User, L2Group
 from l2auth.backends import L2Backend
 myauth = L2Backend()
 myauth.authenticate('user02@binonet','')
> L2Backend => user02@binonet 
> ['user02', 'binonet']
> company_id => 1
> user==> user02
> 
 myuser=myauth.authenticate('user02@binonet','')
> L2Backend => user02@binonet 
> ['user02', 'binonet']
> company_id => 1
> user==> user02
 myuser.company_id
> 

 myuserdict=myuser.__dict__
 myuserdict
> {'username': u'user02', 'first_name': u'user 02', 'last_name': u'of
> binonet', '_state':  0xa7890ac>, '_company_id_cache': , 'company_id_id':
> 1, 'email': u'', 'is_active': True, 'is_superuser': False, 'is_staff':
> False, 'last_login': datetime.datetime(2013, 2, 28, 7, 1, 41, 521980,
> tzinfo=), 'password': u'pbkdf2_sha256$1$0NrkpAjo4osS
> $nFdAVaH9mlAbE9vzAvlj+aQeTP7gQsUpFZLZTYOVggs=', 'id': 2,
> 'date_joined': datetime.datetime(2013, 2, 28, 6, 58, 41,
> tzinfo=)}
 myuser.company_id_id
> 1
> STOP-
>
> My concern is 'myuser.company_id', this attribute is a ForeignKey to
> 'Company' model.
>
> I also have 'Car' model like :
> --START
> class Car(models.Model) :
> company_id = models.ForeignKey()
> badge = models.CharField('Badge', max_length=10)
> --STOP-
>
> By Default, every user login .. he/she have full access (CrUD) to all
> cars, including other company's car.
>
> My question is how to make :
> 1. Car list : Only show cars with company_id=myuser.company_id
> 2. Create/Update : 'Company choice list' locked to the one with
> value=myuser.company_id
> 3. Delete : Only posible for Car.company_id=myuser.company_id
>
> Kindly please give me any of your enlighten.
>
> Sincerely
> -bino-
>

It seems like you are asking how to do multi-tenancy in the stock django admin?

Multi tenancy is tricky in django. Is there any reason you are not
using one of the already existing multi-tenancy efforts?

Cheers

Tom

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




Re: Does Django support general reusable UI widgets?

2013-02-28 Thread Tom Evans
On Thu, Feb 28, 2013 at 10:46 AM, Dong Wang  wrote:
> It seems "django.forms.widgets" is designed to support only reusable input
> widgets used in forms, does Django support general reusable UI widgets like
> tornado.web.UIModule ?
>

Yes, Django allows you to define custom template tags that can do
anything you want. The closest equivalent to a UIModule is a template
inclusion tag, which allows you to define a context and a template
that uses that context.

https://docs.djangoproject.com/en/1.4/howto/custom-template-tags/

Cheers

Tom

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




Re: how to evaluate "cities/countries of the world" static table for an application.

2013-02-25 Thread Tom Evans
On Mon, Feb 25, 2013 at 12:47 PM, Johan ter Beest  wrote:
>
> On Feb 25, 2013, at 8:05 AM, Fatih Tiryakioglu  wrote:
>
> Hello all,
>
> Is there any shortcut for evaluating such a database table, or should I
> collect myself all this information. Please help. If you prefer a package
> which one do you prefer, or all of them is workable.
>
>
> This should give you all the info you need:
>
> http://www.maxmind.com/en/worldcities
>

Another useful resource is the CLDR:

http://cldr.unicode.org/

Cheers

Tom

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




Re: how to create attribute for image in django models.py

2013-02-20 Thread Tom Evans
On Wed, Feb 20, 2013 at 12:36 PM, Avnesh Shakya  wrote:
> thanks alot plz share any small project for beginners, if u have
>

If you haven't done the tutorial, you should do that first.

https://docs.djangoproject.com/en/1.4/intro/tutorial01/

Then you can extend the project by adding an image to a Poll.

Cheers

Tom

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




Re: how to create attribute for image in django models.py

2013-02-20 Thread Tom Evans
On Wed, Feb 20, 2013 at 12:26 PM, Avnesh Shakya  wrote:
> plz help me... i want to store image in database using model,how is it
> possible...?
>

https://docs.djangoproject.com/en/1.4/ref/models/fields/#imagefield

Cheers

Tom

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




Re: form media (css+js)

2013-02-20 Thread Tom Evans
On Tue, Feb 19, 2013 at 9:07 PM, yakoub abaya  wrote:
> i read this page : https://docs.djangoproject.com/en/1.4/topics/forms/media
> but i don't understand how those files gets rendered into the page template
> is it our responsibility when creating template files to make sure those
> form media files gets rendered ?
>
> if we take django/contrib/admin/templates/admin/base.html for example,
> then i don't see under head where it happens, maybe {% block extrastyle %}{%
> endblock %} ?
>

The form has an attribute called media. It is your responsibility to
output the value of that in the appropriate place in the page.

In the admin site, it has additional media to add, so it collects
form.media and the other media together in a list in the view, and
outputs it as the context variable media in the template. In 1.4, this
is here:

django/contrib/admin/options.py:985
django/contrib/admin/templates/admin/change_form.html:9

and probably in other places in the admin too - that is just an
example from the change form.

Cheers

Tom

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




Re: Call Class based view from another class based view

2013-02-19 Thread Tom Evans
On Tue, Feb 19, 2013 at 12:14 PM, psychok7  wrote:
> What do you mean not returnig?? i have a return statement. how should i do
> it?
>

You have this code:

  if u.username == username:
  if request.GET.get('action') == 'delete':
  #some logic here and then:
  ShowAppsView.as_view()(self.request)

When you call the other CBV like this, it produces a response. You
don't store it anywhere, so it is discarded. In effect, you run the
entire other view, produce a response and throw it away.

I thought you should return the response at this point, but on closer
inspection of the code, this is in compute_context(), which probably
is expecting a context to be returned, not a response.

You may need someone with more experience in CBVs.

Cheers

Tom

PS: Please don't email me directly in reply, I replied to the original
list email, it's quite likely I'll read any follow ups posted to list,
I don't need them in my inbox as well.

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




Re: Call Class based view from another class based view

2013-02-19 Thread Tom Evans
On Tue, Feb 19, 2013 at 11:34 AM, psychok7  wrote:
> hi, i am trying to call a class based view and i am able to do it, but for
> some reason i am not getting the context of the new class
>
> class ShowAppsView(LoginRequiredMixin, CurrentUserIdMixin, TemplateView):
> template_name = "accounts/thing.html"
>
> def compute_context(self, request, username):
> u = get_object_or_404(User, pk=self.current_user_id(request))
> if u.username == username:
> cities_list=City.objects.filter(user_id__exact=self.current_user_id(request)).order_by('-kms')
> allcategories = Category.objects.all()
> allcities = City.objects.all()
> rating_list = Rating.objects.filter(user=u)
> totalMiles = 0
> for city in cities_list:
> totalMiles = totalMiles + city.kms
> return {'totalMiles': totalMiles ,
> 'cities_list':cities_list,'rating_list':rating_list,'allcities' : allcities,
> 'allcategories':allcategories}
>
> @method_decorator(csrf_exempt)
> def dispatch(self, *args, **kwargs):
> return super(ShowAppsView, self).dispatch(*args, **kwargs)
>
> def get(self, request, username, **kwargs):
> return self.render_to_response(self.compute_context(request,username))
>
> class ManageAppView(LoginRequiredMixin, CheckTokenMixin,
> CurrentUserIdMixin,TemplateView):
> template_name = "accounts/smarturbia.html"
>
> def compute_context(self, request, username):
> action = request.GET.get('action')
> city_id = request.GET.get('id')
> u = get_object_or_404(User, pk=self.current_user_id(request))
> if u.username == username:
> if request.GET.get('action') == 'delete':
> #some logic here and then:
> ShowAppsView.as_view()(self.request)
>
> What am i doing wrong guys?
>

You're not returning the response created by calling the ShowAppsView
CBV, you just discard it. After that, control flows back in to the
ManageAppView CBV.

Cheers

Tom

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




Re: Migrating existing auth.User users to Django 1.5 Custom User table

2013-02-18 Thread Tom Evans
On Mon, Feb 18, 2013 at 4:33 PM, Ben Roberts  wrote:
> I assume, when Django 1.5 hits the public in 2014 >;) that many will want to
> take advantage of some facet of the new pluggable User models.  You may,
> like me,  want to add an additional column (field) or two in your custom
> User.
>
> E.g.:
>
> class SiteUser(AbstractUser):
> site = models.ForeignKey(Site, null=True)
>
>
> However, you have an exiting table of users and need to migrate them to your
> new model/table.  How? My current challenge is that I don't see any clear,
> scriptable way to do this, whether it be through South, SQL, or
> dumpdata/loaddata.
>
> Have an answer that's more than just a fleeting suggestion?  Feel free to
> grab the bounty on the Stack Overflow question if your answer works, or
> respond here if SO isn't your thing.
>

South migrations do not have to be automatically generated, there is a
rich API for making schema altering migrations:

http://south.readthedocs.org/en/latest/databaseapi.html#db-rename-table

Therefore, it simply comes down to what steps are required. Something
like this should suffice:

Add 'custom' user model that has exactly the same fields as the
current user model.
Add a schema migration to rename auth_user to the new required table name
Run your migration
Modify the user model as you see fit
Generate schema migrations as per any other model

Cheers

Tom

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




Re: Custom Http404 like exception

2013-02-18 Thread Tom Evans
On Mon, Feb 18, 2013 at 2:41 PM, Serge G. Spaolonzi  wrote:
> Thanks Pankaj,  In this case I could not use an HttpResponse because the
> helper method I am developing doesn't return a respose it returns a dict or
> raises an exception if the user is not authenticated.
> For example:
>
> def get_server_time(request):
>   time_dictionary = helper_method()
>   #Rest of the view here
>
> def helper_method():
>  if user.is_authenticated():
> return {'server_time': server_time()}
>  else:
> raise HttpCustomException(redirect='this_login_for_this_method')
>
> The goal is to return the dictionary or redirect the user to a specific
> login screen (there would be several login screens).
> The idea is to encapsulate all this functionality in the helper method so
> the views dont have to implement the authentication part or write a
> try/catch/redirect in all the views.
>

Hi Serge

If an unhandled exception is raised from view code, then before
generating a default error response, Django will first call any
middleware that has a process_exception method, and if a response is
returned from any of them, will use that response rather than proceed
with it's standard error reporting.

Therefore, you can simply define some middleware to handle project
specific exceptions in a similar manner to Http404.

Cheers

Tom

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




Re: Designing the email processing system. What path should I follow?

2013-02-15 Thread Tom Evans
On Fri, Feb 15, 2013 at 12:57 PM, Andre Lopes  wrote:
> Hi all,
>
> I'm building a Django website. Currently I'm searching for the best
> way to design the email processing system.
>
> The website is a Ads site. I need to send emails in a regular basis to
> the users. I'm looking for 20 or 30 e-mails hour for now.
>
> In other projects, I've been using a database table to handle the
> e-mail processing. But when I started to develop in Django I have read
> some articles about Celery/RabbitMQ. What I want to know is if adding
> Celery/RabbitMQ to the e-mail processing system is a must or I adding
> this I will only add another layer of complexity.

The problem is that if you don't use Celery, what you end up doing is…

>
> The solution that I've designed in another project uses a database
> table and a cronjob running every 5 or 10 minutes to handle this. The
> Database table is very simple. Looks like this:
>
> [code]
> CREATE TABLE "atem_emails_envios" (
> "id_email_envio" int4 NOT NULL,
> "id_email_msg" varchar(20) NOT NULL,
> "dat_inserted" timestamp NOT NULL,
> "dat_sended" timestamp,
> "try_number" int4,
> "max_tries" int4 NOT NULL,
> "email_from" varchar(500) NOT NULL,
> "email_to" varchar(500) NOT NULL,
> "email_cc" varchar(500),
> "email_bcc" varchar(500),
> "email_subject" varchar(500) NOT NULL,
> "email_msg" text NOT NULL,
> "error_msg" text,
> "i_started" timestamp,
> "pid" int4,
> "coment" varchar(2000),
> "id_utiliz_ins" varchar(45),
> "id_utiliz_upd" varchar(45),
> "data_ult_actual" timestamp,
>   PRIMARY KEY("id_email_envio"),
>   CONSTRAINT "Ref_atem_emails_envios_to_atem_mensagens_email" FOREIGN
> KEY ("id_email_msg")
> REFERENCES "atem_mensagens_email"("id_email_msg")
> MATCH SIMPLE
> ON DELETE NO ACTION
> ON UPDATE NO ACTION
> NOT DEFERRABLE
> );
> [/code]
>
> When an e-mail is being processed I just store the PID to the table to
> avoid collisions.

… this.

>
> My question goes in this direction. I've been using this table to
> process e-mails in a website with low traffic, and works well. What
> advantages I have using a Queue manager like Celery and a broker like
> RabbitMQ? What benefits I will gain using a solution like
> Celery/RabbitMQ?
>

You get a robust queuing system for processing tasks asynchronously
that will be understood by anyone who has used celery. If they haven't
used celery, then they can learn it, and then on the next project that
requires asynchronous handling of tasks, they don't need to learn the
quirks and deficiencies of yet another hand rolled queueing system.

You get tight integration into Django.

You get tools for monitoring and maintaining your queues.

You get the comfort that hundreds of billions of messages have
successfully passed through the same setup.

You don't have to write and maintain a queueing system. You don't have
to subsequently expand it to do multiprocessing. You don't have to fix
the inevitable bugs!

You get a proper AMQP stack which heterogeneous components can
communicate with each other through, if you have the need. For
instance, actions on your django site could send AMQP messages to a
node.js instance instructing it to push data to a client over
websockets.

(I swear there is an awesome blog post that explains all of this
better than I have, but my google-fu is weak today apparently!)

Cheers

Tom

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




Re: Using template fragment caching *inside* a sitewide cache: possible?

2013-02-14 Thread Tom Evans
On Mon, Feb 11, 2013 at 1:42 PM, Matt Andrews  wrote:
> Hi all,
>
> I've been experimenting with an expensive query I need to call (essentially
> grabbing data from some Google APIs). I tried this experiment:
>
> A sitewide cache with a long (days) expiry time
> A template fragment with its own separate cache inside a view cached by the
> sitewide cache -- this fragment simply displays the current time.
> A view function which clears the named template fragment cache.
>
> The behaviour I expected was that on first pageload, the fragment would
> display the time of page render, and all subsequent reloads would display
> the same time. This was true.
>
> The second part, though, was that I expected to be able to call the view
> function to clear the fragment cache and then reload the page to see the
> time update. This didn't happen.
>
> Is it possible to achieve this behaviour? Essentially I want to run a
> background cron task which just hits the Google API and updates my cached
> fragments - the Google data changes every 15 minutes but the sitewide cache
> has several hours timeout, normally.
>
> Hope this makes sense.
>
> Matt
>

Hi Matt

Can I restate the problem to see if I am getting it right?

You have a page fragment, 'FRAG', stored in the cache.
You have a page, 'PAGE', using that fragment stored in the cache.
You update 'FRAG' in the cache.
You reload 'PAGE', and it has the old contents of 'FRAG' instead of
the updated one.

If so, this is to be expected. The site cache caches entire responses,
with a key derived from that request. When a new request comes in, a
key is generated from that request. If the key is found in the cache,
the cached response is returned.

At no point does the cache know that one cache entry is built using
another, or that invalidating the fragment should invalidate any page
containing that fragment.

One potential solution is to use something like Varnish, an HTTP
accelerator/cache that has support for ESI - Edge Side Includes - that
allow you to build up responses from multiple components, and
intelligently cache the components. Eg, an example of what you are
trying to do in Varnish using ESI:

https://www.varnish-cache.org/trac/wiki/ESIfeatures#Anesi:includeexample

Alternatively, I may have completely misunderstood this :)

Cheers

Tom

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




Re: Is there an easy way to popup forms?

2013-02-13 Thread Tom Evans
On Wed, Feb 13, 2013 at 4:12 PM, frocco  wrote:
> I have a form I want to popup and am having trouble getting this to work.
> This is not in the admin page.
>
> Can someone give me an example?
>
> Thanks
>

An easy way to do a pop up form is to use a jqueryui dialog¹

http://api.jqueryui.com/dialog/

Cheers

Tom

¹ Other dialogs are available, consult your local google

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




Re: Replacing a model instance's __dict__

2013-02-11 Thread Tom Evans
Thanks for the advice guys, I didn't like it much either - a Friday
afternoon solution. I'll do something a little less brute force ;)

Cheers

Tom

On Sat, Feb 9, 2013 at 11:22 AM, Bill Freeman <ke1g...@gmail.com> wrote:
> Tom,
>
> I suspect that there man be problematic, perhaps dependent on python
> version, because the __dict__ attribute itself is a slot (it couldn't, for
> example, be in the __dict__).  Some slots may not accept assignment after
> creation, and the __dict__ object may not be an ordinary dict().
>
> Separately, if I'm understanding correctly, there is a local database with a
> copy of the information.  Unless you've done something special with the
> local model definitions, the id field will be problematic.
>
> I think that you're stuck with  a for loop over synched_contact.items(),
> where you can filter keys that shouldn't be saved.  You can also then uses
> setattr(self, key, value) instead of accessing self.__dict__, leaving you
> the flexibility for some of these attributes to be properties, if that turns
> out to be useful.
>
> Bill
>
> On Fri, Feb 8, 2013 at 12:50 PM, Tom Evans <tevans...@googlemail.com> wrote:
>>
>> Hi all
>>
>> I have a curious problem with a complex data replication issue.
>>
>> Basically, we use SalesForce as a CRM system. We also have a bunch of
>> users who aren't allowed a SF license due to cost reasons, and they
>> interact with SF via our own Django website that communicates to SF
>> via an API.
>>
>> With this API, we can CRUD all salesforce objects. We can also fetch
>> all changes since (specific time), so we maintain a local copy of all
>> our SF data in django models, synchronizing changes every 10 minutes
>> throughout the day. This actually works quite well!
>>
>> The problem comes with using django idioms like get_or_create(), when
>> an object is created directly on SF in the period since the last
>> synchronization. In this example, we want to get_or_create a Contact
>> with a specific email address. There is no Contact locally with the
>> specified email address, so get_or_create tries to create a new one.
>>
>> Using the API, this issues the appropriate query to SF, but since the
>> Contact already exists on SF, an exception is raised.
>>
>> get_or_create(), create() all work via save(), so my idea is to catch
>> this specific error in save, re-synchronise the database against the
>> remote end, pull the freshly synced record out of the database, and
>> replace self.__dict__ with new_item.__dict__, looking something like
>> this:
>>
>>   def save(self, *args, **kwargs):
>>   try:
>>   super(Contact, self).save(*args, **kwargs)
>>   except ValueError, e:
>>   if 'Contact already exists' in unicode(e):
>>   # Synchronize Contact objects with SF
>>   run_log = SyncRunLog(start_time=datetime.now())
>>   run_log.save()
>>   Contact.update(run_log)
>>   # The contact should now be available locally
>>   try:
>>   synched_contact = Contact.objects.get(email=self.email)
>>   self.__dict__ = synched_contact.__dict__
>>   except Contact.DoesNotExist:
>>   # Still not there, raise a new ValueError
>>   raise ValueError(
>>   'Failed to find contact %s after resyncing '
>>   'Contact following this error: %s'
>>   % (self.email, unicode(e)))
>>   else:
>>   raise e
>>
>> Is there an obvious issue with doing this? Can I simply replace
>> self.__dict__ like that without bad consequences?
>>
>> Cheers
>>
>> Tom
>>
>> --
>> You received this message because you are subscribed to the Google Groups
>> "Django users" group.
>> To unsubscribe from this group and stop receiving emails from it, send an
>> email to django-users+unsubscr...@googlegroups.com.
>> To post to this group, send email to django-users@googlegroups.com.
>> Visit this group at http://groups.google.com/group/django-users?hl=en.
>> For more options, visit https://groups.google.com/groups/opt_out.
>>
>>
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visi

Replacing a model instance's __dict__

2013-02-08 Thread Tom Evans
Hi all

I have a curious problem with a complex data replication issue.

Basically, we use SalesForce as a CRM system. We also have a bunch of
users who aren't allowed a SF license due to cost reasons, and they
interact with SF via our own Django website that communicates to SF
via an API.

With this API, we can CRUD all salesforce objects. We can also fetch
all changes since (specific time), so we maintain a local copy of all
our SF data in django models, synchronizing changes every 10 minutes
throughout the day. This actually works quite well!

The problem comes with using django idioms like get_or_create(), when
an object is created directly on SF in the period since the last
synchronization. In this example, we want to get_or_create a Contact
with a specific email address. There is no Contact locally with the
specified email address, so get_or_create tries to create a new one.

Using the API, this issues the appropriate query to SF, but since the
Contact already exists on SF, an exception is raised.

get_or_create(), create() all work via save(), so my idea is to catch
this specific error in save, re-synchronise the database against the
remote end, pull the freshly synced record out of the database, and
replace self.__dict__ with new_item.__dict__, looking something like
this:

  def save(self, *args, **kwargs):
  try:
  super(Contact, self).save(*args, **kwargs)
  except ValueError, e:
  if 'Contact already exists' in unicode(e):
  # Synchronize Contact objects with SF
  run_log = SyncRunLog(start_time=datetime.now())
  run_log.save()
  Contact.update(run_log)
  # The contact should now be available locally
  try:
  synched_contact = Contact.objects.get(email=self.email)
  self.__dict__ = synched_contact.__dict__
  except Contact.DoesNotExist:
  # Still not there, raise a new ValueError
  raise ValueError(
  'Failed to find contact %s after resyncing '
  'Contact following this error: %s'
  % (self.email, unicode(e)))
  else:
  raise e

Is there an obvious issue with doing this? Can I simply replace
self.__dict__ like that without bad consequences?

Cheers

Tom

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




Re: Any good books for learning django?

2013-02-08 Thread Tom Evans
On Fri, Feb 8, 2013 at 10:13 AM, vijay shanker  wrote:
> do u have the pdf ?
> will u share it at some place (or please mail it to me deont...@gmail.com)

Please don't use this list to arrange or ask others to pirate books.
The author of any django book almost certainly is a subscriber, you
are stealing his/her work from under their nose.

Please don't pirate technical books anyway. If everyone pirated
technical books, there would be no incentive to write new technical
books, and everyone loses out.

Cheers

Tom

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




Re: How to create a Django Group in case of multiple databases.

2013-02-07 Thread Tom Evans
On Thu, Feb 7, 2013 at 12:16 PM, laxglx  wrote:
>
> Hello Everybody,
>
> I'm going to create a Group using Django Group.
>
> I have two databases one is "master" and another is "slave"
> In master I created a user and group as usual.
>
> And in slave database I tried like this:
>
>
 Group.objects.db_manager('slave').create(name="grp1")
>
> This returned an error :
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/lib/python2.6/site-packages/django/db/models/manager.py", line
> 138, in create
> return self.get_query_set().create(**kwargs)
>   File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line
> 358, in create
> obj.save(force_insert=True, using=self.db)
> TypeError: save() got an unexpected keyword argument 'force_insert'

Have you trimmed this traceback?

>
> I also tried as follows, but got error :
>
 g = Group()
 g.name = "grp1"
 g.save(using='slave')
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: save() got an unexpected keyword argument 'using'
>

It looks like you have overwritten the save() method on the model you
are trying to save, and have not given it a method signature capable
of accepting the necessary arguments that save() is expected to
handle.

I say 'looks like', since I think you have obliterated the parts of
the traceback that would tell me…

save() takes many arguments. If you are not specifying any additional
arguments for your save() method, then it should look like so:

def save(self, *args, **kwargs):

This protects you from having to change the method if more arguments
are added in later versions of django, eg when the 'using' argument
was added in 1.2.

As usual, the docs have canonical instructions on how to override
model methods like save():

https://docs.djangoproject.com/en/1.4/topics/db/models/#overriding-model-methods

Cheers

Tom

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




Re: Any good books for learning django?

2013-02-07 Thread Tom Evans
On Thu, Feb 7, 2013 at 5:49 PM, frocco  wrote:
> Hello,
> Most of what I find are dated, 2008,2009.
> Are these still good for learning django 1.4?
>
> Which books do you recommend?
>
> Thanks

An often overlooked resource is the django documentation itself. The
index page is arranged in complexity from least to most. If you are an
experienced web developer but new to django, just reading the topics
directly linked from the index will give you a good understanding of
what features django has, and where the documentation for a topic can
(roughly) be found.

As an added bonus, the docs are never out of date.

If you are new to both python and django, then a book on python itself
will probably be very useful also.

Cheers

Tom

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




Re: post_save signal getting called twice !

2013-02-07 Thread Tom Evans
On Thu, Feb 7, 2013 at 1:54 PM, vijay shanker  wrote:
> Hi
> I am using django version 1.4.3
> I am using two signals in my models.py
> one is m2m_changed, so i can have a counter field (numcounter) of number of
> m2m fields attached, and another is post_save so i can decide whether to
> have a OneToOneField (cartrule, is to be applied only if there are more than
> 2 fields) or not.
> my models.py is:
>
> class CartItem(models.Model):
> content_type= models.ForeignKey(ContentType)
> object_id   = models.PositiveIntegerField()
> content_object  = generic.GenericForeignKey('
> content_type','object_id')
> quantity= models.PositiveIntegerField(default=0)
> is_abandoned= models.BooleanField(default=False)
> created_at  = models.DateTimeField(auto_now_add=True)
> update_at   = models.DateTimeField(auto_now=True)
> def __str__(self):
> return self.content_object.name
>
> class CartRule(models.Model):
> ##some field
> pass
>
> class Cart(models.Model):
> cart_id = models.CharField(max_length=50, null=False)
> customer= models.ForeignKey(Customer,null=True,blank=True)
> cartitems   = models.ManyToManyField(CartItem,null=True)
> created_at  = models.DateTimeField(auto_now_add=True)
> update_at   = models.DateTimeField(auto_now=True)
> cartrule   =
> models.OneToOneField(crapclass,null=True,blank=True)
> num_cartitem= models.IntegerField()
> def __str__(self):
> return self.cart_id
>
> @receiver(post_save, sender=Cart)
> def apply_condition(sender,instance,created,raw,using,*args,**kwargs):
> # i want to decide here if num_cartitem is greater than 2 its ok to have
> a cartrule
> pass
>
> @receiver(m2m_changed)
> def save_cartitem_counter(sender, instance, signal,*args, **kwargs):
> if kwargs['action'] == 'post_add':
> instance.num_cartitem = instance.cartitems.all().count()
> instance.save()
>
> the issue is apply_condition gets called twice, with similar value of args,
> first with older value of m2m (cartitem) field in Cart, the other time with
> the values i intended to save
> I looked into older post but still could not figure out the whys.How should
> i go about this ?
>

When you save a Cart instance, the post_save signal is triggered.
If the M2M relationship is changed as well, then the m2m_changed
signal is triggered. Your handler for this then re-saves the Cart
instance after denormalising data, which triggers the post save signal
for a second time.
You should probably connect the M2M receiver to a specific sender too,
currently it will fire whenever any M2M on any model is changed.

Keeping denormalized data like that is a pain, could you do without
it, and re-calculate it where necessary?

Alternatively, you could use a named intermediary M2M relationship:

https://docs.djangoproject.com/en/1.4/topics/db/models/#intermediary-manytomany

and connect signals on post_create and post_delete to the intermediary
model, updating the Cart as necessary.

This is a little more logical, since you wish to denormalise the data
whenever an item is added to or removed from a cart, ie whenever a row
is added or deleted to the intermediate table. Naming the relationship
allows you to connect the signals to the right place.

Cheers

Tom

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




Re: initial argument in forms not working for me

2013-02-01 Thread Tom Evans
On Mon, Jan 28, 2013 at 5:35 AM, Nikhil Verma  wrote:
> Hi
>
> I am using django 1.4.3 and have a field in form
>
>
>  PROFILE_TYPE = (
> ('public', 'Public'),
> ('private', 'Private'),
> )
>  profile_type = forms.CharField(max_length=10, widget=RadioSelect
>(choices=PROFILE_TYPE),
>initial='Public',
>required=False
>)
>
> I want that when i open this form the radio button with choice public should
> be pre selected.
> Can anybody explain what mistake you are doing ?
>
> Thanks

You've specified the initial value as 'Public', which does not match
either of the allowed choices, 'public' and 'private'.

Cheers

Tom

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




Re: Special SELECT and UPDATE for a field

2013-01-31 Thread Tom Evans
On Wed, Jan 30, 2013 at 8:14 PM, Yarden Sachs  wrote:
> Hello,
> i want to create a field class for geometry (not using geodjango).
> here's the field code: http://pastebin.com/yADpZykJ
>
> i want 2 things i can't seem to do:
> 1. I want the select to wrap the column with MySql AsText() Function
> e.x. SELECT AsText(location) FROM addresses
>
> 2. I want to be able to save the value wrapped with a function e.x.
> GeomFromText('POINT(0.0 0.0)')
> but is seems that django will wrap that function with quotes, and so mysql
> thinks its a string.
>
> I found that in order to fix these, i will have to write an SQLCompiler,
> Query, QuerySet, QuerySetManager. (or modify the get_columns and
> get_default_columns methods of the SQLCompiler)
> I am sure there is a simpler way.
>
> What can I do?
>
> Thanks!

Sounds like you want to define a custom field rather than fiddle with
a Model's manager.

https://docs.djangoproject.com/en/1.4/howto/custom-model-fields/

Cheers

Tom

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




Re: Kindly help for an interview with Google on python django

2013-01-31 Thread Tom Evans
On Thu, Jan 31, 2013 at 5:25 PM, Larry Martell  wrote:
> Books have been written about interviewing at google. Google
> 'interviewing at google' and you'll find a plethora of stories. After
> reading them you may not want to interview there. I was offered a
> chance to interview there about 8 years ago, and I after reading what
> it would be like, I declined. YMMV

Don't google for 'interviewing at google', or they'll know what you
are up to! Best to use Bing for that.

Bad jokes aside, you should have a clear idea why you want to work
there, what you can bring to them, and why they would want it (this is
basically true of any interview). Work it out before you go there, so
you don't stammer around trying to figure it out on the spot!

Cheers

Tom

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




Re: Can I set a "global" variable after user login, to use in my view?

2013-01-31 Thread Tom Evans
On Tue, Jan 22, 2013 at 8:01 PM, Fellipe Henrique  wrote:
> The problem is, I need to pass this request.user to one form, using a
> inlineformset_factory..in these code:
>
> class PedidoItensForm(ModelForm):
> class Meta:
> model = ItensPedido
>
> def __init__(self, *args, **kwargs):
> profile = kwargs.pop('vUserProfile', None)
> super(PedidoItensForm, self).__init__(*args, **kwargs)
> self.fields["idproduto"].queryset =
> Produto.objects.filter(idempresa=profile.idempresa)
>
> I need to pass UserProfile to my form, to get works my filter.
>
> If I use inlineformset_factory, how can I pass the vUserProfile ?
>

You need to define a new base formset and form classes that take the
additional arguments when constructing form/formset, and to supply
them when the formset creates the forms, and supply these classes as
arguments to inlineformset_factory.

Eg, to accept an argument of 'profile' on each form:

from django.form.models import BaseInlineFormSet

class MyForm(Form):
  def __init__(self, *args, **kwargs):
self.profile = kwargs.pop('profile')

class MyFormBaseFormSet(BaseInlineFormSet):
  def __init__(self, profile=None, *args, **kwargs):
self.profile = profile
  def _construct_form(self, i, **kwargs):
kwargs['profile'] = self.profile
return super(MyFormBaseFormSet, self)._construct_form(i, **kwargs)

MyFormSet = inlineformset_factory(MyModel, form=MyForm,
formset=MyFormBaseFormSet)

Cheers

Tom

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




Re: an elusive ValueError: 'str' object not callable -- lost.

2013-01-31 Thread Tom Evans
On Wed, Jan 30, 2013 at 6:59 PM, Maurice Asimov  wrote:
> Hey guys.
>
> I recently started getting a ValueError complaining that an str is not
> callable -- in a very wierd place.
>
> This happens to some calls to messages.info(request, 'somethingsomething'),
> in one of those cases __inside the django console__
>
> Any other ideas what's wrong? Anyone bumped into this?
>
> The same problem occured in part of the app I control, removing the call to
> messages.info solved it.
>
> Anything at all? Thanks.
>

Somehow, you have overwritten the 'info' attribute of the
django.messages module with a string, and so it blows up.

Look for places where you assign to anything named 'info':

ack "\Winfo.*="
ack "setattr\([^,]*,.*info"

or

grep -r "[^a-z_]info.*=" *
grep -r "setattr([^,]*,.*info" *

I know you said not to blame your custom middleware, but this does not
happen with stock 1.4.2, so if you have this happening even in
requests that do not touch your views, it most likely will be your
middleware.

It would be easy to test if you can reliably reproduce this in the
admin site, simply disable the custom middleware and see if you can
still reproduce the error.

Cheers

Tom

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




Re: Getting a no such column error when adding data and syncdb is not syncing

2013-01-18 Thread Tom Evans
On Fri, Jan 18, 2013 at 3:38 PM, Nick  wrote:
> This is my first django project outside of the tutorials and it's
> frustrating to stumble over something so simple.
>
> I'm getting this error when I try to add a product:
>>
>> DatabaseError at /admin/products/product/add/
>>
>> table products_product has no column named pub_date
>
>
> This is what my models.py file looks like:
>>
>> from django.db import models
>>
>> class Product(models.Model):
>> name = models.CharField(max_length = 200)
>> desc = models.TextField()
>> pub_date = models.DateTimeField()
>>
>> def __unicode__(self):
>> self.name
>
>
> ./manage.py sqlall products returns:
>>
>> BEGIN;
>> CREATE TABLE "products_product" (
>> "id" integer NOT NULL PRIMARY KEY,
>> "name" varchar(200) NOT NULL,
>> "desc" text NOT NULL,
>> "pub_date" datetime NOT NULL
>> )
>> ;
>> COMMIT;
>
>
> It's all very simple and nothing is special about what I have done. Sorry in
> advance if you guys have dealt with noob questions like this a hundred
> times.
>

syncdb creates tables in the database if they do not exist.

syncdb does not alter existing tables in the databases.

If you would like to automate the work of altering your database
tables, there is an app called django-south which you can use to
inspect your models and database, and generate migration scripts to
update the database so that it corresponds with your models. Google
knows more about this.

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-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: static files, runserver debug=True

2013-01-17 Thread Tom Evans
On Wed, Jan 16, 2013 at 11:31 PM, Fred Kingham  wrote:
> perfect thanks Javier.
>
> I guess my question should have been phrased, if debug = False, does the
> runserver serve static files  from the STATIC_ROOT. Clearly that's no.
>
> Thanks again.
>
>  Fred

Even with debug=True, runserver does not serve files from STATIC_ROOT,
it dynamically locates them inside your python packages on each
request. This is more expensive, but means you do not need to
constantly keep running collectstatic during development.

Cheers

Tom

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

2013-01-16 Thread Tom Evans
On Wed, Jan 16, 2013 at 10:38 AM, Fred Kingham  wrote:
> not sure if this is the right place to post this, but doesn't this -
>
> https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-in-development
>
> "If using runserver for local development (and the DEBUG setting is True),
> you no longer need to add anything to your URLconf for serving static files
> in development."
>
> contradict this -
>
> https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-in-development
>
> "
>
> To enable this view if you are using some other server for local
> development, you'll add a couple of lines to your URLconf. The first line
> goes at the top of the file, and the last line at the bottom:
>
> from django.contrib.staticfiles.urls import staticfiles_urlpatterns
>
> # ... the rest of your URLconf goes here ...
>
> urlpatterns += staticfiles_urlpatterns()
> "
>
>

No. You've snipped the context in the second extract which makes it
clear that it is not required using runserver:

"""
This view is automatically enabled and will serve your static files at
STATIC_URL when you use the built-in runserver management command.

To enable this view if you are using some other server for local
development, you'll add a couple of lines to your URLconf. The first
line goes at the top of the file, and the last line at the bottom:
"""

Cheers

Tom

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

2013-01-14 Thread Tom Evans
On Sun, Jan 13, 2013 at 8:00 PM, Matt Barry  wrote:
> Hi,
>
> I'm creating a model from an external database that has some encrypted
> columns.  Initially I was thinking of creating a custom field type:
>
> class EncryptedField(models.Field):
>   def db_type(self, connection):
> return 'TEXT'
>   def pre_save(self, model, add):
> return encrypt(getattr(model, self.attname))
>
> ..but it doesn't seem there are any hooks to decrypt the data on the loading
> side.  Am I missing anything, or is there a better way to do this sort of
> thing?
>
> Thanks,
> Matt
>

Hi Matt

get_db_prep_value() is called prior to saving in the database, this is
where you should encrypt the data.
to_python() is called on values loaded from the database, or
deserialised, this is where you should decrypt the data.

https://docs.djangoproject.com/en/dev/howto/custom-model-fields/#converting-database-values-to-python-objects

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-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: "Principle of least privilege" in accessing a DB from an app

2013-01-14 Thread Tom Evans
On Sun, Jan 13, 2013 at 5:05 PM, Isaac Perez
 wrote:
> Hi guys,
>
> I'm creating a new app and I'd like to know how would be the best way to
> implement the principle of least privilege.
> At the moment the DB has 5 users:
>
> 1 is the root user for the DB (which I don't want it to be used by the
> webapp)
> 1 has read access to the data fields
> 1 has write access to the data fields
> 1 has read access to the users table
> 1  has write access to the users table
>
> What I intend to achieve is that if in any occasion we've got a sql
> injection for whatever the reason, the access to the DB from the app form
> will be as limited as possible.
>
> If using python directly I would create a DB connection for each
> functionality so they use the right DB user and have the right permissions.
>
> In Django, though, as you have to configure the default DB access in the
> settings and it has to sync, etc... I'm not sure what will be the best way
> to implement that splitting of privileges.
>
> I've configured the 5 connections in the settings but not sure how to best
> use them for the different functions of authenticate, read and write from
> the DB.
>
> Any ideas?
>

Hi Isaac

Personally I think this is overkill, but you can achieve exactly what
you want by using DB routers to allow Django to select the right DB
connection to use at the right time.

However, what's the point? If your DB router correctly tells Django to
use the "data write" DB handle when saving data fields on an object
loaded from the "data read" DB handle, then it would do so whenever
asked to save an object. So saving objects would always use the write
handle.

In effect, by separating out read and write handles, all you are
protecting against is Django accidentally generating a query to modify
your DB when it is attempting to generate a query to read from your
DB.

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-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: DateTimeField received a naive datetime (2013-01-10 00:00:00) while time zone support is active.

2013-01-11 Thread Tom Evans
On Fri, Jan 11, 2013 at 8:23 AM, Jeff Hsu  wrote:
> Hi all,
>
>I kept getting DateTimeField received a naive datetime (2013-01-10
> 00:00:00) while time zone support is active. but I can't figure out where
> it's receiving a naive datetime.  I have USE_TZ set to True in my setting
> file(stores timezone aware object in mysql?).  My url is as below:
>
> urlpatterns = patterns('django.views.generic.date_based', #add the
> repetitive pattern here
> url(r'^$', 'archive_index', entry_info_dict,
> name='coltrane_entry_archive_index'),
> url(r'^(?P\d{4})/$','archive_year', entry_info_dict,
> name='coltrane_entry_archive_year'),
> url(r'^(?P\d{4})/(?P\w{3})/$','archive_month',
> entry_info_dict,
> name='coltrane_entry_archive_month'),
> url(r'^(?P\d{4})/(?P\w{3})/(?P\d{2})/$','archive_day',
> entry_info_dict,
> name='coltrane_entry_archive_day'),
>
> url(r'^(?P\d{4})/(?P\w{3})/(?P\d{2})/(?P[-\w]+)/$',
> 'object_detail', entry_info_dict, name='coltrane_entry_detail'),
> #the forth arg will this patter a name
>  #[-\w] will match letter, number or a hyphen
> )
>
> Every time I access a detail page from the archive index page, the error
> will pop out.  I'm using generic view to do my detail page, and I can figure
> out what's wrong.  Can anybody give me some direction?
>
> http://dpaste.com/871999/
>
> Thank you,
> Jeff
>

Function based generic views were deprecated in 1.3, TZ support
appeared in 1.4.

When a date based generic view is asked to filter against a
DateTimeField, it takes the specified day, and filters that field is
between datetime.combine(date, time.min) and datetime.combine(date,
time.max). datetime.combine only returns TZ aware datetimes if the
time supplied is TZ aware (time.min/time.max are not).

I suggest you update to use the class based generic views that arrived in 1.3:

https://docs.djangoproject.com/en/1.4/topics/generic-views-migration/

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-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: Execution time of a long process results in an Internal Server Error 500

2013-01-10 Thread Tom Evans
On Thu, Jan 10, 2013 at 1:21 PM, Mauro Sánchez  wrote:
> Hello, I have a process that takes about 2 or 3 minutes to execute. The
> problem is that sometimes (not always) it results in an Internal Server
> Error 500 because of the time it takes.
> Is there a way to configure Apache or mod_wsgi to prevent this? Let's say,
> that even if the process takes 10 or 15 minutes it just keeps running until
> it finish?
> Thanks a lot for the help.
> Cheers,
> Mauro.
>

Providing a URL that consumes an entire web worker for >1 minute is a
good way to open yourself up for a DOS attack - even 10 seconds is too
long really. Put lengthy operations in to a queue - like django-celery
-  so that you can manage how much of your resources that task
consumes, and poll for completion with AJAX.

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-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: How to get self.id when saving a new object?

2013-01-09 Thread Tom Evans
On Wed, Jan 9, 2013 at 12:55 PM, Andre Lopes  wrote:
> Hi,
>
> I'm without a clue on how to get the sef.id when creating a new object
> in Django. I've created a question in StackOverflow. Can someone give
> me a clue on this subject?
>
> Please read the question:
> http://stackoverflow.com/questions/14234917/django-how-to-get-self-id-when-saving-a-new-object
>
> Any clues?

Save the object first.

Cheers

Tom

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

2013-01-09 Thread Tom Evans
On Sat, Dec 29, 2012 at 10:01 PM, Phil  wrote:
> Is it because at the top of my "manage.py" it is pointing to my system wide
> python(#!/usr/bin/env python) instead of my virtualenv one? If so how do I
> fix this? I tried changing the path at the top of the manage.py file but
> didn't seem to do anything.

Just to answer this particular point, the way virtualenv works is by
specifying a different lib location for python libraries.

It does that by using a different python interpreter (the one in
/bin/python) - python looks relative to the binary location
for it's library files.

And it chooses a different python interpreter by putting the directory
that python interpreter is loaded from first in your $PATH environment
variable, so that it is chosen instead of your system python package
by your shell. This happens when you activate your virtualenv.

So, by activating your virtualenv, and running "python manage.py", you
are using the shell's PATH resolution to choose which 'python' binary
will be run, and it will be the one in your virtualenv.

However, even if you had run './manage.py', then the shell would look
at the shebang line, the shebang in this case points at "/usr/bin/env
python". What the env command does is to walk your $PATH environment
variable, looking for the supplied argument as a program - just like a
shell when you run a command - and so that too would have used your
virtualenv.

If you have the virtualenv activated, you can run "pip freeze" to list
all the packages that pip thinks are installed in the virtualenv. This
should give you some more information about whether django is
installed or not. You could also try uninstalling and reinstalling it,
which may fix issues if the original installation was damaged or
interrupted for some reason.

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-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 admin save error: get_db_prep_value() got an unexpected keyword argument 'connection'

2013-01-04 Thread Tom Evans
On Thu, Jan 3, 2013 at 1:51 PM, Glyn Jackson  wrote:
> I really struggling with my understanding of the following issue and how to
> resolve
>
>
> 
>
>
> When I try and save (using the Django standard admin interface) I get the
> following error...
>
>> TypeError at /admin/web/campaign/dc6eb21f-87fa-462f-88af-416cf6be37f6/
>>
>> get_db_prep_value() got an unexpected keyword argument 'connection'
>
>
> Could someone explain this to me, why and maybe a possible solution? I'm
> assuming it is something to do with my custom HibernateBooleanField field.
>

You don't say whether this used to work, or has stopped working, but
the issue is that your custom field is not compatible with Django 1.4
(It's not compatible with any version above 1.1.x).

The fine documentation explains what this method does and what
signature it should have:

https://docs.djangoproject.com/en/1.4/howto/custom-model-fields/#converting-query-values-to-database-values

get_db_prep_value() is supposed to be used to generate DB specific
customizations of the value. If you do not need DB specific
customizations, don't override get_db_prep_value(), override
get_prep_value().

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-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: getting "DateTimeField received a naive datetime" error but have no DateTimeFields

2012-12-17 Thread Tom Evans
On Fri, Dec 14, 2012 at 5:46 PM, bobhaugen  wrote:
> RuntimeWarning: DateTimeField received a naive datetime (2012-12-14
> 17:39:38.878379) while time zone support is active.
>
> This is happening in my tests, but not in normal code.
>
> From dropping a trace in, it looks like it is happening before the test
> setup even runs.
>
> I double-checked my models,  not a DateTimeField in the lot. Nor anywhere
> else in my code except for South migrations, where it is found in
> models['auth.user']. (But I'm not creating any Users in my test code,
> either...)
>
> The tests run ok, but the error messages will be disconcerting to people who
> install my open-source project code.
>
> Any clues?
>
> Thanks.
>

Following the thread I see that you have figured out where and why
this is coming from. There is a simple tip you can use to speed this
up in future, simply run python with warnings set to error, and any
Warnings will be converted into RuntimeErrors - so you get a lovely
stack trace showing exactly how and when the warning was issued.

You can configure python to stop only on certain Warnings, but the
simplest way is to turn all Warnings into Errors:

python -W error manage.py 

Full details on what you can specify with -W here:

http://docs.python.org/2/library/warnings.html#the-warnings-filter

Cheers

Tom

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

2012-12-13 Thread Tom Evans
On Wed, Dec 12, 2012 at 9:32 PM, Chris Cogdon  wrote:
> The BIG advantage here is that you're not checking anything into the SCM
> that must remain secret, or must change (or very likely to change) between
> installations, but all other settings are source controlled.

The big disadvantage is that the configuration of your production
website instances are not in a VCS, you cannot track or merge changes
to them or their ancestors, and if a box goes kabluie, you can't
instantly re-create it. Configuration is code, code lives in a VCS.

(Our configuration files live in a separate repository to the project
or app code, and are finangled into place based upon the hostname)

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-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: IntegerField and SmallIntegerFields maps to the same db type on Oracle.

2012-12-13 Thread Tom Evans
On Thu, Dec 13, 2012 at 4:50 PM, Michał Nowotka  wrote:
> I agree, but if you map SmallIntegerField to say NUMBER(9) you will save
> some space, correct?
>

Oracle may use the exact same datatype underneath for all NUMBER
(speculation). The value in brackets could simply be the default
number of digits presented.

Cheers

Tom

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

2012-12-13 Thread Tom Evans
On Thu, Dec 13, 2012 at 8:24 AM, florian  wrote:
> Hi,
>
> for my project, i hav a mobile_manage.py and a manage.py. Each has its
> specific settings, but has also lots of sommon settings.

Er, why have two versions of manage.py? One of the arguments manage.py
takes is the name of your settings module.

Put all your common settings into 'settings_default.py'.

Add your mobile settings as 'settings_mobile.py' and default as
'settings_default.py'.

In each of them, start the file with 'from settings_default import *'.
Add any overrides or other settings after that.

Run your server with "python manage.py --settings=settings_mobile" (or
"--settings=project.settings_mobile", depending on how your project is
structured.

With mod_wsgi, set the appropriate DJANGO_SETTINGS_MODULE environment variable.

>
> Thus, i've created a common_settings.py and included it in the specific
> settings (settings.py and mobile_settings.py). Howerver, it doesn't work.
>
> There's no error message when i start the server (either with runserver or
> using fcgi/nginx), but when i try to access the homepage i gent an
> "ImproperlyConfigured" error, telling me that django.contrib.contenttypes is
> not in my INSTALLED_APPS. It is in my INSTALLED_APPS and the debugging after
> this error (the settings displayed in the "Request Information" part) show
> that it is really defined correctly.

Use manage.py to open a django shell. Import settings as django would
("from django.conf import settings"). Is contenttypes in
settings.INSTALLED_APPS?


Cheers

Tom

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

2012-12-12 Thread Tom Evans
On Mon, Dec 10, 2012 at 7:41 PM, Marc Aymerich  wrote:
> Hi,
> I'm considering to implement a simple monitorization system that
> basically gathers some data from a set of nodes (<1000 nodes). The
> gathered data should be stored in order to let users perform some
> queries and maybe also generate some graphs.
>
> I'm looking for advice in what components are best suited for each of
> the following parts:
>
> 1) Storage: maybe something nonsql like MongoDB? or perhaps RRD?
> 2) Data gathering: celery periodic tasks?
> 3) Graphs: rrd? or some java script framework for graphing?
>
> thanks for your comments!!

Any reason not to use something like Nagios or Cacti? We use Nagios at
$JOB, it's great.

Cheers

Tom

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

2012-12-11 Thread Tom Evans
On Tue, Dec 11, 2012 at 12:32 PM, psychok7  wrote:
> i need to get my queue back from the worker when i need to add a new task to
> the queue (if it isn't yet executed) in order to keep a FIFO order, i read
> somewhere that i cant do that and that its not a good idea.
>
> do you have a solution? my i am just thinking about this the wrong way,
> please let me know.
>

Hi Nuno

Nik gave you the appropriate solution:

Use named queues with celery:
http://docs.celeryproject.org/en/latest/userguide/workers.html#queues

Start a worker process with a single worker:
http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html#starting-the-worker-process

Set this worker to consume from the appropriate queue:
http://docs.celeryproject.org/en/latest/userguide/workers.html#queues-adding-consumers

There is no simple example showing exactly what you want, because it's
a little strange - normally you use celery to scale out, this
purposefully restricts the scale - so you will have to do some
investigation and trial and error.

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-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: Loading XSD file into memory ONCE

2012-12-10 Thread Tom Evans
On Sun, Dec 9, 2012 at 8:05 AM, Dwayne Ghant  wrote:
> Hello All,
>
> I will be short and sweet.  I have a simple (well at least I think it's
> simple) question.  First let me explain,  I'm writing a RESTful webservice
> that uses validates xml submissions using an xsd (440kb in size),
> pre-defined, schema.  I would, idealistically, like to bootstrap the schema
> into memory so that it's not being requested every time the web service is
> requested.  What's the best way to do this?  A brief google search yielded
> the results below
> (http://stackoverflow.com/questions/11159077/python-load-2gb-of-text-file-to-memory):
>
> import mmap
>
> with open('dump.xml', 'rb') as f:
>   # Size 0 will read the ENTIRE file into memory!
>   m = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ) #File is open read-only
>
>   # Proceed with your code here -- note the file is already in memory
>   # so "readine" here will be as fast as could be
>   data = m.readline()
>   while data:
> # Do stuff
> data = m.readline()
>
>
> Will this work? Will this make the file only load once into memory?
>

No - not if you run that code on every (applicable) request. Ignore
the cost of reading it from disk - if you read a file from disk
repeatedly, even the worst OS should start to cache that file - the
actual cost is repeatedly re-parsing the XML document.

What you want to do is cache the resulting object, the parsed XML
document. An easy way to do this is by using a global:

__xsd_cache = None
def get_xsd():
  global __xsd_cache
  if __xsd_cache is None:
__xsd_cache = parse_xsd()
  return __xsd_cache

def parse_xsd():
  ...

The only problem with caching is that eventually, what is cached is no
longer correct. You will need to think about how and when you will/can
invalidate the cache.

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-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: Set Permissions in User model from views

2012-12-06 Thread Tom Evans
On Thu, Dec 6, 2012 at 8:10 AM, Nikhil Verma  wrote:
> Hi All
>
> I am developing a simple app in which i have to play with user permissions.I
> register a user(during a sign up process)  with this method :-
>
> def register_user(data):
> """
> This method is used to register a new user and create a user profile.
> """
> password = hashlib.sha1(data['confirm_password']).hexdigest()
>
> new_user = User(username=data['email'], email=data['email'],
> is_staff=True
> )
> new_user.set_password(data['confirm_password'])
> # At this point i want to add user_permissions ! How can i do this ?
> new_user.user_premissions.add('can add table_name') @ Since it is a
> manytomany field
>
>How can i set permissions from this part of code ?
> new_user.save()
>
>
>
>
> new_user.first_name = data['title']
> new_user.email = data['email']
> new_user.is_locked = True
> new_user.save()
> new_user.user_permissions('Can add department')
>
> profile = new_user.profile
> key = uuid.uuid4().__str__()
> profile.key = key
> profile.save()
> if new_user and profile:
> return new_user
> else:
> return False
>
> Thanks in advance
>
>
>

Permissions are just objects, fetch them from the database and add
them to the M2M:

>>> from django.contrib.auth.models import Permission, User

>>> user = User.objects.get(id=1)
>>> perm = Permission.objects.get(codename='add_user')
>>> user.user_permissions.add(perm)
>>> user.user_permissions.all()
[]
>>> user.has_perm('auth.add_user')
True

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-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 + fastcgi + lighttpd outlog and errlog not working

2012-12-05 Thread Tom Evans
On Wed, Dec 5, 2012 at 6:44 AM, Gontran Magnat  wrote:
> So you mean there is no way to get this kind of log with fastcgi mode:
>

There is always a way, it just doesn't do it by default. If you
require this output even in fastcgi mode than you can create a trivial
middleware to print this output to whatever log you want.

Normally, people use the logging facilities of whatever is hosting the
fastcgi app to create a request log, eg Apache or nginx.

Cheers

Tom

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

2012-11-30 Thread Tom Evans
On Fri, Nov 30, 2012 at 6:45 PM, Mo J. Al-Mughrabi
 wrote:
> Hi,
>
> I've been trying to resolve this issue for a day without luck, its
> very strange error, i tried to post it on stackoverflow but still no
> luck.
>
>
> http://stackoverflow.com/questions/13629099/getting-cannot-identify-image-file-when-trying-to-create-thumbnail-in-django
>

Does it still crash if you fix the double commit?

instance = super(ImageForm, self).save(commit=False)

You shouldn't save it at all if commit=False was passed, and only save
it once if commit=True was passed.

Seeing the traceback may be informative too - sanitize it if needs be.

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-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: Drop foreign key, add another - keep data

2012-11-30 Thread Tom Evans
On Fri, Nov 30, 2012 at 11:56 AM, Peter Edström  wrote:
> Hello,
>
> I'd like to drop a ForeignKey-field and add another using south (mysql
> database), but it won't work. Googling it takes me not far, but it seems to
> be a problem with dropping foreign key constraints with InnoDB.
> What is the recommended way ot dropping a ForeignKey-field, and adding
> another?
>
> Say the model looks like this:
>
>> class Model1(models.Model):
>>
>> test = models.ForeignKey(Model2)
>
>
> And I won't to change it to:
>
>> class Model1(models.Model):
>>
>> test2 = models.ForeignKey(Model3)
>
>
> Right now I don't really care if I lose data, but for future reference I'd
> prefer a method that keeps it.
>
> Thank you.
>

How are you trying to do it? There should be several migrations:

1) A schema migration to add the new foreign key, which should be
nullable at this point
2) A data migration to move the old data into the new column
3) A schema migration to drop the nullability of the new foreign key
4) A schema migration to drop the old foreign key

You may not need as many migrations if you do not need to migrate the
old data over, or if the new foreign key is allowed to be null.

Cheers

Tom

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

2012-11-29 Thread Tom Evans
On Thu, Nov 29, 2012 at 6:00 PM, Sammy  wrote:
> Hello django experts
> I am unable to get my static files to work.  Here are my settings:
>
> projectfiles
> |
> |-myproject
> | |
> | |-static
> | | |
> | | |-css
> | | |-js
> | |-__init__.py
> | |-settings.py
> | |-urls.py
> | |-wsgi.py
> |
> |-myapp
> |
> |-templates
>
>
> +++
> 
>
>
> settings.py
> import os
> SITE_ROOT = (os.path.realpath(os.path.dirname(__file__))).replace('\\','/')
> DEBUG = True
> MEDIA_ROOT = (os.path.join(SITE_ROOT, '/static')).replace('\\','/')
> MEDIA_URL = '/static/'
> STATIC_ROOT = ''
> STATIC_URL = ''

I think you are confused about MEDIA and STATIC. MEDIA is where files
are uploaded to by users, STATIC is where files are served from, the
_ROOT postfix denotes a directory path, the _URL postfix a URL path.

So you should have STATIC_ROOT=os.path.join(...) and STATIC_URL='/static/'

> STATICFILES_DIRS = ()
> STATICFILES_FINDERS = (
> 'django.contrib.staticfiles.finders.FileSystemFinder',
> 'django.contrib.staticfiles.finders.AppDirectoriesFinder',
> 'django.contrib.staticfiles.finders.DefaultStorageFinder',
> )
>

But do you have the staticfiles app in INSTALLED_APPS?

> +
> +
>
>
> urls.py
> urlpatterns = patterns('',
> (r'^myurl/$', myview),
> )
>
>
> from myproject.settings import DEBUG

You should always import settings like this:

from django.conf import settings
if settings.DEBUG

https://docs.djangoproject.com/en/1.4/topics/settings/#using-settings-in-python-code

(It's really important actually, it can cause hard to find bugs!)

> if DEBUG:
> urlpatterns += patterns('', (r'^static/(?P.*)$',
> 'django.views.static.serve',
>
> {'document_root': 'static'}))

This is not needed if you are using runserver in development, if you
are not using runserver, then it is better to use the shortcut methods
provided

https://docs.djangoproject.com/en/1.4/howto/static-files/#serving-static-files-in-development

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-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: how to use named urls from apps

2012-11-29 Thread Tom Evans
On Thu, Nov 29, 2012 at 2:32 PM, Mike  wrote:
> I'm trying to use the url template tag to call the login view from
> contrib.auth.  I've tried the following but none work:
>
> {% url login %}
> {% url auth:login %}
> {% url auth.login %}
> {% url contrib.auth.login %}
>
> Can someone enlighten me please?
> Mike
>

Named urls are URLs defined in your urlconf that have named views. The
contrib auth app, although it provides a bunch of views, does not
automatically install any of them at any URLs, hence this would fail.

If you include the login view in one of your urlconfs, it will not
have the 'auth' app label, it will have whatever name you decide to
give it.

Cheers

Tom

PS: The fully qualified view name may have worked -
"django.contrib.auth.views.login". There is a function at
"django.contrib.auth.login", but that function is used to actually log
users in, not to present a login form and process 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-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: Error: No module named books

2012-11-29 Thread Tom Evans
On Thu, Nov 29, 2012 at 4:51 AM, Chris Recher
 wrote:
> Hi all,
>
> I'm working through the Django book and I've run into an error that wasn't
> predicted. I've got a project called mysite. I used "python manage.py
> startapp books" to create an app called books inside of it. I added a few
> models to the models.py file inside books, then tried to use "python
> manage.py validate". I got "Error: No module named books" in return.
> __init__.py is perfectly intact in both the second mysite directory and the
> books directory. I've added mysite.books to INSTALLED_APPS. All the results
> I could find searching for this problem deal with someone that's made a
> spelling mistake somewhere. I've been through my files multiple times, and
> my spelling is pristine. I figure I'm making an obvious, beginner's mistake
> - could anyone help?
>

Hi Chris

First hint, newlines are free to use! Consider some next time!

Second, Django is an evolving framework. It helps to know what version
you are using.

Finally, launch the django shell ("python mange.py shell" instead of
"python manage.py runserver").
Try to import your module - "import mysite.books" - does it work?
If it doesn't, does this work? - "import books"

Cheers

Tom

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

2012-11-29 Thread Tom Evans
On Thu, Nov 29, 2012 at 1:01 PM, Jirka Vejrazka
 wrote:
>> I'm just facing a problem with little longer runnig SQL select command,
>> and DJago framework returns a "504 Gateway Timeout" after aprox 10 seconds.
>> My sql command is executed on Oracle SQL database through
>> "django.db.backends.oracle" driver.
>
> You'd have to change multiple timeouts to make this work. There are several
> approaches in similar situations, pick what suits your situation (which you
> have not described in detail).

Not that many; django itself has no timeouts, so you only need to
adjust the timeouts on your http server. Normally there are several
that apply - a timeout between writes, a timeout for the total
response time, etc. This timeout is happening due to timeout between
writes, so adjusting that one first and seeing where you go would be a
start.

>
>   - calculate data *before* user requests it and keep the calculated copy
>   - caching of any data that takes long to compute (retrieve) - can and
> should be combined with above
>   - using asyncronous queries, typically achived via celery (django-celery)
> and some AJAX calls
>

You missed 'just increase the timeouts', which is architecturally
simpler than any of those options, and may easily fit within the
desired performance for the app - only the OP can know that though.

It is also possible that your query could be optimised. Have you
analysed the query yet? Could additional indices be added to speed up
this particular query?

Cheers

Tom

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

2012-11-29 Thread Tom Evans
On Thu, Nov 29, 2012 at 11:58 AM, bikeridercz  wrote:
> Dear all,
>
> I'm just facing a problem with little longer runnig SQL select command, and
> DJago framework returns a "504 Gateway Timeout" after aprox 10 seconds. My
> sql command is executed on Oracle SQL database through
> "django.db.backends.oracle" driver.
>
> Unfortunately I'm not able to find a place where to change the timeout.
>
> Please help.
>
> Thanks and Regards.
>

The timeout comes from your web server, not Django. I think this error
is from nginx + FastCGI (I know it is not Apache :)

http://wiki.nginx.org/HttpFastcgiModule#fastcgi_send_timeout

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-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: Where to put PDF files + how to authenticate the urls requesting them

2012-11-29 Thread Tom Evans
On Thu, Nov 29, 2012 at 11:30 AM, Loai Ghoraba  wrote:
> I am still new to sreving stuff (in fact I know barely anything about it :))
> Then you instruct to have something like this
>
> url(r'^media/(?P.*)$', 'myview,func', {
> 'document_root': MEDIA_ROOT,
> }),
>
> and my func have the instructions to the real web servers ?

Read up on X-Sendfile and if anything doesn't make sense, ask some
questions on here.

http://stackoverflow.com/questions/7296642/django-understanding-x-sendfile

>
> And another question: Does this applies also to light static files like css
> and javascript ?

It applies to any file you want to control access to via django.

Cheers

Tom

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-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: Where to put PDF files + how to authenticate the urls requesting them

2012-11-29 Thread Tom Evans
On Wed, Nov 28, 2012 at 6:27 PM, Loai Ghoraba  wrote:
> Thanks for the reply, but I am still new to the web technology world, so I
> would like to fully use Django now before , moving to another ways to host
> my files.
> Actually I am totally new to serving stuff, so if there is some best
> practice or that my way is totally wrong, please tell me.
>
> So in short: is there a way to provide some kind of authentication against
> /static/whatever urls ? Because I want Django to host the file now
> Also,  assuming I found someway to do this, django says that to mark a file
> as downloadable, we can do this
>
> https://docs.djangoproject.com/en/dev/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment
>
 response = HttpResponse(my_data,
 content_type='application/vnd.ms-excel')
 response['Content-Disposition'] = 'attachment; filename="foo.xls"'
>
>
> Now what is the type of my_data? any file object ?
>

A string, or any file like object - it's just like any HttpResponse.

You do not want to do this though, using Django to download static
files is very wasteful. Others have pointed out solutions where you
use django to authenticate the request, and then instruct your web
server (eg Apache, nginx) to serve the correct file, which will be an
order of magnitude more efficient.

Django is never served by itself, there should always be a real web
server in front of it.

Cheers

Tom

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



<    1   2   3   4   5   6   7   8   9   10   >