best way to design poll and choice form for multiple choice entries

2008-11-24 Thread Kevin

Starting from the tutorial, I figured a good first exercise would be
to create a front-facing form for creating a poll question and
choices. I've successfully done it, but I'd like the implementation of
it to be closer to the functionality of the admin interface for adding
and removing choices.

I've got a button called "Add Choice" and when clicked the choice is
added, but it's also validated at the same time even though I'm not
saving anything. So there are errors when the button is clicked no
matter what.

I checked out the code the template code for the admin interface and
the sheer number of variables and tags makes it daunting to replicate.
I also saw that it used Formsets but when I tried to use a Formset I
couldn't create blank choices, or delete choices, etc.

Can anyone guide me here? Where should I start? Should I use Forms or
Formsets? Or should I forget Django's forms altogether? I know it can
be done because the Admin interface does it--am I just making it
harder than it is?

All guidance is appreciated.



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



front facing poll form issues

2008-12-26 Thread Kevin

I'd like to create a front facing poll creation form that can
automatically handle deletion, reordering of choices.

I believe formsets are the easiest way to accomplish this. I start
with 3 choices and want to allow the user to add more.

Check the following code:

def create(request):

numchoices = 3 #default number of choices to display

if request.method == "POST":

questionform = QuestionForm(request.POST, instance=Question(),
prefix='question')
ChoiceFormSet = formset_factory(ChoiceForm, 
extra=int(request.POST
['numchoices']), max_num=10, can_order=True, can_delete=True)
choiceformset = ChoiceFormSet(request.POST, prefix='choice')

if request.POST['submit_action'] == "Add Choice":
 pass
...
else:
questionform = QuestionForm(prefix='question')
ChoiceFormSet = formset_factory(ChoiceForm, extra=numchoices,
max_num=10, can_order=True, can_delete=True)
choiceformset = ChoiceFormSet(prefix='choice')

return render_to_response(
  'create.html',
  
{'questionform':questionform,
 
'choiceformset':choiceformset,
  },
  context_instance = 
RequestContext(request),
  )


My questions are as follows:

1. How can I get a choice to be added if there is data present? I know
it has something to do with the management_form but I am unclear on
how to increment TOTAL-FORMS and INITIAL-FORMS in the management_form
or if I even need to. Anyhow, whenever I call ChoiceFormSet
(request.POST) a new blank choice is NEVER added, and if I leave out
request.POST, the extra choice form is added but all user input is
lost!

2. How are reordering and deleting choices processed? If I have a
submit action called, "Delete choices," what do I have to do in my
python code to actually get them off the form? Same with reordering.
Is this handled automatically?

3. Is there any way to get initial data in the ordering box on the
form? This would be done in the template, I imagine.

4. Are formsets the best way to do this or should I be doing
everything some other way? I am currently saving the Question and the
Choices at the same time--so the Question doesn't officially exist
until everything is saved at once.

I've been experimenting with this on and off for a while and cannot
find much good information on it. I highly appreciate any guidance!
--~--~-~--~~~---~--~~
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: front facing poll form issues

2008-12-27 Thread Kevin

No one has offered any help. That's fine, so let me ask my question
differently.

Can anyone point me to an example of form processing for formsets?
Let's say can_delete=True, how do I process that in my code?

I have scoured google and can find no examples, so any examples/links
would be appreciated.
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-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
-~--~~~~--~~--~--~---



ensuring a string does not get escaped in views.py

2008-10-17 Thread Kevin

All,

I am new to Python and Django. I'm quickly catching on but have
finally run in to my first issue.

I'm building a simple app that will work with Google's Picasa. The
idea is to copy an album from one account to another, something that
Picasa won't let you do in its interface.

Here's the thing--I have this working within the Python shell, but
can't make it work with Django.

To retrieve an Album from Picasa, the code looks something like this:
album_uri_to_copy = request.POST['album_uri']
gclient1 = gdata.photos.service.PhotosService()
gclient1.ClientLogin( guser1, gpassword1 )
album_feed = gclient1.GetFeed(album_uri_to_copy)

And album_uri_to_copy might look like:
http://www.ggpht.com//data/feed/api/user/someuser/album?id=4rdioE_s&kind=photo

When calling:
album_feed = gclient1.GetFeed(album_uri_to_copy)

from a Python shell it works fine. When calling it from Django it
returns an Exception saying that album_uri_to_copy isn't a valid uri
or atom feed (this is a google error message).

I SUSPECT that the & is getting changed to "&". The thing is, I've
used {{ album_uri|safe }} in my template, so album_uri_to_copy should
be safe! I'm thinking that Django is interfering with the
album_uri_to_copy string in the GetFeed() call.

Can anyone give me some troubleshooting options?

Thanks!

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



I need to get psycopg2 installed on Mac OS X 10.5

2009-07-14 Thread Kevin

I need to get psycopg2 installed on Mac OS X 10.5

I have read every install guide I could find and I still do not have
it working. I have developer tools installed. I am running MacPython
2.6.2 and PostgreSQL 8.4 downloaded from 
http://www.enterprisedb.com/products/pgdownload.do

On my production machine (Debian) I did a simple atp-get and it
worked. Why is it so much harder on Mac OS X?  I am very near ripping
my hair out because I have wasted too much time and I do not
understand why psycopg2 does not work on my machine.

Below are my notes from three attempts to install psycopg2.  I have
read other threads that suggest installing Python, PostgreSQL, and
psycopg2 from MacPorts.  I do not want to use MacPorts.  I do not see
why I need to use a completely different installation of Python to use
a simple database driver.



For my first attempt I followed the instructions listed here:
http://jasonism.org/weblog/2008/nov/06/getting-psycopg2-work-mac-os-x-leopard/
It told me to add these lines to setup.cfg:

include_dirs=/Library/PostgreSQL/8.3/include
library_dirs=/Library/PostgreSQL/8.3/lib

I then ran python setup.py build and got this error:

$ python setup.py build
running build
running build_py
creating build
creating build/lib.macosx-10.3-fat-2.6
creating build/lib.macosx-10.3-fat-2.6/psycopg2
copying lib/__init__.py -> build/lib.macosx-10.3-fat-2.6/psycopg2
copying lib/errorcodes.py -> build/lib.macosx-10.3-fat-2.6/psycopg2
copying lib/extensions.py -> build/lib.macosx-10.3-fat-2.6/psycopg2
copying lib/extras.py -> build/lib.macosx-10.3-fat-2.6/psycopg2
copying lib/pool.py -> build/lib.macosx-10.3-fat-2.6/psycopg2
copying lib/psycopg1.py -> build/lib.macosx-10.3-fat-2.6/psycopg2
copying lib/tz.py -> build/lib.macosx-10.3-fat-2.6/psycopg2
running build_ext
error: No such file or directory


===


For my next attempt I followed the instructions listed here:
http://blog.jonypawks.net/2008/06/20/installing-psycopg2-on-os-x/
It told me to run this:

PATH=$PATH:/Library/PostgresPlus/8.3/bin/ sudo easy_install psycopg2

This resulted in this error: (I substituted "8.4" for "8.3" because my
version of PostgreSQL is newer)

$ PATH=$PATH:/Library/PostgreSQL/8.4/bin/ sudo easy_install psycopg2
Password:
Searching for psycopg2
Reading http://pypi.python.org/simple/psycopg2/
Reading http://initd.org/projects/psycopg2
Reading http://initd.org/pub/software/psycopg/
Best match: psycopg2 2.0.11
Downloading http://initd.org/pub/software/psycopg/psycopg2-2.0.11.tar.gz
Processing psycopg2-2.0.11.tar.gz
Running psycopg2-2.0.11/setup.py -q bdist_egg --dist-dir /tmp/
easy_install-dUXtsI/psycopg2-2.0.11/egg-dist-tmp-1008XV
warning: no files found matching '*.html' under directory 'doc'
warning: no files found matching 'MANIFEST'
/usr/libexec/gcc/i686-apple-darwin9/4.0.1/as: assembler (/usr/bin/../
libexec/gcc/darwin/i386/as or /usr/bin/../local/libexec/gcc/darwin/
i386/as) for architecture i386 not installed
/usr/libexec/gcc/powerpc-apple-darwin9/4.0.1/as: assembler (/usr/
bin/../libexec/gcc/darwin/ppc/as or /usr/bin/../local/libexec/gcc/
darwin/ppc/as) for architecture ppc not installed
Installed assemblers are:
/usr/bin/../libexec/gcc/darwin/ppc64/as for architecture ppc64
/usr/bin/../libexec/gcc/darwin/x86_64/as for architecture x86_64
Installed assemblers are:
/usr/bin/../libexec/gcc/darwin/ppc64/as for architecture ppc64
/usr/bin/../libexec/gcc/darwin/x86_64/as for architecture x86_64
lipo: can't open input file: /var/tmp//ccSK6sd7.out (No such file or
directory)
error: Setup script exited with error: command 'gcc' failed with exit
status 1
Exception TypeError: TypeError("'NoneType' object is not callable",)
in > ignored
Exception TypeError: TypeError("'NoneType' object is not callable",)
in > ignored


===


For my third attempt I installed the binary of psycopg2 from
http://pythonmac.org/packages/py25-fat/index.html
I thought it worked, but when I tried to import the module in the
interpreter I got this error:

>>> import psycopg2
Traceback (most recent call last):
  File "", line 1, in 
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/
python2.6/site-packages/psycopg2/__init__.py", line 60, in 
from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/
lib/python2.6/site-packages/psycopg2/_psycopg.so, 2): Library not
loaded: /usr/local/pgsql/lib/libpq.4.dylib
  Referenced from: /Library/Frameworks/Python.framework/Versions/2.6/
lib/python2.6/site-packages/psycopg2/_psycopg.so
  Reason: image not found





What the hell do I need to do to get psycopg2 working with my
MacPython 2.6.2 install?  Sorry if I sound angry, but I have lost a
lot of time on something that seems like it should be easy.

--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django use

Re: I need to get psycopg2 installed on Mac OS X 10.5

2009-07-14 Thread Kevin

Thanks a lot Juan!  It works fine on my machine.  Would you be able to
share your compilation steps?

On Jul 14, 7:32 am, Juan Pablo Romero Méndez 
wrote:
> I don't know if it will run in your machine, but here is one compiled
> for Python2.5, MacOS X 10.5.7, and PostgreSQL 8.3.
>
> Regards,
>
>   Juan Pablo
>
> 2009/7/14 Kevin :
>
>
>
>
>
> > I need to get psycopg2 installed on Mac OS X 10.5
>
> > I have read every install guide I could find and I still do not have
> > it working. I have developer tools installed. I am running MacPython
> > 2.6.2 and PostgreSQL 8.4 downloaded 
> > fromhttp://www.enterprisedb.com/products/pgdownload.do
>
> > On my production machine (Debian) I did a simple atp-get and it
> > worked. Why is it so much harder on Mac OS X?  I am very near ripping
> > my hair out because I have wasted too much time and I do not
> > understand why psycopg2 does not work on my machine.
>
> > Below are my notes from three attempts to install psycopg2.  I have
> > read other threads that suggest installing Python, PostgreSQL, and
> > psycopg2 from MacPorts.  I do not want to use MacPorts.  I do not see
> > why I need to use a completely different installation of Python to use
> > a simple database driver.
>
> > For my first attempt I followed the instructions listed here:
> >http://jasonism.org/weblog/2008/nov/06/getting-psycopg2-work-mac-os-x...
> > It told me to add these lines to setup.cfg:
>
> > include_dirs=/Library/PostgreSQL/8.3/include
> > library_dirs=/Library/PostgreSQL/8.3/lib
>
> > I then ran python setup.py build and got this error:
>
> > $ python setup.py build
> > running build
> > running build_py
> > creating build
> > creating build/lib.macosx-10.3-fat-2.6
> > creating build/lib.macosx-10.3-fat-2.6/psycopg2
> > copying lib/__init__.py -> build/lib.macosx-10.3-fat-2.6/psycopg2
> > copying lib/errorcodes.py -> build/lib.macosx-10.3-fat-2.6/psycopg2
> > copying lib/extensions.py -> build/lib.macosx-10.3-fat-2.6/psycopg2
> > copying lib/extras.py -> build/lib.macosx-10.3-fat-2.6/psycopg2
> > copying lib/pool.py -> build/lib.macosx-10.3-fat-2.6/psycopg2
> > copying lib/psycopg1.py -> build/lib.macosx-10.3-fat-2.6/psycopg2
> > copying lib/tz.py -> build/lib.macosx-10.3-fat-2.6/psycopg2
> > running build_ext
> > error: No such file or directory
>
> > ===
>
> > For my next attempt I followed the instructions listed here:
> >http://blog.jonypawks.net/2008/06/20/installing-psycopg2-on-os-x/
> > It told me to run this:
>
> > PATH=$PATH:/Library/PostgresPlus/8.3/bin/ sudo easy_install psycopg2
>
> > This resulted in this error: (I substituted "8.4" for "8.3" because my
> > version of PostgreSQL is newer)
>
> > $ PATH=$PATH:/Library/PostgreSQL/8.4/bin/ sudo easy_install psycopg2
> > Password:
> > Searching for psycopg2
> > Readinghttp://pypi.python.org/simple/psycopg2/
> > Readinghttp://initd.org/projects/psycopg2
> > Readinghttp://initd.org/pub/software/psycopg/
> > Best match: psycopg2 2.0.11
> > Downloadinghttp://initd.org/pub/software/psycopg/psycopg2-2.0.11.tar.gz
> > Processing psycopg2-2.0.11.tar.gz
> > Running psycopg2-2.0.11/setup.py -q bdist_egg --dist-dir /tmp/
> > easy_install-dUXtsI/psycopg2-2.0.11/egg-dist-tmp-1008XV
> > warning: no files found matching '*.html' under directory 'doc'
> > warning: no files found matching 'MANIFEST'
> > /usr/libexec/gcc/i686-apple-darwin9/4.0.1/as: assembler (/usr/bin/../
> > libexec/gcc/darwin/i386/as or /usr/bin/../local/libexec/gcc/darwin/
> > i386/as) for architecture i386 not installed
> > /usr/libexec/gcc/powerpc-apple-darwin9/4.0.1/as: assembler (/usr/
> > bin/../libexec/gcc/darwin/ppc/as or /usr/bin/../local/libexec/gcc/
> > darwin/ppc/as) for architecture ppc not installed
> > Installed assemblers are:
> > /usr/bin/../libexec/gcc/darwin/ppc64/as for architecture ppc64
> > /usr/bin/../libexec/gcc/darwin/x86_64/as for architecture x86_64
> > Installed assemblers are:
> > /usr/bin/../libexec/gcc/darwin/ppc64/as for architecture ppc64
> > /usr/bin/../libexec/gcc/darwin/x86_64/as for architecture x86_64
> > lipo: can't open input file: /var/tmp//ccSK6sd7.out (No such file or
> > directory)
> > error: Setup script exited with error: command 'gcc' failed with exit
> > status 1
> > Exception TypeError: TypeError("'NoneType' object is not callable",)
> > in  > 0x9e3910>> ignore

Re: I need to get psycopg2 installed on Mac OS X 10.5

2009-07-27 Thread Kevin

I have gotten psycopg2 to compile though in a roundabout way.  I have
tried to compile Python from source and got other errors.  Although I
already had Xcode installed, I decided that it couldn't hurt to
reinstall it and see what happens.  After doing so, I was able to
compile Python without any problems; go figure =).  Then using my new
install of Python and exporting the path to PostgreSQL, compiling
psycopg2 went smoothly.

On Jul 16, 9:46 am, Dave Everitt  wrote:
> I've just done this after installing Postgresql (BTW and letting it
> mess with my OS X memory settings):
>
> Added path to .bash_login (or .bash_profile)
> export PATH="/Library/PostgreSQL/8.4/bin:$PATH"
>
> sudo easy_install psycopg2
> Password:
> Searching for psycopg2
> Readinghttp://pypi.python.org/simple/psycopg2/
> Readinghttp://initd.org/projects/psycopg2
> Readinghttp://initd.org/pub/software/psycopg/
> Best match: psycopg2 2.0.11
> Downloadinghttp://initd.org/pub/software/psycopg/psycopg2-2.0.11.tar.gz
> Processing psycopg2-2.0.11.tar.gz
> Running psycopg2-2.0.11/setup.py -q bdist_egg --dist-dir /tmp/
> easy_install-jTbWWk/psycopg2-2.0.11/egg-dist-tmp-9HFHuM
> warning: no files found matching '*.html' under directory 'doc'
> warning: no files found matching 'MANIFEST'
> zip_safe flag not set; analyzing archive contents...
> Adding psycopg2 2.0.11 to easy-install.pth file
>
> Installed /Library/Frameworks/Python.framework/Versions/2.6/lib/
> python2.6/site-packages/psycopg2-2.0.11-py2.6-macosx-10.3-i386.egg
> Processing dependencies for psycopg2
> Finished processing dependencies for psycopg2
>
> python
>
> >>>import psycopg2
>
> Success?
--~--~-~--~~~---~--~~
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
-~--~~~~--~~--~--~---



TypeError: execute() takes at most 3 arguments (4 given)

2009-08-22 Thread kevin

cursor.execute("SELECT a,b,c FROM Table_Name WHERE a = %s AND b = %s ",
[string1],[string2])

gives me the following error:

TypeError: execute() takes at most 3 arguments (4 given)

Where did i go wrong?

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



Can't build Django documentation

2010-08-13 Thread Kevin
I tried to build the Django docs and got an error.

$ cd django/docs/
$ make html
sphinx-build -b djangohtml -d _build/doctrees   . _build/html
Running Sphinx v1.0.1
loading pickled environment... not yet created
building [djangohtml]: targets for 427 source files that are out of
date
updating environment: 427 added, 0 changed, 0 removed
/Users/haitran/Desktop/obnob_project/src/django_docs/_ext/
djangodocs.py:91: DeprecationWarning: xfileref_role is deprecated, use
XRefRole
  xrefs = sphinx.roles.xfileref_role('ref', linktext, linktext,
lineno, state)
reading sources... [ 73%] ref/contrib/gis/
commands
Exception occurred:
  File "/Users/src/django_docs/_ext/djangodocs.py", line 215, in
parse_django_adminopt_node
from sphinx.directives.desc import option_desc_re
ImportError: No module named desc
The full traceback has been saved in /var/folders/od/
odl44I41FT0yZPHQw8kT8E+++TM/-Tmp-/sphinx-err-RgDvku.log, if you want
to report the issue to the developers.
Please also report this if it was a user error, so that a better error
message can be provided next time.
Either send bugs to the mailing list at ,
or report them in the tracker at . Thanks!
make: *** [html] Error 1

The process fails when it tries to do an import:

from sphinx.directives.desc import option_desc_re

Why is there no module named desc?

I am using:
Python 2.6
Sphinx 1.0.1
Django 1.2.1
Mac OS X 10.5.8

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



Re: Can't build Django documentation

2010-08-18 Thread Kevin
Thanks for that info.  I downgraded to Sphinx 0.6.6 and all is well.

On Aug 14, 11:14 am, Ramiro Morales  wrote:
> On Sat, Aug 14, 2010 at 9:07 AM, DrBloodmoney  wrote:
>
> > The docs [0] mention an incompatibility with the currently released
> > Sphinx. I can't build right now either, and I'm too lazy to install
> > Sphinx from source.
>
> > [0]http://docs.djangoproject.com/en/dev/intro/whatsnext/#as-html-locally
>
> That's and outdated and misleading note. Thanks for pointing it. I' ve
> opened ticket 14111 to get rid of it.
>
> --
> Ramiro Morales  | http://rmorales.net

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



Ability to use PSP templates with Django?

2010-08-21 Thread Kevin
I come from the world of mod_python and really enjoyed the PSP
template system, where I can embed Python code directly in my template
for dynamically generating menus and such.

What is the recommended method of calling a PSP template from inside
Django and rendering it?

Here is a sniplet of code I am trying to convert over to the Django
template engine, but cannot figure out the best method:

for name, text, url in menu_items:
attr = ""
if name == hlight:
attr = "class='highlight'"
# begin
%>
><%=text%>
<%
# end
%>

And yes, this menu code is from the mod_python example site.  Also
does Django include an example fully working site to display most, if
not all of it's abilities?  The example site which mod_python includes
is very simple, but is a great starting point for a website.

mod_python's example site is here:  http://modpython.org/examples/

I really think having such an example for django would be good as
well.  I am actually in the process of basically re-creating this
example site in django to learn how django works and how it differs
from mod_python coding.

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



Trouble comparing variables in a view

2010-08-21 Thread Kevin
I have attempted to troubleshoot this myself with no luck and am very
confused why a simple IF statement is not working.  I have used if
statements in python before and never had such a problem.  I am rather
glad to see that PRINT outputs to the console, this helps a bit for
troubleshooting.  Variable information:

client_id = Comes in from a views request... def
view_client(request,client_id):
c.id = Comes in from a database model.

-- code --
print "%s - %s" % (str(client_id),str(c.id))
if str(client_id) == str(c.id):
-- end --

The console output, displays 3 - 3 as plain as a day, this is why I am
very confused on why it is not resolving.  The logic always resolves
as False, which should resolve as True.  I came to the conclusion that
both objects were different by using dir() and printing it out to the
console, hence the reason I now placed both objects inside a str() in
hopes it may work, but alas, it does not.  If I put it as 3 == 3, it
resolves as True.  Any ideas?  Placed in str() along with dir(), both
objects are now equal, but the IF statement sees otherwise.

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



Re: newbie question: generating javascript, avoiding trailing comma

2007-07-19 Thread Kevin

There's a forloop.last variable that you could test.  Eg:
var crimes =  [
 {% for crime in crime_list %}
 [ {{crime.longitude}},
{{ crime.latitude }},'{{ crime.address }}','{{ crime.type }}','{{ crime.date 
}}']
{% if not forloop.last %},{% endif %}
 {% endfor %}
];

On Jul 19, 12:35 pm, cjl <[EMAIL PROTECTED]> wrote:
> DU:
>
> I am a newbie, and I'm working on a simple tutorial for other
> newbies.  I am trying to generate some javascript, and I have the
> following code in my template:
>
> var crimes =  [
>  {% for crime in crime_list %}
>  [ {{crime.longitude}},
> {{ crime.latitude }},'{{ crime.address }}','{{ crime.type }}','{{ crime.date 
> }}'],
>  {% endfor %}
> ];
>
> When this template is rendered to a webpage, I can get something like
> the following:
>
> var crimes = [
> [-78.817828,42.904851,'17 Rapin
> Place','homicide','2006-01-05'],
> [-78.889458,42.897707,'155 Pennsylvania
> Street','homicide','2006-04-17'],
> [-78.884766,42.915257,'446 West
> Ferry','homicide','2006-01-10'],
> ];
>
> This is fine, but I think the trailing comma in the final array item
> is causing a javascript error in IE. Is there a way to rewrite my
> template code to avoid the trailing comma?
>
> Thanks in advance,
> cjl


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



Add Support for Hex numbers is Admin

2007-09-19 Thread Kevin

In the admin interface if someone enters a number in hex, then it
fails the validation test. I've managed to make it pass the validation
test, but now the number gets passed in hex to the back-end database
(which does not support hex). Any ideas on how I might be able to
convert the number to an integer before it hits the database?

Thanks,
Kevin


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



Re: Add Support for Hex numbers is Admin

2007-09-19 Thread Kevin

This is great thanks! You were one step ahead of me on the display.
I'm still reading up on customizing the admin interface, but hopefully
something in there will help me adding any javascript if it is needed.

Thanks!

On Sep 19, 3:25 pm, jake elliott <[EMAIL PROTECTED]> wrote:
> hi kevin,
>
> you could convert to int in the model's save() method
>
> class MyModel(models.Model):
> def save(self):
> self.hexval = int(str(self.hexval), 16)
> super(MyModel, self).save()
>
> or whatever hex->decimal method you need for how you have the hex val
> stored.
>
> but then how to get it back into a hex representation when someone goes
> to edit the field?  the only thing that comes to my mind is javascript
> but i'm sure there's a less hackish solution :)
>
> best
> jake
>
> Kevin wrote:
> > In the admin interface if someone enters a number in hex, then it
> > fails the validation test. I've managed to make it pass the validation
> > test, but now the number gets passed in hex to the back-end database
> > (which does not support hex). Any ideas on how I might be able to
> > convert the number to an integer before it hits the database?
>
> > Thanks,
> > Kevin


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



Re: Chaining Filters for many-to-many

2007-10-29 Thread Kevin

I've tried some of the Q stuff, and that is probabbly where my answer
lies, but I can't quite figure it out. I  believe the example you
provided would return a test that has either 1024 or 2048 not one test
that has both.

models.TestLine.objects.get( Q(dimm__size=1024) | Q(dimm__size=2048) )



On Oct 29, 5:05 pm, Matthias Kestenholz <[EMAIL PROTECTED]> wrote:
> Hi,
>
> On 29.10.2007, at 21:58, Kevin wrote:
>
>
>
>
>
> > I'm trying to figure out how to chain filters for a many-to-many
> > relation ship that is evaluating to an empty set when it should not. I
> > basically have some a test with multiple dimms. I want to find a test
> > with both dimm "sizes" 1024 & 2048.
>
> > class TestLine(models.Model):
> >  #...some test info
>
> > class Dimm(models.Model):
> >testline = models.ForeignKey(TestLine)
> >size = models.IntegerField()
>
> > models
> > .TestLine.objects.filter(dimm__size=1024).filter(dimm__size=2048)
>
> > This returns an empty set, but I know there is a test with multiple
> > dimm objects and meets this criteria. Is there a limitation that I'm
> > missing here? Is there an alternative method to accomplish the intent
> > here?
>
> You should probably take a look at the Q 
> objects:http://www.djangoproject.com/documentation/db-api/#complex-lookups-wi...
>
> Something like this might work (untested):
>
> models.TestLine.objects.get( Q(dimm__size=1024) | Q(dimm__size=2048) )
>
> --http://spinlock.ch/blog/


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



Chaining Filters for many-to-many

2007-10-29 Thread Kevin

I'm trying to figure out how to chain filters for a many-to-many
relation ship that is evaluating to an empty set when it should not. I
basically have some a test with multiple dimms. I want to find a test
with both dimm "sizes" 1024 & 2048.

class TestLine(models.Model):
  #...some test info

class Dimm(models.Model):
testline = models.ForeignKey(TestLine)
size = models.IntegerField()

models.TestLine.objects.filter(dimm__size=1024).filter(dimm__size=2048)

This returns an empty set, but I know there is a test with multiple
dimm objects and meets this criteria. Is there a limitation that I'm
missing here? Is there an alternative method to accomplish the intent
here?

Thanks for any help,
Kevin


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



Re: Chaining Filters for many-to-many

2007-10-29 Thread Kevin

I gave up and did it a slightly harder way...just wish I would have
thought of it sooner :)

I used sets.Set to create a list of tests matching the criteria and
then used its intersection function to get the primary keys of those
tests.

It works o.k, but it just feels like I'm having to use the sets to
workaround a bug...oh well...Not complaining too much, I've loved
django since I found it.

On Oct 29, 5:17 pm, Matthias Kestenholz <[EMAIL PROTECTED]> wrote:
> On 29.10.2007, at 22:08, Kevin wrote:
>
> > I've tried some of the Q stuff, and that is probabbly where my answer
> > lies, but I can't quite figure it out. I  believe the example you
> > provided would return a test that has either 1024 or 2048 not one test
> > that has both.
>
> > models.TestLine.objects.get( Q(dimm__size=1024) | Q(dimm__size=2048) )
>
> Ah ok, I see. Perhaps you need to look into the extra() functionality?
> I don't know
> if you can compose this query with the builtin queryset methods.
>
> I think I'd use custom sql to get a list of matching TestLine IDs, but
> I have to admit
> that I don't know django too well (yet)
>
> --http://spinlock.ch/blog/


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



Re: Chaining Filters for many-to-many

2007-10-29 Thread Kevin

Ah, glad to know that it is a known issue at least and not a new
problem. Thanks for the info.

On Oct 29, 9:07 pm, Malcolm Tredinnick <[EMAIL PROTECTED]>
wrote:
> On Mon, 2007-10-29 at 20:58 +0000, Kevin wrote:
> > I'm trying to figure out how to chain filters for a many-to-many
> > relation ship that is evaluating to an empty set when it should not. I
> > basically have some a test with multiple dimms. I want to find a test
> > with both dimm "sizes" 1024 & 2048.
>
> > class TestLine(models.Model):
> >   #...some test info
>
> > class Dimm(models.Model):
> > testline = models.ForeignKey(TestLine)
> > size = models.IntegerField()
>
> > models.TestLine.objects.filter(dimm__size=1024).filter(dimm__size=2048)
>
> > This returns an empty set, but I know there is a test with multiple
> > dimm objects and meets this criteria. Is there a limitation that I'm
> > missing here? Is there an alternative method to accomplish the intent
> > here?
>
> So I see you've found an alternative approach that works for now. The
> underlying thing going on here is that there is a bug in the way Django
> generates the SQL for many-to-many relations. If you try to filter on on
> the same column more than once, it still only makes a single join to the
> intermediary table, so you end up with things look like:
>
> ... where foo_id = 6 and foo_id = 7 ...
>
> which is clearly impossible to satisfy for a unique column on the same
> table.
>
> This is ticket #1801 and has been fixed as part of the queryset-refactor
> branch. When that work is complete, it'll be merged into trunk (the
> branch is not suitable for testing yet)
>
> Regards,
> Malcolm
>
> --
> Remember that you are unique. Just like everyone 
> else.http://www.pointy-stick.com/blog/


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



bulk modify in the admin?

2007-11-14 Thread Kevin

I was just curious: has anyone fooled around with extending the admin
to do a sort of "bulk modify"? For example: update update multiple
entries (like an article) in the database to now have the same
author ?

I know that making the application/html and such wouldn't be too bad
for each particular use case, but just thought it would be pretty neat
if I there existed a way to extend/hack the admin interface to do
something similar in a more generic fashion.

Thanks!
Kevin


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



Re: Manager overriding error

2006-05-09 Thread Kevin

I ran into this problem as well.  The issue is that super() expects the
child class not the parent class (the documentation is wrong), so try
this:

super(DahlBookManager, self).get_query_set()..
instead of
super(Manager, self).get_query_set()

In addition, it wouldn't let me create the Manager sub-class enclosed
in my model, it had to be defined at the module level, eg:

BAD:
class MyModel(Model):
class MyManager(Manager):
 pass
objects = MyManager()

GOOD:
class MyManager(Manager):
def get_query_set():

class MyModel(Model):
objects = MyManager()


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



Re: Search Engine for Python and Django

2006-07-25 Thread Kevin

On the recommendation that ljworld uses swish-e [1], I incorporated
that into my django powered site.  The Python interface I use is [2].

Here's the code my search view uses:

handle = SwishE.new(SEARCH_INDEX_FILE)
results = handle.query(terms)

ids = [int(x.getproperty('swishdocpath')) for x in results]

Then just call a Model.objects.in_bulk().

[1] http://swish-e.org/
[2] http://jibe.freeshell.org/bits/SwishE


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



Re: Search Engine for Python and Django

2006-07-27 Thread Kevin

I run django (and Swish-E) under linux so I can't provide any advise on
how to compile it for windows.

I do run swish-e with the -S prog option and I wrote a python script
that reads all of the models from the database and writes out xml
(actually html) that corresponds with the values that I'm interested in
indexing.

This allows me to weight the various fields (eg title field is more
important that the description field)

Here's my entire indexing script (my database is a catalog of items for
an e-commerce store):

from cwood.store.models import *

import sys

def render(item):
str = ""
str += '%s'% item.name
str += ""
str += "%s" % item.description
str += ""
return str

def print_data(path, data):
print "Path-Name: %s" % str(path)
print "Content-Length: %d" % len(data)
print "Document-Type: HTML*"
print ""
sys.stdout.write(data)

items = Item.objects.all()
for i in items:
print_data(i.id, render(i))


Then I just run:
swish-e -S prog -i generate_index.py


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



Re: Using Swish-e with django...

2006-07-31 Thread Kevin

My use of swish-e is clearly different that yours.  The indexer part of
swish-e is run only periodically (say, nightly) with a `swish-e -S prog
-i ./generate_index.py`

this creates an index file that the SwishE python api queries


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



Manipulator.save() not hitting the DB

2005-11-03 Thread Kevin

I'm trying to use the manipulator framework to generate a multi-part
form.  It's for an online shopping engine where the customer goes
through a few steps entering their shipping and credit card info, etc.

Anyways, I created some model classes, eg ContactInfo (phone #, email,
etc), Address and CreditCardInfo.  Using the builtin manipulators and
formwrappers to present these variables to the user.  When each form
was POSTed to the server, I was going to use the AddManipulator to
first validate the data (get_validation_errors()), and if that
succeeds, convert the form data into the representative Model object
and then store that object in the session dictionary.  Unfortunately,
it seems the only method available in the Manipulator framework is
save() and that stores the variable first in the database.  Is there a
way to convert the form data into django Model objects without saving
them to the db?



Re: Manipulator.save() not hitting the DB

2005-11-03 Thread Kevin

The base class, Manipulator, just throws a NotImplementedException for
it's save() method.  Is there a more concrete example I can view to see
how to override storing to the database.

PS.  I'm converting an existing PHP site to django, it's so nice having
all these validation/admin stuff just "taken care of".  Thanks for the
work & help.



Re: Using API to bulk populate data

2005-11-07 Thread Kevin

I'm working on a similar script to convert a legacy database.  Just a
hint from a tough lesson learned, you work the opposite order that OO
may teach you and you save() first, then aggregate.

So example:
class PhoneNumber(meta.Model):
number = meta.CharField()

class Contact(meta.Model):
name = meta.CharField()
home_phone = meta.ForeignKey(PhoneNumber)
work_phone = meta.ForeignKey(PhoneNumber)


So to build a Contact, do the following:
home = PhoneNumber(number = '555-12-12')
home.save()

work = PhoneNumber(number = '555-1212')
work.save()

c = Contact(name = 'Bob', home_phone = home, work_phone = work)
c.save()



FormField Length

2005-11-07 Thread Kevin

In my code, I have:

zip_code = meta.CharField(maxlength=9)

But when it's rendered as a form, it's always given a SIZE="30".  Now I
saw that sub-classes like USStateField override the length parameter in
the TextField.__init__ method, but I really don't want to go creating
all kinds of sub-classes just to correct the display of the form.  Are
there any other ways to fix this?



Re: Dictionary keys in templates

2005-11-09 Thread Kevin

Is there a reason you can't do this:

{% for items in dictionary.items %}
... be able to use {{ items.0 }} and "{{ items.1 }}"...
{% endfor %}

this is equivalent to the python:
for key, value in dictionary.items()

but since for loops in the template language can only create one
variable, you need ot use tuple indexes...



Form Value Array

2005-11-21 Thread Kevin

I'm converting a PHP application over to django and one thing I took
for granted was PHPs conversion of inputs with the name "input[]" into
an array automatically.  Since django nor python seem to support that
conversion, what do people suggest for receiving 1 to N inputs on a
request.POST?

In my specific case, it's a shopping cart, so I want to let the user
add multiple items at the same time.  Eg, in HTML:




and ideally I could just do:
items = request.POST.get_list('item')

any ideas?  Should I just plan on doing:

pat = re.compile("^.+\[\d+\]$")
values = []
for name, value in request.POST.items():
   if(pat.search(name)):
   values.append(value)

Thanks.



Re: Form Value Array

2005-11-22 Thread Kevin

Unfortunately, I believe they're necessary.  My exact code is a list of
radio inputs, in template lanaguage and radio buttons use the input
name as a way of grouping.

My Models would be:
class OptionSet(Model):
   name = CharField()

class Option(Model):
   name = CharField
   option_set = ForeignKey(OptionSet)

clas Item(model):
   options = ForeignKey(OptionSet)

{% for option_set in item.get_options %}

{{option_set.name}}
{% for option in option_set.get_choices %}
 {{option.name}}
{% endfor %}
{% endfor %}

Which once translated would look like:

Color

o Blue
o Red
o Green

Size
--
o Small
o Medium
o Large



Re: Form Value Array

2005-11-22 Thread Kevin

I understand, and that's what I'm really doing at the moment, but I was
just curious if there's a better way to retrieve these POST values than
just:

options = []
for name, value in request.POST.items():
if(name.startswith("option")):
 options.append(value)



Re: Form Value Array

2005-11-22 Thread Kevin

I decided to try writing a generic array converter as a middleware:

import re
class ParamsMiddleware:
patt = re.compile("^([a-zA-Z_]\w*)\[\(d*)\]$")
LARGE_INT = 2**30

def process_request(self, request):
if(request.POST):
post = request.POST.copy()
new_vals = {}
for name, value in post.items():
match =
ParamsMiddleware.patt.match(name)
if not match:
continue
value = post[name]
del post.data[name]
new_name = match.group(1)
try:
idx = int(match.group(2))
except ValueError:
# just append it to the end
# se use the largest number for
sorting
idx =
ParamsMiddleware.LARGE_INT
vals = new_vals.setdefault(new_name,
[])
vals.append((idx, value))
if(new_vals):
for name, vals in new_vals.items():
vals.sort(key=lambda x: x[0])
post[name] = [x[1] for x in
vals]
post._mutable = False
request._post = post
return None



Re: ANN: new-admin branch merged to trunk

2005-11-25 Thread Kevin

Excellent, time to `svn switch` back to trunk



Re: is Django too powerful?

2005-12-14 Thread Kevin

I'd prefer to see a two stage approach to contributing applications to
Django where newly contributed apps are in some sub-directory like
django.extras instead of django.contrib that  contains more
standardized and popular applications like admin.

I'm thinking of KDE as a model with there kdenonbeta directory for
newer applications that have yet to be fully integrated into the main
kde distribution.



url hierarchy

2005-12-20 Thread Kevin

Hey guys, got myself stumped and I'm hoping you could help me figure
this one out.  In my code I've got a hierarchical category structure
for my model that's intended to roughly analogize a filesystem, eg:

class Album(meta.Model):
location = meta.SlugField()
name = meta.CharField()
parent = meta.ForeignKey('self', null=True)


And then I build up these albums as directories, eg:

a = Album(location='2005')
a.save()
b = Album(location='May', parent=a)
b.save()

etc

Now, that all works, but I'm trying to figure out how to define my
urlconf so that I can specify urls like a filesystem, eg:
www.mydomain.com/albums/2005/may/fishing_trip/

I've tried something similar to:
(r'^/albums/(?:([a-z0-9_]+)/)+$', 'mydomain.views.view_album')

and then:
def view_album(request, *albums):
return HttpResponse(repr(albums))

but this always only returns the last match, not all of them as a list.
 I know it's a limitation of regular expressions, anyone know a way
around it?  Id rather not go to:

r'/albums/(?P\d+)/$' and keep the more readable urls



Re: url hierarchy

2005-12-20 Thread Kevin

Yeah, after more experimenting, I came to the same conclusion and
globbed the whole path and tokenized the names in the view.

Thanks for the help.



SQL Injection

2005-12-20 Thread Kevin

Is there any builtin protection against SQL Injection in django?  Let
me present a common case I use:

class Article(meta.Model):
name = meta.SlugField()
title = meta.CharField()
text = meta.TextField()


# my url conf
(r'^articles/(?P.*)/$', 'mydomain.views.view_article')

# my view
def view_article(request, article):
try:
articles.get_object(name__exact=article)
except:
return HttpResponseNotFound()

render_to_response('view_article', {'article': article})


My question is, can I trust that django's ORM won't allow "bad things"
to happen from the 'article' string received from the urlconf?  Or do I
need to perform some validation on the argument before passing it to
get_object()?



Re: Django for eCommerce?

2005-12-22 Thread Kevin

I'm converting my custom PHP e-commerce site over to django.  It's a
dream writing in a true MVC framework with the python language and
django's ORM and template language.

I do all my payment processing offline, so I can't help on that topic.
It's much easier to develop a product catalog with the built-in admin
interface and the object-relational manager.



Search Functionality

2005-12-28 Thread Kevin

Could anyone provide some hints on how they have implemented search
functionality on their web site?  Did you do it django or use another
middleware (eg, Lucene)?  If you did it django, did you bypass the ORM
and use direct SQL to take advantage of full text search?

I'm currently trying to build the functionality directly in django's
ORM as a cascade of functions that would retrieve matches in decreasing
relevance, eg:

class Article(meta.Model):
title = meta.CharField()
description = meta.TextField()
keywords = meta.CharField()

def search(request, term):
matches = []
matches.extend(findExactTitle(term))
matches.extend(findInTitle(term))
matches.extend(findInKeywords(term))
matches.extend(findInDescription(term))

render_to_response('search_results', {'matches': matches}

Any ideas?  Suggestions?



Re: Search Functionality

2005-12-31 Thread Kevin

That would be great.  I think it would a strong benefit to many django
users as search is such a common problem.



Re: making photo gallery

2006-01-05 Thread Kevin

For this exact use I created the following custom filter.  It converts
a list into a two-dimensional table:

def tabularize(value, cols):
"""modifies a list to become a list of lists
eg [1,2,3,4] becomes [[1,2], [3,4]] with an argument of 2"""
try:
cols = int(cols)
except ValueError:
return [value]
return map(*([None] + [value[i::cols] for i in range(0,
cols)]))


so now you just have to:

{% for row in photos|tabularize:"4" %}

{% for photo in row %}
{% if photo %}{{ photo.whatever }}{% endif %}
{% endfor %}

{% endfor %}




Re: making photo gallery

2006-01-06 Thread Kevin

Because without the map(None + ), your last row will be short
elements if it doesn't divide pefectly.

So, if you're cols was 3, you'd get:
[(1,2,3), (4,)]

and of course, that could create bad html:


1
2
3


4



So, now with the Map, the left over cells are set to None, so that's
why the template does the {% if cell %} test inside the  tag so you
can have some empty cells finish off the row:
eg:

4


..

You're right about the list of tuples instead of list of lists, but I
only ever need iterables...



Validator across fields

2006-01-06 Thread Kevin

I'm sure this has been asked before, but googling didn't turn up a
solution.

I have the following class:

class ContactInfo(meta.Model):
name = meta.CharField()
phone = meta.PhoneNumberField(blank=True)
email = meta.EmailField(blank=True)


And I'm trying to present a form to the user to enter this info, easy:
m = contactinfos.AddManipulator()
form = formfields.FormWrapper(m, data, errors)
return render_to_response('contact', {'form': form})


The main issue is, I'm trying to add a constraint that the user enter
EITHER a phone number OR an email.  So I thought I could write a custom
validator that took the all_data param and did the check.

But since I set blank=True, validator's aren't checked.  But if I don't
use blank=True, I get errors for leaving the field blank.  How can I
solve this?

The only thing I can think of is to attach the validator to a different
field that is required (like name) but that's ugly since the error
message will be associated with the wrong field.



Re: Managing static media urls

2006-01-20 Thread Kevin

I think the question at hand is not where to store and serve the media
files, but how to write an app that can easily support accessing media
files from different urls.  I had this same issue between my
development and production apache servers:

Dev Site
localhost/mysite/images/whatever.gif

Production
mysite.com/images/whatever.gif

And even the occasional development on my laptop on the road
localhost/~myuser/mysite/images/whatever.gif

This was never a problem in my previous dev environment (php) because
I'd always just use relative urls like:



But with django's more flexible url mapping, I need to make all the
links absolute.

The most frequent suggestion is just to define a setting such as the
MEDIA_ROOT that can be set to "/images" on my production server,
"/mysite/images" on my dev and then "~myuser/mysite/images" on the
laptop example.

Looking at ruby on rails, they seem to have some template tag
equivalent that does url generation for you automatically (stolen from
the rails tutorial):
<%= link_to recipe.title.

Perhaps django could use something similar?



Re: Overthinking urls.py?

2006-03-29 Thread Kevin

I think the problem is that urlconf provides a url => view mapping.
Really though, for creating the links, we need the reverse mapping.  We
usually know the view we want to display, but don't know it's URL.

For example, you have a bulletin board app:

urls.py:
urlpatterns = patterns(''
'^comments/(\d+)/', 'sample.bboard.view_comment')
.

def view_comment(id):
comment = Comment.objects.get(id)
responses = comment.responses.all()
render_to_response('template', {'comment': comment, 'responses':
responses})


Currently, you could define the template like this:
template.html:
.
{% for response in responses %}
{{ response.title }}
{% endfor %}

But, really, all you want is a tag like this:
{% for response in responses %}
{{ response.title}}


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



Starting a new Python blog

2012-01-28 Thread Kevin
Hello Everyone,

  For sometime now I have been itching to create a Python blog, and
now the fruits of my labor have paid off.  I am ready to release the
blog to the public eyes.  At the moment it has 2 main features, a blog
portion, and a bookmark system.  Both the blog and the bookmark system
offer an RSS Atom feed.  The bookmark system is fully compatible with
"Live Bookmarks" to quickly access some of my top Python sites I visit
or visited recently which caught my eye.

  The website is called "Python Diary", a rather unique take on a tech
blog name.  The site itself has a diary-like theme, and is for the
most part very easily to navigate.  The website was completely built
using Python, the theme was taken from a wordpress theme website and
formatted to work with the Django template system.  The entire backend
is written from scratch using a few reusable Django apps, namely,
django-tagging, south, and cumulus.

  Now you might be saying, "Oh great, yet another Python blog".  But
wait...  I plan on setting this blog apart from the thousands of other
blogs in the world with some very unique features.  Features normally
found on commercial software blogs, movie and video game blogs is a
thorough review system.  I plan on going through many of the available
Python packages out there in the wild and basically reviewing them
like one would review anything else.  I do not see a dedicated Python
website which has reviews of many Python packages available in PyPi.
I plan on stating the usual pros and cons of the package, and
providing a score.  For example of how this type of review is
formatted, take a look at a CNET Review.

My new blog can be found here: http://www.pythondiary.com/

  Tell me what you think of the website in general, and the overall
idea for this blog.

If you would like to subscribe to the upcoming content, add this RSS
feed to your favorite RSS reader:
http://www.pythondiary.com/blog.xml

-- 
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: Starting a new Python blog

2012-01-29 Thread Kevin
It is good to see some subscribers this early on.  Thank you.  I have
rolled out the updates for Tutorials and set the foundation for the
Review system by starting a list of packages I frequently use, and
hope to later review.  I hope to have the full review system live by
the end of this week.

The tutorials will also use the package list I built to build a list
of dependencies required for the tutorial itself.  I hope this makes
it much easier to follow tutorials by knowing which Python packages
will be required before hand.  The package list has a summary of the
package and a link to the website where it is maintained.  There are
currently 2 tutorials available for consumption.  Both are videos I
made on YouTube for Rackspace Cloud last year, so if your curious
about how Rackspace cloud works, do check them out.

There is a separate RSS feed for the tutorials: 
http://www.pythondiary.com/tutorials.xml

I am planning on making a "Digest" RSS Feed which will contain the
latest posts from each section, but will also keep the separate feeds
there for subscribers who only want the blog, or just tutorials.

The site will remain ad-free for the time being, so that requests are
quick for end-users.  I made use of the Django caching framework to
also increase the response time.  I hope to keep the blog site quick
and clean.

Enjoy!

On Jan 29, 5:06 pm, Mario Gudelj  wrote:
> Same :)
>
> On 29 January 2012 19:11, Anler Hernandez Peral  wrote:
>
>
>
>
>
>
>
> > you have one subscriber over here and waiting to see more posts ;)
>
> > --
> > anler
>
> > On Sat, Jan 28, 2012 at 9:35 PM, Kevin  wrote:
>
> >> Hello Everyone,
>
> >>  For sometime now I have been itching to create a Python blog, and
> >> now the fruits of my labor have paid off.  I am ready to release the
> >> blog to the public eyes.  At the moment it has 2 main features, a blog
> >> portion, and a bookmark system.  Both the blog and the bookmark system
> >> offer an RSS Atom feed.  The bookmark system is fully compatible with
> >> "Live Bookmarks" to quickly access some of my top Python sites I visit
> >> or visited recently which caught my eye.
>
> >>  The website is called "Python Diary", a rather unique take on a tech
> >> blog name.  The site itself has a diary-like theme, and is for the
> >> most part very easily to navigate.  The website was completely built
> >> using Python, the theme was taken from a wordpress theme website and
> >> formatted to work with the Django template system.  The entire backend
> >> is written from scratch using a few reusable Django apps, namely,
> >> django-tagging, south, and cumulus.
>
> >>  Now you might be saying, "Oh great, yet another Python blog".  But
> >> wait...  I plan on setting this blog apart from the thousands of other
> >> blogs in the world with some very unique features.  Features normally
> >> found on commercial software blogs, movie and video game blogs is a
> >> thorough review system.  I plan on going through many of the available
> >> Python packages out there in the wild and basically reviewing them
> >> like one would review anything else.  I do not see a dedicated Python
> >> website which has reviews of many Python packages available in PyPi.
> >> I plan on stating the usual pros and cons of the package, and
> >> providing a score.  For example of how this type of review is
> >> formatted, take a look at a CNET Review.
>
> >> My new blog can be found here:http://www.pythondiary.com/
>
> >>  Tell me what you think of the website in general, and the overall
> >> idea for this blog.
>
> >> If you would like to subscribe to the upcoming content, add this RSS
> >> feed to your favorite RSS reader:
> >>http://www.pythondiary.com/blog.xml
>
> >> --
> >> You received this message because you are subscribed to the Google Groups
> >> "Django users" group.
> >> To post to this group, send email to django-users@googlegroups.com.
> >> To unsubscribe from this group, send email to
> >> django-users+unsubscr...@googlegroups.com.
> >> For more options, visit this group at
> >>http://groups.google.com/group/django-users?hl=en.
>
> >  --
> > You received this message because you are subscribed to the Google Groups
> > "Django users" group.
> > To post to this group, send email to django-users@googlegroups.com.
> > To unsubscribe from this group, send email to
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group at
> >http://groups.google.com/group/django-users?hl=en.

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

2012-01-30 Thread Kevin
@Aaron, good suggestion, I'll definitely look into it for a future
update, if only Twitter supported RSS feeds.

@Kate, yes I have considered changing the style of the site.  I had no
idea the template would be so awkward when I first tested it.  Now
that there's content, the styling really hurts navigation and overall
usability.

@Wc, I will make the change to open bookmarks in a new window/tab.
There is also the live bookmark feature available for Desktop browser
users, should work in all major browsers.

Kevin

On Jan 30, 7:47 am, Katie Cunningham  wrote:
> Have you considered changing the styling of your site? It's a bit
> awkward to look at, since it looks like it was only made to fit on a
> much smaller screen. Perhaps you could look at Bootstrap, which is a
> much more flexible CSS framework?
>
> Katie
>
> On Mon, Jan 30, 2012 at 8:45 AM, Aaron Cannon
>
>
>
>
>
>
>
>  wrote:
> > For me, Twitter is the new RSS.  Any chance of setting up a feed for
> > new content notifications?
>
> > Thanks.
>
> > Aaron
>
> > On 1/30/12, Kevin  wrote:
> >> It is good to see some subscribers this early on.  Thank you.  I have
> >> rolled out the updates for Tutorials and set the foundation for the
> >> Review system by starting a list of packages I frequently use, and
> >> hope to later review.  I hope to have the full review system live by
> >> the end of this week.
>
> >> The tutorials will also use the package list I built to build a list
> >> of dependencies required for the tutorial itself.  I hope this makes
> >> it much easier to follow tutorials by knowing which Python packages
> >> will be required before hand.  The package list has a summary of the
> >> package and a link to the website where it is maintained.  There are
> >> currently 2 tutorials available for consumption.  Both are videos I
> >> made on YouTube for Rackspace Cloud last year, so if your curious
> >> about how Rackspace cloud works, do check them out.
>
> >> There is a separate RSS feed for the tutorials:
> >>http://www.pythondiary.com/tutorials.xml
>
> >> I am planning on making a "Digest" RSS Feed which will contain the
> >> latest posts from each section, but will also keep the separate feeds
> >> there for subscribers who only want the blog, or just tutorials.
>
> >> The site will remain ad-free for the time being, so that requests are
> >> quick for end-users.  I made use of the Django caching framework to
> >> also increase the response time.  I hope to keep the blog site quick
> >> and clean.
>
> >> Enjoy!
>
> >> On Jan 29, 5:06 pm, Mario Gudelj  wrote:
> >>> Same :)
>
> >>> On 29 January 2012 19:11, Anler Hernandez Peral  wrote:
>
> >>> > you have one subscriber over here and waiting to see more posts ;)
>
> >>> > --
> >>> > anler
>
> >>> > On Sat, Jan 28, 2012 at 9:35 PM, Kevin  wrote:
>
> >>> >> Hello Everyone,
>
> >>> >>  For sometime now I have been itching to create a Python blog, and
> >>> >> now the fruits of my labor have paid off.  I am ready to release the
> >>> >> blog to the public eyes.  At the moment it has 2 main features, a blog
> >>> >> portion, and a bookmark system.  Both the blog and the bookmark system
> >>> >> offer an RSS Atom feed.  The bookmark system is fully compatible with
> >>> >> "Live Bookmarks" to quickly access some of my top Python sites I visit
> >>> >> or visited recently which caught my eye.
>
> >>> >>  The website is called "Python Diary", a rather unique take on a tech
> >>> >> blog name.  The site itself has a diary-like theme, and is for the
> >>> >> most part very easily to navigate.  The website was completely built
> >>> >> using Python, the theme was taken from a wordpress theme website and
> >>> >> formatted to work with the Django template system.  The entire backend
> >>> >> is written from scratch using a few reusable Django apps, namely,
> >>> >> django-tagging, south, and cumulus.
>
> >>> >>  Now you might be saying, "Oh great, yet another Python blog".  But
> >>> >> wait...  I plan on setting this blog apart from the thousands of other
> >>> >> blogs in the world with some very unique features.  Features normally
> >>> >> found on commercial software blogs, movie an

Re: Help Me With omab/django-socialauth

2012-02-03 Thread Kevin
Did you take a look at the example project?

https://github.com/omab/django-social-auth/tree/master/example

Compare it with your own project, or even use this example project as
a base for your own project.

If all your urls.py contains is "url(r'',
include('social_auth.urls')), " and no other definitions, this could
be why it redirecting, as it cannot find the URL it's suppose to land
on.  Check the output in the Windows command window and see what URLs
are being requested and see if there's anything odd.

On Feb 3, 2:12 am, coded kid  wrote:
> Just keep getting redirect error. My Api keys are correct. Do you use
> the same LOGIN URL with the one above? Whats the main login url to
> twitter auth form?
>
> On Feb 2, 5:23 pm, Thorsten Sanders  wrote:
>
>
>
>
>
>
>
> > I took your config and its working fine, maybe your twitter api key is
> > wrong?
>
> > On 02.02.2012 11:22, coded kid wrote:
>
> > > I'm getting a redirect loop error. Whats the probs?
>
> > > On Feb 1, 1:22 pm, Thorsten Sanders  wrote:
> > >> Some sort of error traceback/description would be helpful, from a quick
> > >> look it seems all right.
>
> > >> On 01.02.2012 13:23, coded kid wrote:
>
> > >>> Hey guys, I'm facing a huge  problem with omab/django/socialauth.
> > >>> After setting all the necessary settings, I clicked on the Enter
> > >>> using Twitter link on my homepage, it couldn t redirect me to where I
> > >>> will enter my twitter username and password. Below are my settings.
> > >>> In settings.py
> > >>> INSTALLED_APPS = (
> > >>> 'social_auth',
> > >>> }
> > >>> TEMPLATE_CONTEXT_PROCESSORS = (
> > >>>      "django.core.context_processors.auth",
> > >>>      "django.core.context_processors.debug",
> > >>>      "django.core.context_processors.i18n",
> > >>>      "django.core.context_processors.media",
> > >>>      "django.core.context_processors.static",
> > >>>     "django.contrib.messages.context_processors.messages",
> > >>>     "django.core.context_processors.request",
> > >>>      social_auth.context_processors.social_auth_by_type_backends ,
> > >>> )
> > >>> AUTHENTICATION_BACKENDS = (
> > >>>      'social_auth.backends.twitter.TwitterBackend',
> > >>>     'django.contrib.auth.backends.ModelBackend',
> > >>> )
> > >>> SOCIAL_AUTH_ENABLED_BACKENDS = ('twitter')
> > >>> TWITTER_CONSUMER_KEY         = '0hdgdhsnmzHDGDK'
> > >>> TWITTER_CONSUMER_SECRET      = 'YyNngsgw[1jw lcllcleleedfejewjuw'
> > >>> LOGIN_URL = '/accounts/login/' #login form for users to log in with
> > >>> their username and password!
> > >>> SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/homi/'  #page after user get
> > >>> authenticated
> > >>> SOCIAL_AUTH_NEW_ASSOCIATION_REDIRECT_URL = '/homi/'   '  #page after
> > >>> user get authenticated
> > >>> SOCIAL_AUTH_ERROR_KEY='social_errors'
> > >>> SOCIAL_AUTH_COMPLETE_URL_NAME  = 'socialauth_complete'
> > >>> SOCIAL_AUTH_ASSOCIATE_URL_NAME = 'socialauth_associate_complete'
> > >>> from django.template.defaultfilters import slugify
> > >>> SOCIAL_AUTH_USERNAME_FIXER = lambda u: slugify(u)
> > >>> SOCIAL_AUTH_UUID_LENGTH = 16
> > >>> SOCIAL_AUTH_EXTRA_DATA = False
> > >>> In urls.py
> > >>> url(r'', include('social_auth.urls')),
> > >>> In my template:
> > >>> 
> > >>>    Enter using Twitter > >>> a>
> > >>>    
> > >>> 
> > >>> What do you think I m doing wrong? Hope to hear from you soon. Thanks
> > >>> so much!
> > >>> N:B : I m coding on windows machine. And in the development
> > >>> environment using localhost:8000.

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



Middleware class to properly format arbitrary data

2012-02-14 Thread Kevin
Hello everyone,

  Before I go ahead and build a simple middleware for this myself, I
would like to know if such a middleware already exists in the wild, so
that I can prevent re-inventing the wheel.  Here's an example, if
nobody is following what the subject actually means:

  Say I have a view that does not return a django.http.HTTPResponse
object.  Instead, it returns a dictionary or a file-like object.  I
would like said middleware to detect this and format the output data
accordingly.  In the case of a dictionary, it will automatically add a
JSON header, encode the dictionary and output it.  For the sake of a
file-like object, it will use it's .read() method to provide the
output data.  I would also like it to check if a Form object is being
returned and automatically provide a template and a RequestContext.

According to a DRY principle, this type of feature only makes sense to
have built into Django.  However, if I attempt to return anything but
an HTTPResponse object, I get a big fat exception saying that it just
won't work, and I need to manually construct my HTTPResponse object
specifically for my data.  Constructing HTTPResponses and Contexts is
one of my most hated parts of Django, it's not really fun and get's
very repetitive and old really fast.

Thanks.

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



Re: Starting a new Python blog

2012-02-18 Thread Kevin
Hello Everyone!

  Great news!  The blog's theme has been redone completely using help
from Twitter's brilliant Bootstrap.  The site is now much easier to
navigate and find all the content with only 2 clicks from anywhere on
the site(you don't even need to scroll).

  On top of the new site design, I incorporated a nice search bar,
which works exactly like Google's search bar.  This will make it very
easy to locate any content within the site.  The search bar only
searches Blog entries, and excludes Package lists, tutorials and
reviews.  I will be adding separate search bars in each of these
categories for specific searches in these areas.

  Thank you all for your many great suggestions on django-users here,
and hopefully the site is much more easier for you to navigate.
Twitter's Bootstrap also supports mobile browsers, such as the iPhone/
iPad/Android.  This should make it much easier to read while on the
go.  The new navigation bar includes new features such as easy access
to the site's RSS feeds, and Archive browsing.

  Future site features will include an option to easily share articles
with others and tweet them on your twitter feed.  This blog will use
the hash tag, #PythonDiary.  If you wish to follow me on twitter,
which may have the odd update, it's best to subscribe using RSS in
your favorite reader or mobile app.  My twitter handle is @kveroneau

Kevin Veroneau
PythonDiary.com

On Jan 30, 11:46 pm, Kevin  wrote:
> @Aaron, good suggestion, I'll definitely look into it for a future
> update, if only Twitter supported RSS feeds.
>
> @Kate, yes I have considered changing the style of the site.  I had no
> idea the template would be so awkward when I first tested it.  Now
> that there's content, the styling really hurts navigation and overall
> usability.
>
> @Wc, I will make the change to open bookmarks in a new window/tab.
> There is also the live bookmark feature available for Desktop browser
> users, should work in all major browsers.
>
> Kevin
>
> On Jan 30, 7:47 am, Katie Cunningham  wrote:
>
>
>
>
>
>
>
> > Have you considered changing the styling of your site? It's a bit
> > awkward to look at, since it looks like it was only made to fit on a
> > much smaller screen. Perhaps you could look at Bootstrap, which is a
> > much more flexible CSS framework?
>
> > Katie
>
> > On Mon, Jan 30, 2012 at 8:45 AM, Aaron Cannon
>
> >  wrote:
> > > For me, Twitter is the new RSS.  Any chance of setting up a feed for
> > > new content notifications?
>
> > > Thanks.
>
> > > Aaron
>
> > > On 1/30/12, Kevin  wrote:
> > >> It is good to see some subscribers this early on.  Thank you.  I have
> > >> rolled out the updates for Tutorials and set the foundation for the
> > >> Review system by starting a list of packages I frequently use, and
> > >> hope to later review.  I hope to have the full review system live by
> > >> the end of this week.
>
> > >> The tutorials will also use the package list I built to build a list
> > >> of dependencies required for the tutorial itself.  I hope this makes
> > >> it much easier to follow tutorials by knowing which Python packages
> > >> will be required before hand.  The package list has a summary of the
> > >> package and a link to the website where it is maintained.  There are
> > >> currently 2 tutorials available for consumption.  Both are videos I
> > >> made on YouTube for Rackspace Cloud last year, so if your curious
> > >> about how Rackspace cloud works, do check them out.
>
> > >> There is a separate RSS feed for the tutorials:
> > >>http://www.pythondiary.com/tutorials.xml
>
> > >> I am planning on making a "Digest" RSS Feed which will contain the
> > >> latest posts from each section, but will also keep the separate feeds
> > >> there for subscribers who only want the blog, or just tutorials.
>
> > >> The site will remain ad-free for the time being, so that requests are
> > >> quick for end-users.  I made use of the Django caching framework to
> > >> also increase the response time.  I hope to keep the blog site quick
> > >> and clean.
>
> > >> Enjoy!
>
> > >> On Jan 29, 5:06 pm, Mario Gudelj  wrote:
> > >>> Same :)
>
> > >>> On 29 January 2012 19:11, Anler Hernandez Peral  
> > >>> wrote:
>
> > >>> > you have one subscriber over here and waiting to see more posts ;)
>
> > >>> > --
> > >>> > anler
>
> > &

Adding 'extra_context' variable to Class-based views

2012-03-26 Thread Kevin
Now that Django 1.4 is among us, function-based generic views are really 
being phased out, and for those who use 'extra_context', but dislike the 
method used implement it:

class MyListView(ListView):
def get_context_data(self, **kwargs):
context = super(MyListView, self).get_context_data(**kwargs)
context.update({
'foo': 42,
'bar': 37
})
return context

Have a look at my tutorial on how to implement something similar to Django 1.2 
and below to ease migration.  This is mainly useful if you use one shot 
'extra_contexts' in a generic view, this tutorial will allow this in your 
urls.py:

ContextListView.as_view(queryset=Book.objects.filter(public=True),extra_context={'form':NewBookForm()})

http://www.pythondiary.com/tutorials/django-13-generic-views-and-extra_context.html

Hope it helps people on the migration path to Django 1.4.  I am currently in 
the progress of migration, and will be writing some tutorials and blog posts 
about my experiences.

Kevin.


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/PtkpfwVHSiEJ.
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.



New release of Instant Django

2012-04-10 Thread Kevin
For the Windows users out there, or for those with friends who use Windows, 
this is for you.

Some of you may recall Instant Django, there should be a post from the 
original author on this group about it.

Basically Instant Django is a self contained Python+Django installation 
within a single directory.  It can run on any Windows platform without any 
further software installations.  It can even run alongside your existing 
Python installation, without interfering with it.  It is an entirely 
self-contained Python+Django installation to easily engage with future 
Django developers, or those who merely want to check out Django just to see 
if it's right for them.

Changes from the original Instant Django include:
Django 1.4
Setuptools-0.6u11
pip-1.1

The inclusion of setuptools and pip allow new users to Python to easy 
install new packages and explore PyPi to see what there is offer in the 
world of Python.

Unlike normal Python installations, the included batch file will setup a 
perfect "PATH" variable, to make the command shell in Windows feel exactly 
like a *NIX.  Python and django-admin are in the PATH. :)  This will allow 
users to easy use the package with no knowledge of setting up their Windows 
environment, and this also makes most, if not all online Python tutorials 
just work.  Normally a Windows user will need to either alter their path 
settings, or type in the entire path, for django-admin.py this can be a tad 
annoying.  This can also deter users from exploring Python or Django, as it 
can be a lot of work to configure your Windows environment.

Everything from the original Instant Django are all left in tact.  I added 
a readme file and a packages file which explains some basic operations to 
get new users up and running quickly.  The batch file is the same as in 
Instant Django.  Notepad++ is also included, just as the original Instant 
Django.

Check it out, and let me know what you think: 
http://www.pythondiary.com/blog/Apr.10,2012/instant-django-release-information.html

Best of all, the actual ZIP file is hosted on a CDN(Content Delivery 
Network), which means all users regardless of their region will be-able to 
download the file at very fast speeds(does depend on your local connection, 
don't expect fast on your 56k).

Kevin Veroneau

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/nK5SoDWrH2AJ.
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: Is it a good practice to delegate views based on GET / POST?

2012-04-10 Thread Kevin
Separating GET and POST is normally used for RESTful web programming.  
Which is becoming a very common practice is popular competing frameworks, 
such as Rails.

Personally I would prefer a more "native" way in Django to separate 
GET/POST views.  I guess this could be done via a decorator or something.

Another reason you may want to separate GET/POST is for security.  For 
example, only letting some views accept POST requests, and basically shove 
a big 403 message to users who attempt to POST to a view which otherwise 
shouldn't accept a POST.  I normally limit this using the web server, so 
POST requests will not even reach the web application if the component 
doesn't even accept it.  I always have a mind set that the Internet is 
never safe, and everybody is a hacker.  It's better to be safe, than sorry 
that a malicious POST body reached your application.  An easy way to do 
this on the server is to use a regex mask for views which will accept a 
POST body, such as having an extension of ".do" or ".action".  If the view 
doesn't have this special extension, then only allow GET requests to pass 
through to WSGI.  You can also filter out headers and such on the server to 
further protect your WSGI application from the outside world.  If you don't 
have access to the server's configuration, well, then I'm sure the cloud 
service you deployed to is "safe enough".

On Tuesday, 10 April 2012 18:21:15 UTC-5, John Yeukhon Wong wrote:
>
> 3/4 down the page
> http://www.djangobook.com/en/2.0/chapter08/
>
> urlpatterns = patterns('', # ... (r'^somepage/$', views.method_splitter, 
> {'GET': views.some_page_get, 'POST': views.some_page_post}), # ... )
>
>
> Is this a good practice at all? If I use the method splitter, my urls will 
> look ugly. Or should I just separate based on the length of certain views? 
> (If it's too long, break it into two, or use the delegator)
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/8AwOL9nh7lcJ.
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: PythonScript(Zope) like in a django app, any tips?

2012-04-15 Thread Kevin
Check out PyPy Sandboxing, it may be your best bet:

http://pypy.org/features.html#sandboxing


On Saturday, 14 April 2012 11:45:41 UTC-5, Arruda wrote:
>
> Hi there, I'm doing a system where I want the users to be able to 
> set/change some scripts that are dynamically run(RPG like scripts).
> So a user can change the way the Kill_a_player script is run.
>
> I thought of doing this by using exec, like this:
>
>
> class Script(models.Model):
>> script_py = models.TextField(u"Script Python")
>> 
>> class Meta:
>> app_label = 'scripts'
>
>  
>
>  
>
> def run(self,**kwargs):
>> ret= None
>> #prepares the args
>> for key, val in kwargs.items():
>> exec("%s = val"%key)
>> exec(self.script_py)
>> return ret
>
>
> So that I can do:
>
> s = Script() 
>
> s.script_py = """character.kill(another_character)
>
> character.win_exp()
>
> ret = character.lvl"""
>
>  
>
> new_lvl = s.run(character = some_player, another_character = 
>> another_player)
>
>  
> This all works just fine, but the problem is the security risk of the 
> exec...
> So the user could do:
>
>> s.script_py = "import os; os.system('shutdown -P 0')
>
>
>  And that's the smallest problem...
> So I was thinking if there is already something like that implemented, and 
> that I can add to my project easily, and found this PythonScript from Zope, 
> that does something like that.
>
> I just don't know if that is easily portable to another project, and if 
> I'm going to get what I want using this(let the users change the way the 
> script is ran). There is not much use if the users can only do : *"a + b 
> = c"*
> *
> *
> I also came across this post http://lybniz2.sourceforge.net/safeeval.html and 
> was thinking if there is something like that in exec.
> I friend of mine also have said that you can limit what the users can 
> import and use in some function(that I don't remember now).
>
> Thanks for the help.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/8ebW_NjxELkJ.
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: Password protected URLs Django - choose which to be protected also in admin

2012-04-15 Thread Kevin
Depending on how you are building your application, you have a few options 
here:

- If you need to protect specific rows in a database to only a handful of 
users, and make this configurable in admin site, use something like 
django-guardian to provide row-level permissions.

- If you absolutely need to pick and choose which URLs are going to require 
a login, the easiest way is to add a login field to your model, and check 
against that in a view.

- You can also create a brand-new model which has 1 field, a url to match 
against.  Then you create a simple middleware to check against this model 
to see if it is in the database, if it's there, then apply a login_required 
decorator to the view.  Here's a simple example:

class AdminProtectorMiddleware(object):
  def process_view(self, req, view_func, view_args, view_kwargs):
# check req.path against your model
if req.path in model:
  return login_required(view_func(*view_args, **view_kwargs))
else:
  return None

Code not tested, please refer to Django documentation, this is just an 
example on how it would be done.

On Saturday, 14 April 2012 13:13:30 UTC-5, rentgeeen wrote:
>
> Hello,
>
> I have quite interesting problem with password protected content in 
> Django. I can successfully protect my content or URLs in Django by using 
> "@login_required" decorator.
>
> Example:
>
> **Urls.py**
>
> urlpatterns = patterns('',
> url(r'^(?P[a-zA-Z0-9_.-]+)/$', 'example.sort'),
> )
>
> **Views.py**
>
> @login_required
> def categorysort(request, category_categoryurl):
> latest_images_list2 = 
> Category.objects.all().filter(categoryurl=category_categoryurl)
> return render_to_response('category.html', {'latest_images_list': 
> latest_images_list})
>
> So basically this example would work like this:
>
> Dynamic urls from DB all protected by password - because of 
> "@login_required" decorator
> http://www.example.com/category1/
> http://www.example.com/category2/
> http://www.example.com/category3/
>
> What I want to achieve is that for example in admin I want to specify that 
> some pages are with login and some not like in the example that with login:
>
> http://www.example.com/category1/
> http://www.example.com/category3/
>
> Without login:
>
> http://www.example.com/category2/
>
> That during creation in admin specifying the url (thats easy) but also 
> specify with checkmark do not need to login something like that.
>
> Can I use python in the views:
>
> If in db in Category login=True
> do this:
> @login_required
> def categorysort(request, category_categoryurl):
> latest_images_list2 = 
> Category.objects.all().filter(categoryurl=category_categoryurl)
> return render_to_response('category.html', {'latest_images_list': 
> latest_images_list})
>
> if Category login=False
> do this:
> def categorysort(request, category_categoryurl):
> latest_images_list2 = 
> Category.objects.all().filter(categoryurl=category_categoryurl)
> return render_to_response('category.html', {'latest_images_list': 
> latest_images_list})
>
> Disregard the syntax only explaining where I am going.
>
> Can you help me?
>
> Thanks
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/45L7P4zMKG4J.
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: Working Hello World Ajax example via django pleeeease

2012-04-15 Thread Kevin
Here you go, a fully working AJAX "Hello World" example in Django:

http://www.dajaxproject.com/dajaxice/

I use both Dajax and Dajaxice for a few projects of mine, check out my 
profile site for a fully working AJAX website made in Django:

http://iamkevin.ca/

Django even has specific form widgets in 3rd party apps which use AJAX, 
such as django-selectable, see my full tutorial here:
http://www.pythondiary.com/tutorials/add-ajax-powered-quick-search-any-django-site.html

The thing is, when making an application, think about what the framework 
can do for you and look for solutions which work with the framework.  Sure 
you can use "naked" jQuery, but why, when some developer devoted months of 
his/her time to build something that "just works".  With Dajax for example, 
you can code almost 95% of your client-side script in Python.  I use this 
for the "Contact" form on my personal profile page provided above.  Django 
does all the form validation, and displays any errors to the user, all 
using AJAX, and almost no JavaScript coded by me.

To take it a step further, you can use Pyjamas, which is Google Web 
toolkit(GWT) ported to Python.  Most of the API is the same(according to 
the developers).  I even wrote a short tutorial on how to integrate Pyjamas 
with Dajaxice for some nice Django AJAX goodness:

http://www.pythondiary.com/tutorials/working-pyjamas-and-dajaxice.html

Hopefully these resources help.  Do it the Pythonic way!

On Friday, 13 April 2012 02:08:19 UTC-5, Eli_West wrote:
>
> I've been attempting the most basic ajax call (.load()  )  through 
> django for over a month now - each time trying a different method or 
> tutorial none with success. Can someone post a working paradigm for 
> whatever django csrf, firefox, ect. workaround they use? 
>
> I can get jquery .load() to load content from an external file with 
> static files , no django. Same file served through django/templating 
> and the ajax is blocked. This is the general jquery call: 
>
> $(document).ready(function() { 
> $('.list').click(function () { 
> $('#message').load('namesinfo.htm li'); 
> return false; 
> }); 
> }); 
>
> To make things worse I found that Firefox/Chrome breaks Jquery's 
> sample 'Tabs: load content via ajax'  in the Themroller download. But 
> it works in IE :/. Same .load() calls occuring here. Just working w 
> static files no django. Could it be related to Firefox/Chrome? 
>
> I am pretty sure it is not: static file serving issues. I have heard 
> comments to follow django 'csrf / ajax' and included their sameOrgin 
> script to no avail. : 
>
> https://docs.djangoproject.com/en/dev/ref/contrib/csrf/ 
>
> A similar issue even though this guys solution is hard to understand: 
>
>
> http://stackoverflow.com/questions/6643242/jquery-load-not-working-in-django 
>
>
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/JAolJSG2LTUJ.
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.



Calling model methods from templates

2012-07-06 Thread Kevin
I'm fairly new to Django/Python so please bear with me.

I want to create some methods in my models that return boolean values 
(has_employees, etc) but I cannot seem to access the return value in the 
template.

Here's a cut-down example:

Model:

def fcnTrue():
return True

View:

return render_to_response('myapp/test.html',
  { 'varTrue' : True})

Template:

{% if varTrue %} varTrue = true {% endif %}
{% if fcnTrue %} fcnTrue = true {% endif %}

Expected output:

varTrue = true
fcnTrue = true

Actual output:

varTrue = true

What am I doing wrong?


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/-PrrNhcSJnkJ.
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: Calling model methods from templates

2012-07-06 Thread Kevin
I should mention this is happening in a loop iterating over a list of 
objects from my view -- the same object type where the fcnTrue method is 
defined. So I'm actually doing the following in a loop

{% if varTrue %} varTrue = true {% endif %}
{% if fcnTrue %} *myObj*.fcnTrue = true {% endif %}

(I realize the method must be called on an instance, and that's what I'm 
doing but failed to illustrate in my first post)

On Friday, July 6, 2012 2:26:22 PM UTC-5, Kevin wrote:
>
> I'm fairly new to Django/Python so please bear with me.
>
> I want to create some methods in my models that return boolean values 
> (has_employees, etc) but I cannot seem to access the return value in the 
> template.
>
> Here's a cut-down example:
>
> Model:
>
> def fcnTrue():
> return True
>
> View:
>
> return render_to_response('myapp/test.html',
>   { 'varTrue' : True})
>
> Template:
>
> {% if varTrue %} varTrue = true {% endif %}
> {% if fcnTrue %} fcnTrue = true {% endif %}
>
> Expected output:
>
> varTrue = true
> fcnTrue = true
>
> Actual output:
>
> varTrue = true
>
> What am I doing wrong?
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/_MWnTbiH4LIJ.
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: Calling model methods from templates

2012-07-06 Thread Kevin
Yes, the following fixed the problem:

def fcnTrue(self):
return True

I knew this would end up being some newbie mistake. Thank you!!

On Friday, July 6, 2012 2:48:59 PM UTC-5, Tomas Neme wrote:
>
> Abigger piece of your model would be nice, but arent you missing a "self" 
> in that method definition? TypeErrors would fail silently in the templates 
>
>
> -Mensaje original- 
> De: Kevin 
> Enviados:  06/07/2012 16:37:04 
> Asunto:  Re: Calling model methods from templates 
>
> I should mention this is happening in a loop iterating over a list of 
> objects from my view -- the same object type where the fcnTrue method is 
> defined. So I'm actually doing the following in a loop 
>
> {% if varTrue %} varTrue = true {% endif %} 
> {% if fcnTrue %} *myObj*.fcnTrue = true {% endif %} 
>
> (I realize the method must be called on an instance, and that's what I'm 
> doing but failed to illustrate in my first post) 
>
> On Friday, July 6, 2012 2:26:22 PM UTC-5, Kevin wrote: 
> > 
> > I'm fairly new to Django/Python so please bear with me. 
> > 
> > I want to create some methods in my models that return boolean values 
> > (has_employees, etc) but I cannot seem to access the return value in the 
> > template. 
> > 
> > Here's a cut-down example: 
> > 
> > Model: 
> > 
> > def fcnTrue(): 
> > return True 
> > 
> > View: 
> > 
> > return render_to_response('myapp/test.html', 
> >   { 'varTrue' : True}) 
> > 
> > Template: 
> > 
> > {% if varTrue %} varTrue = true {% endif %} 
> > {% if fcnTrue %} fcnTrue = true {% endif %} 
> > 
> > Expected output: 
> > 
> > varTrue = true 
> > fcnTrue = true 
> > 
> > Actual output: 
> > 
> > varTrue = true 
> > 
> > What am I doing wrong? 
> > 
> > 
> > 
>
> -- 
> You received this message because you are subscribed to the Google Groups 
> "Django users" group. 
> To view this discussion on the web visit 
> https://groups.google.com/d/msg/django-users/-/_MWnTbiH4LIJ. 
> To post to this group, send email to django-users@googlegroups.com. 
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com. 
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en. 
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/qdpYREF5ebQJ.
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.



Incorrect post URL on failed form validation

2012-07-13 Thread Kevin
I'm new to Django so hopefully this will be trivial to solve.

I have a table of data I display in a view along with a simple form to add 
a new row of data to the table:

def my_data_view(request, data_id):
myData = MyData.objects.get(pk=data_id)
if request.method == 'POST':
myForm = MyForm(request.POST)
else:
myForm = MyForm()
return render_to_response('myapp/mydata.html',
  { 'my_data' : myData,
'my_form' : myForm,},
  context_instance=RequestContext(request))


def add_new_row(request, data_id):
myData = MyData.objects.get(pk=data_id)
if request.method == 'POST':
myForm = MyForm(request.POST)
if myForm.is_valid():
# TODO insert new time into DB
return HttpResponseRedirect(reverse('senslog.views.mydata', 
args=(myData.id,)))
return my_data_view(request, data_id)

This works when I submit a valid form. However submitting an invalid form 
directs me from myapp/mydata/3 to myapp/mydata/addNewRow/3 which means when 
I submit the corrected form it posts to myapp/addNewRow/addNewRow/3 which 
is obviously not what I want. Any suggestions?

Thanks much!

Kevin

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/X0x91sUiuzoJ.
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.



Incorrect post URL on invalid form submissions

2012-07-13 Thread Kevin
I'm new to Django so hopefully this will be trivial to solve.

I have a table of data I display in a view along with a simple form to add 
a new row of data to the table:

def my_data_view(request, data_id):
myData = MyData.objects.get(pk=data_id)
if request.method == 'POST':
myForm = MyForm(request.POST)
else:
myForm = MyForm()
return render_to_response('myapp/mydata.html',
  { 'my_data' : myData,
'my_form' : myForm,},
  
context_instance=RequestContext(request))   
   
def add_new_row(request, data_id):
myData = MyData.objects.get(pk=data_id)
if request.method == 'POST':
myForm = MyForm(request.POST)
if myForm.is_valid():
# TODO insert new time into DB
return HttpResponseRedirect(reverse('myapp.views.mydata', 
args=(myData.id,)))
return my_data_view(request, data_id)

This works when I submit a valid form. However submitting an invalid form 
directs me from myapp/mydata/3 to myapp/mydata/addNewRow/3 which means when 
I submit the corrected form it posts to myapp/addNewRow/addNewRow/3 which 
is obviously not what I want. Any suggestions?

Thanks much!

Kevin

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/b3rgnekl6asJ.
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: Incorrect post URL on invalid form submissions

2012-07-13 Thread Kevin
I refactored this into a single view (similar to the Django form example) 
and it's working fine...not to mention it's much more DRY.

Feel free to disregard!

Kevin

On Friday, July 13, 2012 3:00:03 PM UTC-5, Kevin wrote:
>
> I'm new to Django so hopefully this will be trivial to solve.
>
> I have a table of data I display in a view along with a simple form to add 
> a new row of data to the table:
>
> def my_data_view(request, data_id):
> myData = MyData.objects.get(pk=data_id)
> if request.method == 'POST':
> myForm = MyForm(request.POST)
> else:
> myForm = MyForm()
> return render_to_response('myapp/mydata.html',
>   { 'my_data' : myData,
> 'my_form' : myForm,},
>   
> context_instance=RequestContext(request))   
>
> def add_new_row(request, data_id):
> myData = MyData.objects.get(pk=data_id)
> if request.method == 'POST':
> myForm = MyForm(request.POST)
> if myForm.is_valid():
> # TODO insert new time into DB
> return HttpResponseRedirect(reverse('myapp.views.mydata', 
> args=(myData.id,)))
> return my_data_view(request, data_id)
>
> This works when I submit a valid form. However submitting an invalid form 
> directs me from myapp/mydata/3 to myapp/mydata/addNewRow/3 which means when 
> I submit the corrected form it posts to myapp/addNewRow/addNewRow/3 which 
> is obviously not what I want. Any suggestions?
>
> Thanks much!
>
> Kevin
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/YjQRiYfGyokJ.
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.



Posting from HTTP to HTTPS on same domain results in CSRF failure

2012-10-31 Thread Kevin
Hello everyone,

  I am in the process of deploying a Django app which works both on HTTP 
and HTTPS connections, and require that some specific forms only submit via 
HTTPS.  I want the transition process over to HTTPS to be seamless for the 
end-user.  I am implementing this on a site-wide login form.

  Are there any workarounds for this or any middleware I can create to 
allow same domain HTTP to HTTPS transition without worrying about CSRF 
tokens being declined?  To ensure it wasn't a stale cookie issue, I just 
cleared my cookies before posting this.

  The csrf cookie is allowed for any connection, according to Firefox's 
cookie viewer, so shouldn't this mean that the cookie will be accepted over 
HTTPS?

Thanks in advance.

Django version is 1.4 branch.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/AR9a9jddb_QJ.
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: CBV for Nested Formesets

2012-11-11 Thread Kevin
This example code and example is based on the tutorial provided in your 
URL.  Formsets do not have a save_all() function by default.  The provided 
save_all() does not return back any object, so you should provide a 
success_url or override the function get_success_url() in your class.
You'll need to override the "form_valid()" method to call save_all(), 
rather than a simple save().  Here's a simple example:

class FormsetView(UpdateView):
model = Block
form_class = BuildingFormset
def form_valid(self, form):
self.object = form.save_all()
return super(ModelFormMixin, self).form_valid(form)

Use the other code from the blog. self.object is used if you don't specify 
a success_url, it uses it like self.object.get_absolute_url() to determine 
the URL you go to once the form is successfully saved.  This example code 
here should work, as the API for a Formset is very similar to a Form.

For more information on how to use class-based views, be sure to check out 
my latest blog post on the subject, it may provide some useful information 
on what functions to override:

http://www.pythondiary.com/blog/Nov.11,2012/mapping-out-djangos-class-based-views.html

Best Regards,
  Kevin Veroneau

On Friday, 9 November 2012 12:55:13 UTC-6, Lee Hinde wrote:
>
> I'm looking at these two blog posts to help me figure out nested formsets:
>
> http://yergler.net/blog/2009/09/27/nested-formsets-with-django/
>
> http://andreipetre.tumblr.com/post/26203496689/nested-formsets-with-django
>
> The example uses a function view and I was interested using class-based 
> views, but I can't figure out where to start.
>
> Thanks for any pointers.
>
>  - Lee
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/fAx0JHkuCOcJ.
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.



How many developers have moved to class-based views?

2012-11-11 Thread Kevin
Hello!

  I am curious of how many existing Django developers have moved over to 
class-based views or are still using the function-based ones.  I tend to 
use a mix depending on what I am trying to do.  I try to stick with 
class-based views, but fallback to function-based ones for process-based 
views, views which don't return a template but redirect after processing 
some end-user action.

  At first class-based views were a little confusing and the Django docs 
didn't really clarify how they work as well under the hood and the best 
practices on subclassing them.  It took me a little while to properly 
understand how they worked and what functions to override to do specific 
tasks.  This mainly involved reading the source code to see how everything 
worked.

Best Regards,
  Kevin Veroneau
  Python Diary

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/-b1KxU29PYwJ.
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.



Using os.fork() in a Django view

2011-08-18 Thread Kevin
Hello everyone,

  Firstly, I've been using Django for quiet sometime now and have
created a few projects and many of my websites run it.  I am wanting
to take my Django management to the next level, and need to use the
os.fork() function, here's why.

  I am planning on developing a web control panel for managing Django
instances in Django itself.  It only makes sense to make the control
panel in Django.  It will contain models for managing the actually
instances themselves and which users have control to them, and what
permissions these users have.  Features I plan on putting into the
control panel will be native Subversion support, using the Python
Subversion libraries.  This will allow projects to be versioned and
updated using Subversion rather than FTP/SFTP.  I currently use
Subversion in this manner already and it works wonderfully.  Other
features will include stopping and starting instances by use of
runfcgi management command.  I plan on using FastCGI support for
easier management and wider server support.  I currently use Nginx for
my website and it works nicely with Django's FastCGI server.  It will
allow database syncs and other tools normally supplied by manage.py.
I also plan on adding support for creating new projects and
associating it with an new Subversion repo.

  Now, the only hurdle I am currently trying to get past is the
ability to manage a Django site from within a different Django site.
I need to use Fork in order to make sure that the process uses the
settings.py from the other Django instance, and for it stays separate
from the Django control panel.  For example, a user could add some
malicious setting that could cause havoc when imported.  Process
separation is very important, and I would like some ideas on how I can
go about doing this to ensure a secure server.  Should I just spawn a
new Python process perhaps with a specific function to do the
management calls to be on the safe side?

Here's the code I will be needing to run in a os.fork():
from django.core.management import setup_environ, call_command
import settings
setup_environ(settings)
call_command('', **kwargs)

  So this would be in a separate function and called from a view which
uses os.fork(), or should I place os.fork() in the same function as
this code.  Of course the sys.path will be re-written before any
imports are done.  I plan on integrating Virtualenv with this.  The
model in the management Django project will contain the directories
and such that point to the Virtualenv.

  If anybody is interesting in helping with such a project, I am very
much open to any help.  I hope that this project may open Django to a
wider world of users, if the command-line Django admin stuff can be
done through a nifty web interface.  I have a server which it can be
developed and tested on as well.

-- 
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: Using os.fork() in a Django view

2011-08-19 Thread Kevin
Thank you very much for your suggestions about using Celery.  I'll
definitely look into this one.  Originally I was trying to avoid using
os.fork(), but was unsure what to use.  I will also look into the
uWSGI information provided as well.  Overall I would prefer to make
the entire system modular, much like how Django works.  If you use
Apache, then use this backend, if you use Nginx, then use this one.
Having a similar system to how Django currently works will make it
easy for any current Django developer/deployment administrator to work
with this control panel system.  This also opens the door to third-
parties creating their own backends for custom solutions.  Also a
backend system for storing data would be nice as well, say store
configuration in a model, or fetch and store it using LDAP.  Other
plugins, may include similar ones to what cPanel has, such as DNS
management and such.  Database management would be very basic, as the
editing of data is handled nicely by each projects Django admin site.
Database management would have the ability to administer databases,
and perform exports and imports of data.  Another ability I would like
to be plugable would be how users transfer their applications to the
server, currently I do plan Subversion support, but say a user prefers
GIT, or even the archaic and insecure FTP?  FYI, I use Subversion over
SSH.

  My ultimate goal with this project would be to bring a cPanel like
experience to Django administration, to better widen it's support
among "cheap hosts", where PHP currently(and unfortunately)
dominates.  Does cPanel even support Django type applications?  I
don't want to try re-inventing a wheel here.  I will look further into
panels for hosting Django projects and see what comes up.

On Aug 19, 2:24 am, Roberto De Ioris  wrote:
> Il giorno 19/ago/2011, alle ore 08:46, Kevin ha scritto:
>
> > Hello everyone,
>
> > Here's the code I will be needing to run in a os.fork():
> > from django.core.management import setup_environ, call_command
> > import settings
> > setup_environ(settings)
> > call_command('', **kwargs)
>
> >  So this would be in a separate function and called from a view which
> > uses os.fork(), or should I place os.fork() in the same function as
> > this code.  Of course the sys.path will be re-written before any
> > imports are done.  I plan on integrating Virtualenv with this.  The
> > model in the management Django project will contain the directories
> > and such that point to the Virtualenv.
>
> >  If anybody is interesting in helping with such a project, I am very
> > much open to any help.  I hope that this project may open Django to a
> > wider world of users, if the command-line Django admin stuff can be
> > done through a nifty web interface.  I have a server which it can be
> > developed and tested on as well.
>
> IMHO, this is the wrong approach from a security/sysadmin point of view.
>
> All of your django instances will run under the same uid. bad: all of your 
> users will be able
> to destroy other instances.
>
> If you want to call a setuid after each fork() you have to run the django 
> panel as root. even badder.
>
> As a rule, do not allow users generating fork(). You will need to implement a 
> throttling system (and this could be a pita).
>
> Even if modern os are stronger against fork bombing, you can destroy a whole 
> server easily.
>
> The most secure approach would be enqueing the tasks (you can use celery, 
> uWSGI spooler, or a dedicated daemon or whatever you want)
> and execute one by one (this solves fork bombing problem). You will lose 
> real-time, but you will gain security.
>
> Each task should run as a specific uid, so for each customer run another 
> daemon waiting for event (it will really run manage.py and runfcgi for you).
>
> Lot of work to do, you should take in account that the uWSGI project is built 
> with this target in mind (ISPs), and has systems to easily administering 
> multi-uid environments:
>
> http://projects.unbit.it/uwsgi/wiki/Emperorhttp://projects.unbit.it/uwsgi/wiki/FastRouterhttp://projects.unbit.it/uwsgi/wiki/LinuxNamespacehttp://projects.unbit.it/uwsgi/wiki/UseCgroups
>
> the main idea (already used by more than 20 ISPs worldwide) is having the 
> "panel" generating config files (they can be even taken via http dynamically)
> After you have a user instance running, you could add an embedded app on it 
> to launch tasks (so it will be the user app itself executing processes)
>
> Another (rawer, but funny, used by rosti.cz) approach is this one:
>
> https://github.com/creckx/uWSGI-Manager
>
> You can even start from the ground and re-implement all of this concepts in 
> pure-python (in thi

Pickling a QuerySet

2011-09-02 Thread Kevin
An interesting question here, not sure if anybody has tried to pickle
their QuerySets before.

Here's an example that does work:
entry_list = Entry.objects.all()
response =
HttpResponse(pickle.dumps(entry_list),mimetype='application/x-
pickle.python')
response['Content-Disposition'] = 'attachment; filename=kbase.dat'
return response

This is one of my views.  Now, I have another view that takes a file
upload to take in this pickled data.  My objective is to be-able to
export an entire model, or select items in a model.

It seems to unpickle just fine in the same site, and all the entry
objects in the queryset seem to be intact.  Now, what if, the target
site did not have the same entry objects and this pickle was imported
in?  The model is the exact same, just the actual data in the database
is different.  Is there an easy way to compare for differences and
sync the pickled data with the data in the database?  I won't run into
any conflicts as data is never removed on either end, data is just
merely added on one site, and I want to manually sync it with a
different site.

I'll be running a few tests to see what happens with this data and
post back here to let anybody who wants to know, know.

-- 
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: Pickling a QuerySet

2011-09-02 Thread Kevin
Wow!  This is very interesting and I did not expect the results.

The following:
>>> dat = pickle.loads(open('kbase.dat','rb').read())
>>> for item in dat:
...   item.save()

Worked flawlessly!  It recreated all the data in the database that I
removed to see what would happen if I unpickled it and saved it all.

I just attempted to also do the same with the data already existing,
and it did not create new entries in the database, but merely update
the existing ones.

Are there ways to test if the entry exists in the database after
unpickling the data?  As it currently stands it will overwrite
existing data with the new values contained in the pickle.

This would definitely be an interesting take on data backup or even
migration to a new database server.

On Sep 2, 5:05 am, Kevin  wrote:
> An interesting question here, not sure if anybody has tried to pickle
> their QuerySets before.
>
> Here's an example that does work:
>         entry_list = Entry.objects.all()
>         response =
> HttpResponse(pickle.dumps(entry_list),mimetype='application/x-
> pickle.python')
>         response['Content-Disposition'] = 'attachment; filename=kbase.dat'
>         return response
>
> This is one of my views.  Now, I have another view that takes a file
> upload to take in this pickled data.  My objective is to be-able to
> export an entire model, or select items in a model.
>
> It seems to unpickle just fine in the same site, and all the entry
> objects in the queryset seem to be intact.  Now, what if, the target
> site did not have the same entry objects and this pickle was imported
> in?  The model is the exact same, just the actual data in the database
> is different.  Is there an easy way to compare for differences and
> sync the pickled data with the data in the database?  I won't run into
> any conflicts as data is never removed on either end, data is just
> merely added on one site, and I want to manually sync it with a
> different site.
>
> I'll be running a few tests to see what happens with this data and
> post back here to let anybody who wants to know, know.

-- 
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: Multiple Database Routing Based on Site

2011-09-02 Thread Kevin
The only solution I can directly think of, since the SITE_ID is in
settings.py would be to use some python logic to determine the
database for that site.

eg.
if SITE_ID == 1:
   ...  Database settings for site 1 here ...

Use an if-then like this in your settings.py.

Now if what your going after is storing the SITE_ID in a user's
profile and using that for routing, this will be more complex, as you
will need to code a new databasebackend to perform the routing, and
perhaps some middleware and an authbackend.

Mind you, I haven't done much work on multiple databases, so these are
just ideas on how I think it might be done.

On Sep 1, 9:54 pm, Terribyte  wrote:
> I had a kind of crazy idea and I wanted to bounce it off of some
> people with a lot more django experience than I.
>
> Here's my scenario...
>
> I would like 1 code base, this code base services potentially hundreds
> of businesses, each of which I want to have a copy of the same schema
> but with data only relevant to that business.
>
> Basically my idea is the following
> If the model is a Site object or User object, route to the default
> database, otherwise route reads and writes to a database name I'll set
> in the sites table.
>
> The trick is I need to set the SITE_ID for the current request, and
> I'm not sure exactly When that should happen (after login of course),
> or if this idea is even workable.

-- 
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: Pickling a QuerySet

2011-09-02 Thread Kevin
Thank you for this Tom, it's been awhile since I read about the
QuerySet API.

Kayode:  I'm not sure you can export such data as a CSV.  Why do you
need the date exported in this manner?  You can export the exact data
from the database into a CSV, but re-importing would need a bit of
work.  I have a routine which imports from a CSV adding new data which
currently does not exist based on a unique field.  It does not update
the data from CSV, although it is possible.  As long as you export
either the primary key or have a unique field.

On Sep 2, 7:26 am, Tom Evans  wrote:
> On Fri, Sep 2, 2011 at 11:05 AM, Kevin  wrote:
> > An interesting question here, not sure if anybody has tried to pickle
> > their QuerySets before.
>
> Not only have people tried this before, but there is an entry in the
> manual about it:
>
> https://docs.djangoproject.com/en/1.3/ref/models/querysets/#pickling-...
>
> wrt to your later question - how can you tell if the object already
> exists in the database - you need to understand what django does when
> you save a model, and how to customize that behaviour.
>
> https://docs.djangoproject.com/en/1.3/ref/models/instances/#what-happ...https://docs.djangoproject.com/en/1.3/ref/models/instances/#how-djang...https://docs.djangoproject.com/en/1.3/ref/models/instances/#forcing-a...
>
> 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.



Helping someone move from Joomla to Django

2011-09-28 Thread Kevin
Hello,

  I have a friend who is doing website design, not any backend
programming tasks.  He actually would like me to do the backend
coding.  The unfortunate case is that he is currently using Joomla,
which I know almost nothing about, and the apps/plugins for it are not
reusable in other website frameworks, not even other PHP frameworks,
icky!  I really enjoy Django because if you create a reusable app, and
say use Pinax, it will most likely work as well in say Django-CMS or
another CMS build on top of Django and Python.

  This question is really for anyone who has previously used Joomla
and knows how the editor works for web designers and content
managers.  I have seen and used it's site manager only a few times.  I
took a look at both Pinax and Django-CMS.  After looking at Django-
CMS, it has a similar feel to that of Joomla with in page editing and
is overall very simple for a content manager/web designer.  It's also
very straight forward and supports a lot right out of the box.

  My current task with my friend is to create a music player, I have
been working with jPlayer recently and finding out how I can integrate
it with Joomla, haven't took too much time yet.  I'm quiet happy about
that choice now, since Django-CMS actually has a plugin just for this
player.

  How would you recommend I go about this task of moving my friend
over to a Django/Python based system over a Joomla/PHP based system?
How easy will it be to say convert a Joomla template to a Django
compatible one?  This will be another issue, is template management.
Since there is really no standard for website templates, every CMS/
framework uses it's own system.  I believe Joomla's templates even
embed PHP code directly into the template itself, another icky.

  I am going to pitch the idea and use the jPlayer plugin for Django-
CMS as a sweet spot.  I'm also tempted on copying over all the
existing content to a Django-CMS site to show him how it will look and
feel.

  He is requesting some other interesting features, which apparently
someone else is working on implementing, and it's actually taking this
other person a few days, or maybe weeks to add.  Where I know I can
implement it in Django in a matter of hours.  If the other person is a
PHP programmer, me pitching this idea may scare the other person.  PHP
programmers are sometimes very proud and are hard to turn.  I, myself
used to be like this, that is until I found myself getting byte by a
huge Python, it's venom changed my life entirely.  I saw the light.

  What is everyone elses opinions on development in Django verses a
rival CMS such as Joomla?  Just looking at how the Joomla source tree
is scares me from even looking at how to code anything in it.  After
using Django for awhile, I like how nicely everything is organized.

-- 
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: Community Wiki/CMS app

2011-09-28 Thread Kevin
I will recommend using Pinax for this particular type of site.

http://pinaxproject.com/

I am not sure if Pinax has an included Mailing list app, but there
should be one available at djangopackages.com

If Pinax is a little too much, try out Django-cms:  https://www.django-cms.org/

Django-CMS even has a nice demo site where you can try out all the
main features that come with it out of the box.

For your Mailing list app, check out Colibri:
http://labs.freehackers.org/projects/colibri/wiki

Both Pinax and Django-CMS have nice documentation for installation and
testing.  Deploying is like any other Django project.

On Sep 28, 1:59 am, Thomas Guettler  wrote:
> Hi,
>
> a group of intelligent, but non computer-nerd people, asked me for help. They 
> want to build a community page:
>
>  - simple homepage/wiki
>  - news
>  - members with login
>  - mailing list
>
> I develop with django daily. Since I don't want to reinvent the wheel,
> I search django app which can handle most of this.
>
> I have seen the comparison grids onhttp://djangopackages.com/but I am unsure, 
> and don't
> have much time for the decision.
>
> Any feedback welcome,
>
>   Thomas Güttler
>
> --
> Thomas Guettler,http://www.thomas-guettler.de/
> E-Mail: guettli (*) thomas-guettler + de

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

2011-09-28 Thread Kevin
You can see a list of all available Django wiki software here:

http://www.djangopackages.com/grids/g/wikis/

Also note that Pinax also comes with a wiki App you can use as well,
plus many other features.

On Sep 28, 6:17 am, Anoop Thomas Mathew  wrote:
> Hi,
>
> If you want a basic wiki, you can tryhttp://uswaretech.com/demo/djikiki/
> Its not maintained well now, still, this might be enough to start with.
>
> Thanks,
> Anoop
>
> atm
> ___
> Life is short, Live it hard.
>
> On 28 September 2011 14:20, Kirupashankar Sampath 
> wrote:
>
>
>
>
>
>
>
> > I am relatively new to django..I am trying to think of ways to
> > implement mediawiki concepts in a django wikipage...any ideas of
> > how to approach..
>
> > --
> > You received this message because you are subscribed to the Google Groups
> > "Django users" group.
> > To post to this group, send email to django-users@googlegroups.com.
> > To unsubscribe from this group, send email to
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group at
> >http://groups.google.com/group/django-users?hl=en.

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

2011-09-29 Thread Kevin
Pinax is live and well as they did a recent presentation at PyCon
2011, and the PyCon website is even made in Pinax.

http://us.pycon.org/

List of complete sites currently built on Pinax: http://pinaxproject.com/sites/

The most impressive site in the list is actually GirlGamer.com, their
website is very impressive and highly customized.

http://girlgamer.com/

I'm sure they never committed a new update as they wanted to use the
current commit to showcase their work at PyCon.  I could just imagine
them checking out a revision which had errors and then attempting to
showcase their work in front of thousands of people.  It would be
almost like that time when Bill Gates was showing off Windows 98 and
plug and play support with a printer...  It blue screened right on
CNN.

I'm quite sure once PyCon simmers down, Pinax will receive another
update and perhaps more interested developers from PyCon itself.

On Sep 28, 9:26 am, Thomas Guettler  wrote:
> Am 28.09.2011 10:08, schrieb Kevin:
>
> > I will recommend using Pinax for this particular type of site.
>
> >http://pinaxproject.com/
>
> > I am not sure if Pinax has an included Mailing list app, but there
> > should be one available at djangopackages.com
>
> > If Pinax is a little too much, try out Django-cms:  
> > https://www.django-cms.org/
>
> Have you every used Pinax? I looked at the mailing list  Maybe I am 
> wrong, but I can't see a healthy community there.
>
> Same here: nearly no code changes in the last 
> weeks:https://github.com/pinax/pinax/commits/master/
>
>   Thomas
>
> --
> Thomas Guettler,http://www.thomas-guettler.de/
> E-Mail: guettli (*) thomas-guettler + de

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



MAPI Email Backend available for testing

2011-10-03 Thread Kevin
I noticed that Django does not include a MAPI Backend for sending
Email, for some environments having this type of backend is essential
for testing and debugging.  I do not recommend it as a production
backend unless you are a full exchange shop, as some are and do not
offer SMTP for internal applications.

I do not recommend using this as a production backend as it has not
yet been tested, it is recommended that you have experience coding
MAPI with Python before using this backend.  This backend is only
compatible on Windows machines using the Python extensions as it talks
to Outlook directly, there are no sockets involved, so it makes it
very useful in environments with a tight firewall.  Without further
delay here is the backend, as I said I haven't gotten around to
testing it and I do need some help adding support for the subject line
as this is my first Email backend attempt:

import win32com.client.dynamic, sys, re
import threading

from django.conf import settings
from django.core.mail.backends.base import BaseEmailBackend

class EmailBackend(BaseEmailBackend):
"""
A wrapper that manages the MAPI network connection.
"""
def __init__(self, MAPIProfile=None, fail_silently=False,
**kwargs):
super(EmailBackend,
self).__init__(fail_silently=fail_silently)
self.MAPIProfile = MAPIProfile or settings.MAPIProfile
self.connection = None
self._lock = threading.RLock()

def open(self):
"""
Ensures we have a MAPI Session to the exchange server. Returns
whether or
not a new connection was required (True or False).
"""
if self.connection:
# Nothing to do if the connection is already open.
return False
try:
self.connection = 
win32com.client.dynamic.Dispatch("MAPI.session")
if self.MAPIProfile <> None:
self.connection.Logon(self.MAPIProfile)
else:
self.connection.Logon("MS Exchange Settings")
return True
except:
if not self.fail_silently:
raise

def close(self):
"""Closes the connection to the exchange server."""
try:
try:
self.connection.Logoff()
except:
if self.fail_silently:
return
raise
finally:
self.connection = None

def send_messages(self, email_messages):
"""
Sends one or more EmailMessage objects and returns the number
of email
messages sent.
"""
if not email_messages:
return
self._lock.acquire()
try:
new_conn_created = self.open()
if not self.connection:
# We failed silently on open().
# Trying to send would be pointless.
return
num_sent = 0
for message in email_messages:
sent = self._send(message)
if sent:
num_sent += 1
if new_conn_created:
self.close()
finally:
self._lock.release()
return num_sent

def _sanitize(self, email):
name, domain = email.split('@', 1)
email = '@'.join([name, domain.encode('idna')])
return email

def _send(self, email_message):
"""A helper method that does the actual sending."""
if not email_message.recipients():
return False
recipients = map(self._sanitize, email_message.recipients())
outbox = self.connection.OutBox.Messages.Add('Django sent
message',email_message.message().as_string(),'CMC: IPM')
for recipient in recipients:
recip = outbox.Recipients.Add(Name=recipient, Type=1)
recip.Resolve()
try:
outbox.Update()
outbox.Send()
self.connection.DeliverNow()
except:
if not self.fail_silently:
raise
return False
return True

As you can see I used the SMTP backend as a base, and modified all the
functions to replace them with MAPI session and sending functions
instead.  Hopefully this helps some Windows django developers or
encourages Windows developers to take the leap.

It's actually a funny story on how I even got around to creating this
backend.  I am working on a tool in my workplace to improve my own
productivity, and since I use Python and Django at home for web
projects, I thought I'd use it at work to develop a tool.  This tool
automates a lot of my work, and all that's left is to implement an
Email sending function.  Since I need special developer access to use
the internal SMTP server, I thought of the nifty idea of using my
Outlook client as a host to send out Emai

Re: MAPI Email Backend available for testing

2011-10-03 Thread Kevin
   (mapitags.PR_ADDRTYPE_A, 'SMTP'),
(mapitags.PR_DISPLAY_NAME_A, recipient))

def _send(self, email_message):
"""A helper method that does the actual sending."""
if not email_message.recipients():
return False
recipients = map(self._sanitize, email_message.recipients())
message = self.connection.CreateMessage(None,0)
pal = []
for recipient in recipients:
pal.extend([self._makeentry(recipient, mapi.MAPI_TO)])
# add the resolved recipients to the message
message.ModifyRecipients(mapi.MODRECIP_ADD,pal)
 
message.SetProps([(mapitags.PR_BODY_A,email_message.message().as_string()),
(mapitags.PR_SUBJECT_A,'Django sent message')])
self.connection.SaveChanges(0)
message.SubmitMessage(0)
return True


On Oct 3, 4:01 am, Kevin  wrote:
> I noticed that Django does not include a MAPI Backend for sending
> Email, for some environments having this type of backend is essential
> for testing and debugging.  I do not recommend it as a production
> backend unless you are a full exchange shop, as some are and do not
> offer SMTP for internal applications.
>
> I do not recommend using this as a production backend as it has not
> yet been tested, it is recommended that you have experience coding
> MAPI with Python before using this backend.  This backend is only
> compatible on Windows machines using the Python extensions as it talks
> to Outlook directly, there are no sockets involved, so it makes it
> very useful in environments with a tight firewall.  Without further
> delay here is the backend, as I said I haven't gotten around to
> testing it and I do need some help adding support for the subject line
> as this is my first Email backend attempt:
>
> import win32com.client.dynamic, sys, re
> import threading
>
> from django.conf import settings
> from django.core.mail.backends.base import BaseEmailBackend
>
> class EmailBackend(BaseEmailBackend):
>     """
>     A wrapper that manages the MAPI network connection.
>     """
>     def __init__(self, MAPIProfile=None, fail_silently=False,
> **kwargs):
>         super(EmailBackend,
> self).__init__(fail_silently=fail_silently)
>         self.MAPIProfile = MAPIProfile or settings.MAPIProfile
>         self.connection = None
>         self._lock = threading.RLock()
>
>         def open(self):
>         """
>         Ensures we have a MAPI Session to the exchange server. Returns
> whether or
>         not a new connection was required (True or False).
>         """
>         if self.connection:
>             # Nothing to do if the connection is already open.
>             return False
>         try:
>                         self.connection = 
> win32com.client.dynamic.Dispatch("MAPI.session")
>                         if self.MAPIProfile <> None:
>                                 self.connection.Logon(self.MAPIProfile)
>                         else:
>                                 self.connection.Logon("MS Exchange Settings")
>                         return True
>                 except:
>             if not self.fail_silently:
>                 raise
>
>     def close(self):
>         """Closes the connection to the exchange server."""
>         try:
>             try:
>                 self.connection.Logoff()
>             except:
>                 if self.fail_silently:
>                     return
>                 raise
>         finally:
>             self.connection = None
>
>     def send_messages(self, email_messages):
>         """
>         Sends one or more EmailMessage objects and returns the number
> of email
>         messages sent.
>         """
>         if not email_messages:
>             return
>         self._lock.acquire()
>         try:
>             new_conn_created = self.open()
>             if not self.connection:
>                 # We failed silently on open().
>                 # Trying to send would be pointless.
>                 return
>             num_sent = 0
>             for message in email_messages:
>                 sent = self._send(message)
>                 if sent:
>                     num_sent += 1
>             if new_conn_created:
>                 self.close()
>         finally:
>             self._lock.release()
>         return num_sent
>
>     def _sanitize(self, email):
>         name, domain = email.split(

Re: Helping someone move from Joomla to Django

2011-10-06 Thread Kevin
I might say just 'WOW!'...  I just took some time to go over the
Joomla documentations to see what I was up against.  Why do developers
even use this thing?  Sure maybe the frontend is nice and polished,
but the backend looks horrible, at least compared to Django.  Django
code looks much more cleaner, and what's up with this statement at the
top of almost every page:



If I had to place that in all my source code, I'd go crazy!  You
shouldn't need to use such a thing in sane programming.

If you look at how they built their MVC implementation, it's rather
messy and very confusing.  On top of that, Django documentation and
tutorials are much more better organized.  I couldn't a non-HelloWorld
example, such as even a Poll example which Django uses.

The template system is not really a template system, but rather a hack
and uses PHP inline to implement functionality.  There appears to be
some template tags, but aren't compatible with web authoring software,
as the tag use < and >.

There doesn't seem to be an ORM of any kind, or lack thereof an
example for it.  The database example I stumbled upon in the
documentation uses RAW SQL code.  This can be prone to security issues
if not properly coded and filtered.

Django really needs to be advertised more, and perhaps an easier
method to deploy and manage templates/apps.  I can see how Joomla has
the community it has, installing templates and components(as they call
them) are very simple and mostly pain-free.

Does Django have an app which makes managing templates and apps and
the settings.py file easy for novice users?  I, myself am able to use
Django quite fully, but for new users who might be looking for an
alternative from other frameworks, should have a good solution for
this.

The ability for new developers to easily "dive in" and test drive
Django will be a nice bonus.  Given that a good chunk of the world
uses Windows on their desktop PCs, a nice easy way to get a Django
development environment up and running should be looked into.  I
recently found a nice website(which is no longer there),
instantdjango.com, they provided a nice self-extracting 7zip EXE file
with a contained django environment.  A batch file launched the
command prompt with the correct python environment variables set, it
was rather nice.  There needs to be an official django release of such
a development environment.  I still have a copy of the downloaded
environment if anybody wants to check it out/distribute it amongst
friends:

http://c18321.r21.cf1.rackcdn.com/django.exe

I can see plenty of users moving over to Django if they just saw how
much easier it is to code in Django.

On Sep 29, 4:42 am, Baurzhan Ismagulov  wrote:
> On Wed, Sep 28, 2011 at 11:19:30PM -0700, Derek wrote:
> > > How would you recommend I go about this task of moving my friend
> > > over to a Django/Python based system over a Joomla/PHP based system?
> ...
> > > He is requesting some other interesting features, which apparently
> > >someoneelse is working on implementing, and it's actually taking this
> > > other person a few days, or maybe weeks to add. Where I know I can
> > > implement it in Django in a matter of hours.
> ...
> > > What is everyone elses opinions on development in Django verses a
> > > rival CMS such as Joomla?
>
> If I had to add features or integrate stuff, I'd stay away from Joomla
> (or any heavyweight CMS like Zope / Plone, for that matter). Can you
> implement or at least prototype a few URLs in Django? In that way you
> could answer your question about templates and demonstrate the
> advantages to your friends.
>
> If you don't 
> succeed,http://groups.google.com/group/django-users/browse_thread/thread/4981...
> could be an option.
>
> With kind regards,
> --
> Baurzhan Ismagulovhttp://www.kz-easy.com/

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



Re: Beginner a bit lost - need some pointers please

2011-10-06 Thread Kevin
For that it's worth, I deploy my Django projects using Nginx and
FastCGI.  I find this solution to be working rather nicely, Nginx
takes care of serving all the static content really fast and passes
the app requests to Django.  It's really quick and easy to set-up
too.  I prefer Nginx as I can better control what gets through from
the browser to the Django application.  Say, if I don't want some URLs
to accept POST data, or not pass certain header information.  I can
also use Nginx to graph apps from different frameworks together into
one domain name, I think Apache2 can do this as well.

On Oct 6, 3:14 am, Daniel Roseman  wrote:
> > On Wednesday, 5 October 2011 20:55:33 UTC+1, Chris Green wrote:
>
> I'm an experienced programmer (started around 1971 or so!) and I've done
>
>
>
>
>
>
>
>
>
> > lots of things over the years, much of my background is in Unix (Solaris).
> > In the last few years I have done quite a lot of web related stuff.
>
> > I'm trying to get my mind round django.  I have it installed on my
> > unbuntu server, it works, I've worked through tutorials 1 and 2 and a
> > bit of 3.  I can get the admin screens up and the basics of the polls
> > example work.
>
> > However two rather basic things still elude me:-
>
> >     Where/how do I actually start creating the top level/page of a web
> >     site?   Do I just open vi and create some HTML and embed django
> >     code?  That seems unlikely but I can't see anywhere that tells me
> >     what the code that creates a django site looks like and/or where it
> >     resides.   An actual example of a two or three page working django
> >     based web site would be a huge help.
>
> You *really* need to do the tutorial. If you think that "creating HTML and
> embedding Django code" is how it works, then you haven't read it. That's not
> how it works at all.
>
> If you want to see some working Django sites, look 
> athttp://www.djangosites.org/with-source/- but none of them will make much
> sense until you've got the basics.
>
> >     I can't see anywhere that seems to tell me the issues involved with
> >     moving from using the built in web server to using apache2 (or
> >     whatever, I have apache2 on my system).
>
> Don't worry about this yet. Learn Django first, then worry about deployment.
>
> --
> DR.
>
>
>
>
>
>
>
>

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



Re: Your Impressions on DjangoCMS

2011-10-07 Thread Kevin
I don't have any professional experience with Django-CMS, however I
did dive into it and try out their demo site and even test out an
installation myself on a server.  My first impressions via the demo
site they provided were very good, I enjoyed the feel of it and how
easy it was to add content and build plugins.  The installation onto a
server is a different impression all together...  Firstly they didn't
provide the nice templates to start out with like they provide with
the demo site, so figuring out how to build the template and set-up
the JS/CSS was interesting.  On top of that, following the
installation guide was a failure, and couldn't get it to run
properly.  I ultimately used the quick start guide to get it up and
running much more quickly.

In the end, the installation could be much more elegant, rather than
having to jump through hops to make it work.  Comparing this to the
installation of Pinax, I really enjoyed how much effort that project
put into making Pinax as easy as possible to get an environment up and
running.  In the end, I'm more of a developer who likes to build the
project from scratch and add reusable apps as I see fit.  This way I
have full control over what apps are included in my project.

I will recommend attempting to convert the backend of your companies
current CMS to Django.  If the frontend is not as meshed with the
backend code, there should be little problems with interchanging the
backend to a Django-based solution while keeping your awesome sounding
frontend that's tried and true by your clients.  I recently converted
an old PHP site's backend, keeping all the same HTML/JS/CSS files
almost the same with little modifications, only needing to change the
path which AJAX connects to on the server.  Mind you, in this project
I didn't have any PHP code embedded into the HTML file, which
shouldn't be done anyways.  Backend and Frontend code should always
remain separate, it makes the parts easier to interchange and port to
newer backend platforms in the future.

On Oct 6, 3:57 pm, colinta  wrote:
> I would love to hear some professional opinions on how easy it is to
> create, maintain and support a DjangoCMS-based website.  The only
> curve ball is that the client will need customizable forms.  Otherwise
> it's a pretty standard site.
>
> Very recently - last week - the company I work for announced that we
> are switching from PHP, where we have built a robust lovely framework
> (in PHP, though, so ug) and really whiz-bang-neat CMS (very drag-and-
> droppy, clients love it).  We've settled on Python+Django as our new
> stack, where we will call upon the resources of the open-source
> community so that we can focus on *building sites* rather than adding
> features and bug fixing our internal framework.
>
> But the question remains open whether we should build this *next*
> project using our tried-and-true framework & CMS, or whether we'll use
> DjangoCMS for the first time.
>
> So whaddya say!  Any thoughts?  Strong opinions one way or the other?
> I will really appreciate the insight.

-- 
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: Need advice on ForeignKey query problem.

2011-10-11 Thread Kevin
What your looking for is here in the documentation:
https://docs.djangoproject.com/en/1.3/topics/db/queries/#related-objects

records = models.Facility.objects.get(pk=62).schedule_set.all()

On Oct 10, 8:19 pm, "Sells, Fred" 
wrote:
> I've got these two tables defined where a Facility can have multiple
> schedules but a schedule can have only one facility.
>
> class Facility(models.Model):
>     id = models.CharField(max_length=2, primary_key=True)
>     name = models.CharField(max_length=30)
>     
>
> class Schedule(models.Model):
>     facility = models.ForeignKey(Facility)
>     ...
>
> I would like a query that returns one record for each Facility and that
> record would contain at least the id (if not more) of ALL linked
> schedules.  So far I've only been able to return a queryset that
> contains a record for each schedule at each facility.  My last attempt
> looked like this...
>
>     records = models.Facility.objects.select_related().filter(id='62')
>
> is there a pythonic way to do this?  I only need reasonable efficiency,
> there's not that much data and the query is probably only run 200 times
> in an 8 hour shift.

-- 
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: Ajax replacement in django

2011-10-17 Thread Kevin
Just a simple thought, if you'd prefer to avoid JavaScript/client-side
scripting entirely, and only code using Python.  It might be an idea
to look at Pyjamas to generate your page.  It technically uses Ajax,
but from the programmers point of view, it feels more like coding a
desktop application.  The exposed functions on the django server are
mapped as Python functions in pyjamas, so coding Ajax in this method
seems very natural for a python programmer.  Depending on what type of
web application you are attempting to build, this might be a good
solution for you.  The tools you use all come down to what the end
result should be.  Is it a website or a web application?  Should the
look and feel be more like a desktop app, or a newspaper?  Pyjamas
also strives for cross-platform/browser compatibility for a true code
once, run anywhere feeling without the Java.  Pyjamas also supports
some HTML5 features such as the canvas to further a desktop app like
feeling for the end user.  One can also mix traditional HTML and a
Pyjamas app onto a single page.  If, for example, your project
requires a small widget which updates from the server constantly(news
feed/chatbox), you can make the entire site using standard HTML/CSS
and embed a Pyjamas app into a DIV tag on the site.

Hopefully this gives you some ideas.

On Oct 14, 7:41 am, Phang Mulianto  wrote:
> ajax use usualy load a div part of html with new content fetch from the
> server when user do something,like click a submit button. and django process
> the request as a simple usual request.
>
> i have using prototype+scriptocolous for the simple syntax to make an ajax
> form.
> i see the jquery version also but a bit trouble coz need to add the event
> manually.
>
> and remember the crsf token when using ajax request..will need it generated
> properly..
>
> anyone using prototype to?
>
> or anyone have better way with ajax
> On Oct 14, 2011 7:47 PM, "Babatunde Akinyanmi"  wrote:
>
>
>
>
>
>
>
> > From what Iankesh said initially, I think he is having problems using
> > ajax to load part of a page not ajax as a whole.
> > Iankesh, it is possible to load only a portion of a page with ajax.
>
> > On 10/13/11, Sells, Fred  wrote:
> > >> On Wed, Oct 12, 2011 at 9:17 AM, lankesh87 
> > wrote:
> > >> >  I am developing a web application where i need ajax like features.
> > >> > But I don't want to use ajax, so my question is- "is there any way to
> > >> > perform ajax like functions in django?"
>
> > > Use Flex, it's easier.
>
> > > --
> > > 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.
>
> > --
> > Sent from my mobile device
>
> > --
> > You received this message because you are subscribed to the Google Groups
> > "Django users" group.
> > To post to this group, send email to django-users@googlegroups.com.
> > To unsubscribe from this group, send email to
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group at
> >http://groups.google.com/group/django-users?hl=en.

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

2011-10-17 Thread Kevin
This is rather common when moving over from the dev server to a
production environment.  Sometimes it can be tricky to map all the
static URL paths in the web server serving the static content, such as
the JavaScripts which treemenus uses.  I haven't used treemenus
before, but from past experiences with working with different apps and
moving over to a production environment, I can advise the following
steps to troubleshoot.

* Compare the output HTML from both the dev server and the production
server.
* Make sure all the resources pointed to by the production server
exist, eg. /media/js/mycode.js, in Firefox you can click these
resources in the source view.
* If any resources return a Django error, or a 404 page, that's where
your problem lies.  You will need to create a few location {} blocks
in nginx to point to the resources on the production server.  You
should have already done this for the admin app.
* Make sure you have everything needed installed on the production
server, although if anything was missing Django would have gave an
ImportError exception, it's still good to check.
* Be sure that nginx is passing all the header information to the
application, I'm not sure how wsgi works, I personally use FastCGI
with Django and Nginx.
* Check the nginx log files to see if there are any 404 or 500 error
messages, the page won't display these for resources such as a missing
JS/CSS file.

Hope this helps in your troubleshooting efforts.

On Oct 17, 5:40 pm, Alastair Campbell  wrote:
> Hi everyone,
>
> I got a surprise when using treemenus, where it worked really well on
> my local dev (django-server) , but disappeared on live (nginx using
> mod_wsgi on debian).
>
> I installed the treemenu app, imported the data (menu items) from a
> datadump of my local app, and uploaded the templates that use
> treemenu.
>
> No error, but no output either.
>
> When I went to the Admin, the menus were there, but editing the items
> resulted in a blank editing area.
> I switched on debug briefly on live (in maintenance mode), but no
> error was reported.
>
> Has anyone else experienced blank output under mod_wsgi but not local dev?
>
> If not, could someone suggest where I could start debugging? Usually I
> check logs for errors or use the django error page, but both are blank
> :-(
>
> I've had to hard-code the navigation across the site in the meantime,
> which is going to get time consuming very quickly!
>
> Kind regards,
>
> -Alastair
>
> PS. a belated thank you to Bruno Desthuilliers for help with my
> category question before, it worked!

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



Getting into professional django development

2011-10-17 Thread Kevin
Hello everyone!

  I have been using Django for about a year now and feel that I want
to take my experience to the next level.  I have created a few website
using Django to test my skills, although not for anyone specific.  I
am creating this thread as I will like to ask current Django website
developers what tools and apps are crucial to be learned.

Currently I have been focusing on the following:

* Django 1.2
* Django-guardian
* JQuery(although not specific to django)
* Pyjamas(nice alternative to GWT and works with django)
* Began learning Pinax(based on Django 1.1)
* Began learning Django-cms
* A few other, but cannot remember off the top of my head.

The problem is that I'm not really sure what Django apps to learn due
to the overwhelming amount of apps that do the same thing, just
differently.  I choose Django-guardian over Django-authority, for
example.

The next django app I plan on learning is Djax and Djaxice.

Which Django apps does everyone use in their Django projects for your
company/clients?  I'd rather not learn something which is either going
out of style, out of style, out dated, or barely used.  I cannot take
this type of experience with me to work on a larger scale project.

You must agree that when you look at the djangopackages website, there
are an overwhelming amount of apps which do almost the exact same
thing.  I'm not sure how it feels the download counts, or the other
data.  I would hope from PIP, but not sure if it has an open API for
polling download counts and such data about packages.

-- 
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 into professional django development

2011-10-18 Thread Kevin
Thank you all for your great feedback!

I will definitely take Andre's to-do list there, I hear REST is
definitely something to master.  I've been needing to learn Celery for
a project I want to work.  I have worked with caching, although I do
not see myself as a master, I do know my way around the documentation
and the important functions for it. I have written raw SQL before when
I used to code in PHP.  Exporting to excel I have also done using the
CSV package in Python, I think there's also a Django document on
exporting to CSV and PDF.

Kurtis, I will definitely take you up on that offer.  Experience is
worth a lot.  I am currently working on a project for a friend in
Django, it's a concept similar to GetGlue.com, I've already done most
of the work and everything already works rather nicely.  Basically,
the entire GetGlue interface has been copied, with the backend work
done using Django.  Of course the front-end was not copied directly,
just re-created using my own front-end code, but in the end functions
exactly like GetGlue does.

On Oct 19, 12:21 am, Kurtis Mullins  wrote:
> I recommend South as well. Also, if you're interested -- I *might* be able
> to connect you with some part-time work on a current project. Contact me
> privately if want to know more. I need to talk it over with the big-man who
> signs the pay-check but I could definitely use the help.
>
> On Tue, Oct 18, 2011 at 10:28 PM, kenneth gonsalves
> wrote:
>
>
>
>
>
>
>
> > On Tue, 2011-10-18 at 16:00 +0100, Tom Evans wrote:
> > > I can't stand incorrect pedantry - this is my curse.
>
> > > Kenneth actually said that "1.3 is ancient, you should be using
> > > trunk", which he corrected to "1.2 is ancient, you should be using
> > > trunk". His advice, regardless of which version you look at, is to use
> > > trunk - not the latest stable release.
>
> > if you are playing around and learning - production is an entirely
> > separate issue which depends on many factors, a lot of which are beyond
> > the control of the developer.
> > --
> > regards
> > Kenneth Gonsalves
>
> > --
> > You received this message because you are subscribed to the Google Groups
> > "Django users" group.
> > To post to this group, send email to django-users@googlegroups.com.
> > To unsubscribe from this group, send email to
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group at
> >http://groups.google.com/group/django-users?hl=en.

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

2011-10-20 Thread Kevin
There is no need to implement the same CRUD over and over again with
the help of generic views and signals. :)

https://docs.djangoproject.com/en/1.3/ref/class-based-views/

Mind you, I've only used these generic views in 1.2 and never yet took
some time to learn the new class-based one.  Although the class-based
one seems much more flexible to implement a CRUD with very little
work.

Signals will help for when you do updates in the database, it can auto-
fill information that should be set, such as the user saving the
entry.

https://docs.djangoproject.com/en/1.3/topics/signals/

A Django app that I think will help you realize this fine grained type
of database layout would be django-guardian.  This way you can set
permissions and group assignments per row object.  The admin interface
can even be coded to respect it as well, for managers who need more
fine grain controls to do edits at a low-level.  You can use a signal
to assign the user's group to the object they just created.  Each
company can be assigned a group, and the objects owned by that company
can be assigned to their specific group.  The users in that company
can be part of the company/branch group.  Django-guardian is very
flexible and would be the easiest way(in my eyes) to implement this
type of system you seek to make.

https://github.com/lukaszb/django-guardian

Read the docs for it here:

http://packages.python.org/django-guardian/

Hope this helps.

On Oct 20, 4:43 am, "zzart...@googlemail.com"
 wrote:
> Thanks for your time Mike, Cal, Andre!
> I had suspected that general consensus will be don't use admin :)
> still I had to ask. When i write down all the features admin has and
> features  i will need to be created on top of admin somehow,  i've
> come to the same conclusions. Still it hurts me a lot to be
> implementing the same old CRUD over and over again.
> Anyhow, thanks for sharing !
> mars
>
> On 19 Paź, 18:56, Mike Seidle  wrote:
>
>
>
>
>
>
>
> > On Wednesday, October 19, 2011 02:10:49 PM Andre Terra wrote this and sent 
> > it
> > to To: django-users@googlegroups.com::
>
> > > > To be honest, you're probably (not 100% sure) creating *more* work for
> > > > yourself trying to make something like this work in django admin, than
> > > > just designing something for yourself (YMMV).
>
> > > I couldn't agree more. Too often I see newcomers learning how to extend 
> > > the
> > > admin, when it would actually be easier to roll out their own views, not 
> > > to
> > > mention how they would be learning how to use the framework rather than a
> > > built-in app.
>
> > It's so easy to think Django-Admin is the answer.  Django's admin is a few
> > steps up from PHPMyAdmin or some other SQL GUI tool. Uless your use case for
> > your user is precicely a create, read, update and delete interface to your
> > data as represented by your model definitions, you probably will not have 
> > the
> > moving parts you need to implement what you want... The minute you want
> > more/different, is (most of the time) literally less work to just roll your 
> > own
> > view and template which will give you much more control of the user 
> > experience
> > and avoid the inevitable complaints about "why aren't totals at the bottom 
> > of
> > tables? How come we have to used this wonky Year/Month/Date drill down?
>
> > --- Mike

-- 
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: Blank output from treemenus under nginx

2011-10-20 Thread Kevin
Something you may want to try to see if it is fastcgi related, is
running the site on the server in dev mode, plain old manage.py
runserver.
Then replace your fastCGI command in nginx with proxy_pass 
http://127.0.0.1:8000/;
Be sure to change nginx and reload it's config before running
manage.py runserver, also be sure the fastcgi instance of your django
project is killed too.
When it's running in debug and in dev mode on the production server
going through nginx, you can see the live output of each page being
accessed on the django site within the server console for debugging.

Another thing you may want to check is the "Sites framework", as some
apps use it, and if the domain in Sites does not correctly match the
domain which is visiting the site, it may cause problems.

When you enabled debug mode on your live server, you did restart the
django project instance correct?  Running your project in FastCGI
mode, or any mode other than "runserver", changes to source files will
not take affect until the django instance is rebooted.  I would
recommend using the manage.py's --pid option to save the PID of the
instance to /var/run, so that you can easily stop the instance using
kill `cat /var/run/django/instance.pid`.  Be sure that the user
running your django instance can write to the sub-directory in /var/
run.  Create a subdirectory, don't just give the user full access to /
var/run.

On Oct 18, 3:51 am, Alastair Campbell  wrote:
> Hi Kevin,
>
> Thanks for the tips, unfortunately I think the problem is trickier than that.
>
> The output HTML is different, because the treemenu template tags don't
> output anything.
>
> I.e. within a template that is otherwise working fine, you have:
>
> {% load tree_menu_tags %}
> {% show_menu "ukwa" %}
>
> And that doesn't output anything. No error message, no assets needed
> or anything, just no HTML output.
>
> The installed apps match local between local and live, and I'm getting
> no errors reported in the nginx logs.
>
> Apologies, it is running fastcgi not mod_wsgi, it's a while since I
> configured the server and I assumed it was mod_wsgi.
>
> Does fastcgi typically have an error log somewhere?
>
> -Alastair

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

2011-10-20 Thread Kevin
I have a similar development machine set-up, for hosting, I am
currently using Rackspace Cloud, as I have full control over
deployment options, and it can grow with my apps, scalability is a
must.  I am currently using Debian Squeeze and editing with the
wonderful Kate, and using KIO to edit the odd file on the server via
SFTP/Fish.  For versioning, I choose Subversion.  I also use
Subversion for app deployment on the server.  On the server, I merely
run "svn update" in the app's directory and reload the django instance
for the project.  It's simple and effective.  Subversion also
documents my changed and I can easily revert back if something breaks
in an update.  Although I tend to do a lot of testing before doing an
"svn update" on the server.  My subversion repo is also located on my
Rackspace cloud server.

Question, why do you use VirtualBox?  You can make your development
Linux box act the same as the production server very easily, as the
server is also Linux-based.  You can install all the exact same tools
as the server, I normally do this.  I have MySQL installed on my
workstation, nginx, and edit the hosts file to point a beta domain to
127.0.0.1, and configure a virtualhost in nginx.  The only difference
on my workstation verses the server, is I run django in dev mode and
use nginx's "proxy_pass" instead of the options for either fastcgi or
wsgi.  With different django settings file, you can easily run
multiple tests using different configurations.

Also, how could Fabric benefit me over a traditional subversion-based
deployment?  Are there security issues with having a .svn directory in
the Python packages?  I just read a short tutorial on Fabric, and it
does look interesting, it takes away lots of repetitive work.
Although running a simple python/shell script over ssh can do the same
thing without the extra program: ssh myserver.com python /home/user/
bin/deploy.py $@

I do use ssh pub/private keys for authentication, so creating a local
script to run the above command is just as simple as Fabric.  Although
Fabric probably supports more checks to ensure a stable deployment.
Oh and it also helps that my local user matches the user on the target
server, it avoids adding the username to the ssh command.  I can see
how Fabric can scale better than a custom solution though, thanks for
that.

On Oct 19, 9:02 pm, kenneth gonsalves  wrote:
> On Wed, 2011-10-19 at 14:59 +0200, Benedict Verheyen wrote:
> > - Debian ( 1st install was potato :))
> > - VirtualBox
> > - nginx
> > - gunicorn
> > - supervisord (watch gunicorn process)
> > - git
> > - virtualenv
> > - pip (coupled with virtualenv, it's a powerful tool)
> > - south (easy db migration)
> > - fabric (application deployment)
> > - Django trunk (for development, I tend to use trunk as it's inhouse
> > development)
> > - Postgres db with psycopg2 python module
> > - memcached
> > - workzeug / django-extensions
> > - django-registration
>
> perfect - only celery is missing.
> --
> regards
> Kenneth Gonsalves

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



Storage Backend for MediaTemple's ProCDN?

2011-10-22 Thread Kevin
I have a client who is suggesting that I look into MediaTemple's
ProCDN.  I currently only have experience with RackSpace's CloudFiles
CDN, and only know of it and Amazon S3 for django storage support.
Furthermore, I cannot seem to access their API pages without having a
login, so this complicates it, as I'd like to see what sort of REST
API I'd be looking into implementing.

Has anyone had any success with managing a MediaTemple ProCDN with
Django?  Or rather, as anybody used MediaTemple's CDN at all and what
are their reviews over other popular CDNs such as S3 or Cloudfiles?

Thanks.

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



Re: Storage Backend for MediaTemple's ProCDN?

2011-10-23 Thread Kevin
Thanks for your input.  I currently use Rackspace's CDN, their
cloudfiles.  So far it works nicely with django using the cumulus
storage backend.  Cumulus supports virtual directories in a container,
and for the most part works.  I have not yet tried Amazon's S3, as
currently all my services including servers are hosted on Rackspace.
Today I was looking into the pricing of various CDNs and server
providers, and I do like what Rackspace provides, a nice price, fast
cloud servers, and they are adding new features all the time.

I think I'd suggest using Rackspace CDN over MT CDN, as it's supported
nicely in django, and I have current experience with it.  Although the
app they plan on launching is movie streaming service, and that's
where it get complicated...  I will need to judge more than just
pricing and API, Bandwidth is also a big one, especially for the
initial buffering of the stream.

On Oct 22, 4:32 pm, Kurtis  wrote:
> Hello,
>
> I never heard of MediaTemple or their CDN until I read your post. I
> tried to look at their site for your information and it seems to be
> hidden.
>
> We just went through this same thing but starting with Rackspace and
> then moved to Amazon.
>
> One thing I ran across is that they (MT) use "Objects" for their CDN.
> If this is anything like Rackspace, you may run into troubles. For
> example, on Rackspace, you can only create Objects in a "root
> directory" of your buckets and have to fake a file system if you want
> multiple directories. Without performing some kind of a simulation of
> a heirarchy within a flat-directory structure, you'll have a pretty
> difficult time managing your files. It really depends on what you plan
> on using the CDN for, though.
>
> We started with Rackspace and loved them. But, that one feature drove
> us to try out Amazon's S3. Amazon provided the ability to store files
> in a directory structure. And from there, publishing that "bucket" (I
> forget what they're called on S3) to the CDN was extremely easy. The
> main downside to Amazon's Cloudfront is the TTL Caching -- but I
> honestly haven't tried that hard to invalidate or set lower refresh
> times for objects in the CDN. The thing I loved about Rackspace was
> their *excellent* support -- but with Amazon you have a huge community
> which sort of makes up for that.
>
> I would suggest doing a complete evaluation of the three products.
> Include components like pricing (hosting & CDN), development time, and
> support. Then, present these to your boss and let him/her see why a
> specific provider might be the best to use. Sure, MediaTemple *might*
> be the cheapest to host (I don't know, just assuming) but if there's
> no existing tools to use them as a storage backend, it might cost your
> boss thousands of dollars (equivalent to years of hosting costs) to
> have you build this thing.
>
> Sorry I couldn't compare MT CDN with the others but I hope that offers
> a little help.
>
> On Oct 22, 5:11 pm, Kevin  wrote:
>
> > I have a client who is suggesting that I look into MediaTemple's
> > ProCDN.  I currently only have experience with RackSpace's CloudFiles
> > CDN, and only know of it and Amazon S3 for django storage support.
> > Furthermore, I cannot seem to access their API pages without having a
> > login, so this complicates it, as I'd like to see what sort of REST
> > API I'd be looking into implementing.
>
> > Has anyone had any success with managing a MediaTemple ProCDN with
> > Django?  Or rather, as anybody used MediaTemple's CDN at all and what
> > are their reviews over other popular CDNs such as S3 or Cloudfiles?
>
> > Thanks.

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



Comparing two ManyToMany fields for same entries

2011-10-28 Thread Kevin
Hello,

  I am building a model which shares a relation with another model
using a ManyToManyField.  What I need to do, is find out which models
are on both on two seperate ManyToManyField lists.  Here is a simple
example of what I am trying to do:

Person:
  friends=ManyToManyField(self)

To find out this persons direct friends, Person.friends...
To find out which friends this Person shares in common with another
Person, 

Person0:
  Person1
  Person6
  Person3
  Person8

Person1:
  Person2
  Person6

What would be the most optimized QuerySet to find out that both
Person0 and Person1 are both friends with Person6?

Is there a specific Django app perhaps that can ease develop of this
type of data relations between objects?

Thanks.

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



Re: Comparing two ManyToMany fields for same entries

2011-10-28 Thread Kevin
Just thought I'd add another example using Python script:

Person0 = Person()
Person1 = Person()
Person2 = Person()
Person0.friends.add(Person2)
Person2.friends.add(Person0)
Person2.friends.add(Person1)
Person1.friends.add(Person2)

Now, I would like to do the following, but it seems to fail:

Person0.friends.all() in Person1.friends.all().  I would like it to
say if Person0 and Person1 share another friend in common.

Person0 and Person2 are friends
Person1 and Person2 are friends
Person0 and Person1 are NOT friends, but share a friend in common.
How does one find out that even though Person0 and Person1 are not
friends, they do share Person2 as a friend.

I can use my eye on a Python shell to see that Person2 exists on both
Peson0 and Person1, but how does one make the code see it?

Sorry for having to clarify this so much, I'm just not sure that my
last post actually explained it properly.

Thanks.

On Oct 28, 12:30 pm, Kevin  wrote:
> Hello,
>
>   I am building a model which shares a relation with another model
> using a ManyToManyField.  What I need to do, is find out which models
> are on both on two seperate ManyToManyField lists.  Here is a simple
> example of what I am trying to do:
>
> Person:
>   friends=ManyToManyField(self)
>
> To find out this persons direct friends, Person.friends...
> To find out which friends this Person shares in common with another
> Person, 
>
> Person0:
>   Person1
>   Person6
>   Person3
>   Person8
>
> Person1:
>   Person2
>   Person6
>
> What would be the most optimized QuerySet to find out that both
> Person0 and Person1 are both friends with Person6?
>
> Is there a specific Django app perhaps that can ease develop of this
> type of data relations between objects?
>
> Thanks.

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



Re: Comparing two ManyToMany fields for same entries

2011-10-28 Thread Kevin
Thanks.  Is this way good for database optimization though?  I guess I
could use select_related().  I was hoping there was a QuerySet I could
run.

I made this one, although I'm not sure if it works correctly:

Person.objects.filter(name='Person1').filter(friends__friends__name='Person0')
This outputs "Person1", if I interchange Person0 with Person2, it
outputs no results.  If I use Person1 in both instances, it outputs
'Person1'.
Does this QuerySet return the results I want, or should I use Brett's
suggestion?

Thanks again.

On Oct 28, 1:21 pm, Brett Epps  wrote:
> Try this:
>
> for friendof0 in Person0.friends.all():
>     for friendof1 in Person1.friends.all():
>         if friendof0 == friendof1:
>             # Person 0 and Person 1 share a friend.
>         else:
>             # They have no shared friends.
>
> Brett
>
> On 10/28/11 12:59 PM, "Kevin"  wrote:
>
> >Just thought I'd add another example using Python script:
>
> >Person0 = Person()
> >Person1 = Person()
> >Person2 = Person()
> >Person0.friends.add(Person2)
> >Person2.friends.add(Person0)
> >Person2.friends.add(Person1)
> >Person1.friends.add(Person2)
>
> >Now, I would like to do the following, but it seems to fail:
>
> >Person0.friends.all() in Person1.friends.all().  I would like it to
> >say if Person0 and Person1 share another friend in common.
>
> >Person0 and Person2 are friends
> >Person1 and Person2 are friends
> >Person0 and Person1 are NOT friends, but share a friend in common.
> >How does one find out that even though Person0 and Person1 are not
> >friends, they do share Person2 as a friend.
>
> >I can use my eye on a Python shell to see that Person2 exists on both
> >Peson0 and Person1, but how does one make the code see it?
>
> >Sorry for having to clarify this so much, I'm just not sure that my
> >last post actually explained it properly.
>
> >Thanks.
>
> >On Oct 28, 12:30 pm, Kevin  wrote:
> >> Hello,
>
> >>   I am building a model which shares a relation with another model
> >> using a ManyToManyField.  What I need to do, is find out which models
> >> are on both on two seperate ManyToManyField lists.  Here is a simple
> >> example of what I am trying to do:
>
> >> Person:
> >>   friends=ManyToManyField(self)
>
> >> To find out this persons direct friends, Person.friends...
> >> To find out which friends this Person shares in common with another
> >> Person, 
>
> >> Person0:
> >>   Person1
> >>   Person6
> >>   Person3
> >>   Person8
>
> >> Person1:
> >>   Person2
> >>   Person6
>
> >> What would be the most optimized QuerySet to find out that both
> >> Person0 and Person1 are both friends with Person6?
>
> >> Is there a specific Django app perhaps that can ease develop of this
> >> type of data relations between objects?
>
> >> Thanks.
>
> >--
> >You received this message because you are subscribed to the Google Groups
> >"Django users" group.
> >To post to this group, send email to django-users@googlegroups.com.
> >To unsubscribe from this group, send email to
> >django-users+unsubscr...@googlegroups.com.
> >For more options, visit this group at
> >http://groups.google.com/group/django-users?hl=en.

-- 
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: Comparing two ManyToMany fields for same entries

2011-10-28 Thread Kevin
I think the filter I used does work to detect related friends, here is
a Pythonic example of the same code, but done differently without
filters:

Person.objects.get(name='Person1').friends.get().friends.all()

Instead of returning back 'Person1', when using filters, this returns
back 'Person0'.

Person.objects.get(name='Sean').friends.get().friends.get(name='Person0')

My next question, which would be better optimized for database hits:

* Brett's example
* using the filter version
* using the Pythonic version, but use select_related(depth=2) option?

I am trying to make sure the database hits are optimized as this will
be queries multiple times per page hit for different models.  Also,
which would be faster to make sure the page loads are not burden when
lots of these types of queries go through?

Thanks.

On Oct 28, 1:34 pm, Kevin  wrote:
> Thanks.  Is this way good for database optimization though?  I guess I
> could use select_related().  I was hoping there was a QuerySet I could
> run.
>
> I made this one, although I'm not sure if it works correctly:
>
> Person.objects.filter(name='Person1').filter(friends__friends__name='Person0')
> This outputs "Person1", if I interchange Person0 with Person2, it
> outputs no results.  If I use Person1 in both instances, it outputs
> 'Person1'.
> Does this QuerySet return the results I want, or should I use Brett's
> suggestion?
>
> Thanks again.
>
> On Oct 28, 1:21 pm, Brett Epps  wrote:
>
> > Try this:
>
> > for friendof0 in Person0.friends.all():
> >     for friendof1 in Person1.friends.all():
> >         if friendof0 == friendof1:
> >             # Person 0 and Person 1 share a friend.
> >         else:
> >             # They have no shared friends.
>
> > Brett
>
> > On 10/28/11 12:59 PM, "Kevin"  wrote:
>
> > >Just thought I'd add another example using Python script:
>
> > >Person0 = Person()
> > >Person1 = Person()
> > >Person2 = Person()
> > >Person0.friends.add(Person2)
> > >Person2.friends.add(Person0)
> > >Person2.friends.add(Person1)
> > >Person1.friends.add(Person2)
>
> > >Now, I would like to do the following, but it seems to fail:
>
> > >Person0.friends.all() in Person1.friends.all().  I would like it to
> > >say if Person0 and Person1 share another friend in common.
>
> > >Person0 and Person2 are friends
> > >Person1 and Person2 are friends
> > >Person0 and Person1 are NOT friends, but share a friend in common.
> > >How does one find out that even though Person0 and Person1 are not
> > >friends, they do share Person2 as a friend.
>
> > >I can use my eye on a Python shell to see that Person2 exists on both
> > >Peson0 and Person1, but how does one make the code see it?
>
> > >Sorry for having to clarify this so much, I'm just not sure that my
> > >last post actually explained it properly.
>
> > >Thanks.
>
> > >On Oct 28, 12:30 pm, Kevin  wrote:
> > >> Hello,
>
> > >>   I am building a model which shares a relation with another model
> > >> using a ManyToManyField.  What I need to do, is find out which models
> > >> are on both on two seperate ManyToManyField lists.  Here is a simple
> > >> example of what I am trying to do:
>
> > >> Person:
> > >>   friends=ManyToManyField(self)
>
> > >> To find out this persons direct friends, Person.friends...
> > >> To find out which friends this Person shares in common with another
> > >> Person, 
>
> > >> Person0:
> > >>   Person1
> > >>   Person6
> > >>   Person3
> > >>   Person8
>
> > >> Person1:
> > >>   Person2
> > >>   Person6
>
> > >> What would be the most optimized QuerySet to find out that both
> > >> Person0 and Person1 are both friends with Person6?
>
> > >> Is there a specific Django app perhaps that can ease develop of this
> > >> type of data relations between objects?
>
> > >> Thanks.
>
> > >--
> > >You received this message because you are subscribed to the Google Groups
> > >"Django users" group.
> > >To post to this group, send email to django-users@googlegroups.com.
> > >To unsubscribe from this group, send email to
> > >django-users+unsubscr...@googlegroups.com.
> > >For more options, visit this group at
> > >http://groups.google.com/group/django-users?hl=en.

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



Pickling and caching the current request.user, good or bad idea?

2011-10-29 Thread Kevin
In my attempts to lower database hits, I found that on most of my
pages, auth_user is hit every time.  I had an idea about caching this
object in the current session.  Is this a good idea, or will it cause
more problems than it helps?  If so, what type of problems will I be
looking at?

My app rarely modifies the auth_user table, if at all.  Here is a
quick middleware I wrote to go aloneside the current
AuthenticationMiddleware, and it works perfectly!  Only 2 database
hits when viewing an account page.  One hit to the session table, and
other hit to the table which holds various account settings.

class UserPickleMiddleware(object):
  def process_request(self, request):
if 'cached_user' not in request.session:
  from django.contrib.auth import get_user
  request.session['cached_user'] = get_user(request)
request._cached_user = request.session['cached_user']
return None

I place this just before the standard AuthenticationMiddleware.  I
will continue to run tests and see how it functions, if say the user
is added or removed from a group.

My sessions are stored in a database, which makes this interesting.
As it's only hitting the database once to grab both the session and
current user information.

-- 
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: Pickling and caching the current request.user, good or bad idea?

2011-10-29 Thread Kevin
Okay, so the last one there had a hickup, users could not longer
login, once they have logged out.  It kept the AnonymousUser cached...

Here is an update which works with logging back in:

class UserPickleMiddleware(object):
  def process_request(self, request):
if 'cached_user' not in request.session:
  from django.contrib.auth import get_user
  user = get_user(request)
  if isinstance(user, User):
request.session['cached_user'] = user
if 'cached_user' in request.session:
  request._cached_user = request.session['cached_user']
return None

This one makes sure that the user instance is indeed a regular User
and not some Anonymous person before setting the cached data.  The
code could be more optimized.  I didn't use an Else, because it's
needs to set the request variables.  I'd rather write an extra "if"
instead of copying the same line to set the request variable twice.

On Oct 29, 5:45 am, Kevin  wrote:
> In my attempts to lower database hits, I found that on most of my
> pages, auth_user is hit every time.  I had an idea about caching this
> object in the current session.  Is this a good idea, or will it cause
> more problems than it helps?  If so, what type of problems will I be
> looking at?
>
> My app rarely modifies the auth_user table, if at all.  Here is a
> quick middleware I wrote to go aloneside the current
> AuthenticationMiddleware, and it works perfectly!  Only 2 database
> hits when viewing an account page.  One hit to the session table, and
> other hit to the table which holds various account settings.
>
> class UserPickleMiddleware(object):
>   def process_request(self, request):
>     if 'cached_user' not in request.session:
>       from django.contrib.auth import get_user
>       request.session['cached_user'] = get_user(request)
>     request._cached_user = request.session['cached_user']
>     return None
>
> I place this just before the standard AuthenticationMiddleware.  I
> will continue to run tests and see how it functions, if say the user
> is added or removed from a group.
>
> My sessions are stored in a database, which makes this interesting.
> As it's only hitting the database once to grab both the session and
> current user information.

-- 
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: Comparing two ManyToMany fields for same entries

2011-10-29 Thread Kevin
Your version isn't as bad you think, here is the SQL it generates:

SELECT "relations_person"."id",
   "relations_person"."name"
FROM "relations_person"
INNER JOIN "relations_person_friends" ON ("relations_person"."id" =
"relations_person_friends"."to_person_id")
WHERE "relations_person_friends"."from_person_id" = 1

SELECT "relations_person"."id",
   "relations_person"."name"
FROM "relations_person"
INNER JOIN "relations_person_friends" ON ("relations_person"."id" =
"relations_person_friends"."to_person_id")
WHERE "relations_person_friends"."from_person_id" = 3

It only does 2 queries, but the database's test data only has 3
Persons.

Person.objects.filter(name='Person1').filter(friends__friends__name='Person0')
makes only a single query:

SELECT "relations_person"."id",
   "relations_person"."name"
FROM "relations_person"
INNER JOIN "relations_person_friends" ON ("relations_person"."id" =
"relations_person_friends"."from_person_id")
INNER JOIN "relations_person" T3 ON
("relations_person_friends"."to_person_id" = T3."id")
INNER JOIN "relations_person_friends" T4 ON (T3."id" =
T4."from_person_id")
INNER JOIN "relations_person" T5 ON (T4."to_person_id" = T5."id")
WHERE ("relations_person"."name" = Person1
   AND T5."name" = Person0)LIMIT 21

I'll need to play around a little and see what I can figure out.

On Oct 28, 5:35 pm, Brett Epps  wrote:
> I'm going to guess that my version is slow since a new query would be run
> for each row returned by the initial one.
>
> Check out an app called django-debug-toolbar.  It has a view that will
> show you all of the SQL queries generated as a page is built.  It will
> also tell you how long each query took to run.  This should allow you to
> compare the three methods.
>
> Brett
>
> On 10/28/11 1:44 PM, "Kevin"  wrote:
>
> >I think the filter I used does work to detect related friends, here is
> >a Pythonic example of the same code, but done differently without
> >filters:
>
> >Person.objects.get(name='Person1').friends.get().friends.all()
>
> >Instead of returning back 'Person1', when using filters, this returns
> >back 'Person0'.
>
> >Person.objects.get(name='Sean').friends.get().friends.get(name='Person0')
>
> >My next question, which would be better optimized for database hits:
>
> >* Brett's example
> >* using the filter version
> >* using the Pythonic version, but use select_related(depth=2) option?
>
> >I am trying to make sure the database hits are optimized as this will
> >be queries multiple times per page hit for different models.  Also,
> >which would be faster to make sure the page loads are not burden when
> >lots of these types of queries go through?
>
> >Thanks.
>
> >On Oct 28, 1:34 pm, Kevin  wrote:
> >> Thanks.  Is this way good for database optimization though?  I guess I
> >> could use select_related().  I was hoping there was a QuerySet I could
> >> run.
>
> >> I made this one, although I'm not sure if it works correctly:
>
> >>Person.objects.filter(name='Person1').filter(friends__friends__name='Pers
> >>on0')
> >> This outputs "Person1", if I interchange Person0 with Person2, it
> >> outputs no results.  If I use Person1 in both instances, it outputs
> >> 'Person1'.
> >> Does this QuerySet return the results I want, or should I use Brett's
> >> suggestion?
>
> >> Thanks again.
>
> >> On Oct 28, 1:21 pm, Brett Epps  wrote:
>
> >> > Try this:
>
> >> > for friendof0 in Person0.friends.all():
> >> >     for friendof1 in Person1.friends.all():
> >> >         if friendof0 == friendof1:
> >> >             # Person 0 and Person 1 share a friend.
> >> >         else:
> >> >             # They have no shared friends.
>
> >> > Brett
>
> >> > On 10/28/11 12:59 PM, "Kevin"  wrote:
>
> >> > >Just thought I'd add another example using Python script:
>
> >> > >Person0 = Person()
> >> > >Person1 = Person()
> >> > >Person2 = Person()
> >> &

Django tutorial hasn't received an update for 1.3

2011-10-31 Thread Kevin
I keep checking the tutorial page for version 1.3 hoping to see some
new content related to the class-based views or at least some of the
promised future tutorials.  The tutorial still has the function-based
views, and no new updates since I first went through it on the 1.2
release.

I know the function views work in 1.3, but shouldn't the tutorial be
using the latest features included in 1.3 so that new users coming to
Django begin learning the newest features, such as class-based views.

I'm still a dinosaur and using Django 1.2 and haven't yet dived into
class-based views, and when I do, I would love a great tutorial on how
to proceed.  I plan on learning Django 1.3's newest features very soon
to keep myself up to speed and see if my current apps are fully
compatible.

Are there any updates on when we will see the following new tutorial
sections:
-Advanced form processing
-Using the RSS framework
-Using the cache framework
-Using the comments framework
-Advanced admin features: Permissions
-Advanced admin features: Custom JavaScript

I figured out most of this on my own, as they are pretty
straightforward, still haven't dived into custom javascript in the
admin yet.

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