Using X-editable with Django?

2012-12-08 Thread Steven L
 I am trying to get 
X-Editable inline 
editing of a model in Django. I am simply trying to change attributes of a 
model instance (in this case, the name of a Dataset object). Whenever I try 
to make the inline edit, I get an error that says that there is no CSRF 
protection. How can I add this this?

Also, I am not sure how to write the view so that it correctly captures the 
information from the ajax request:

POST /datasets/9/update_name/{
pk:3//primary key (record id)
value: 'The Updated Name' //new value}

Then save the new name to the Dataset object.

urls.py

# ex: /datasets/3/update_name
url(r'^(?P\d+)/update_name/$', update_name ,
name='update_name'),

detail.html


  {{ dataset.name }}
// using jQueryfunction getCookie(name) {
  var cookieValue = null;
  if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
  var cookie = jQuery.trim(cookies[i]);
  // Does this cookie string begin with the name we want?
  if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
  }
}
  }
  return cookieValue;
}
var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
  // these HTTP methods do not require CSRF protection
  return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));}
$.ajaxSetup({ 
 beforeSend: function(xhr, settings) {
   function getCookie(name) {
 var cookieValue = null;
 if (document.cookie && document.cookie != '') {
   var cookies = document.cookie.split(';');
   for (var i = 0; i < cookies.length; i++) {
 var cookie = jQuery.trim(cookies[i]);
   // Does this cookie string begin with the name we want?
   if (cookie.substring(0, name.length + 1) == (name + '=')) {
 cookieValue = 
decodeURIComponent(cookie.substring(name.length + 1));
 break;
   }
 }
   }
   return cookieValue;
 }
 if (!(/^http:.*/.test(settings.url) || 
/^https:.*/.test(settings.url))) {
   // Only send the token to relative URLs i.e. locally.
   xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
 }
   } 
 });
$('#datasetName').editable({
  type: 'text',
  pk: {{ dataset.pk }},
  url: '{% url 'datasets:update_name' dataset.pk %}',
  title: 'Edit dataset name',});

views.py

def update_name(request, dataset_id):   
# ... Update Dataset object ...
json = simplejson.dumps(request.POST)
return HttpResponse(json, mimetype='application/json') 

-- 
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/-/S0b-lgcqgxwJ.
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: Returning a 503 response instead of a 500 response

2011-06-23 Thread Steven L Smith
Neat. I've been doing Django since the 0.9.6 days and have never written a 
middleware. I guess there's a first time for everything.

Thanks!

========
Steven L Smith, Web Developer
Department of Information Technology Services
Nazareth College of Rochester
585-389-2085 | ssmit...@naz.edu | KC2YTC
http://www.naz.edu/pub/~ssmith46


- Original Message -
From: "Tom Evans" 
To: django-users@googlegroups.com
Sent: Thursday, June 23, 2011 9:28:15 AM GMT -05:00 US/Canada Eastern
Subject: Re: Returning a 503 response instead of a 500 response

On Thu, Jun 23, 2011 at 2:19 PM, Steven L Smith  wrote:
> Some of our apps have to talk to databases outside of our control, and their 
> operators don't have the same uptime standards that we do...
>
> What can I do to make Django return a "503 Service Unavailable" instead of a 
> "500 Internal Server Error", when it encounters a DatabaseError or 
> ProgrammingError while trying to access the database? Bonus points if I could 
> make the 503 page say "there was a temporary database communication problem."
>
> I have some ideas of what I *could* modify, but I'd rather incorporate this 
> into a product or setting instead of having to patch the actual django 
> database backend code itself.
>

Exception handling is performed by middleware. When a django view
encounters an un-handled exception, each installed middleware class is
asked if it wants to handle this exception. If none do, Django sends
out it's pre-canned response as it sees fit.

So, simply write your own exception handling middleware that handles
DatabaseError or ProgrammingError, and passes on other errors. See the
docs for more details:

https://docs.djangoproject.com/en/1.3/topics/http/middleware/#process-exception

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.

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



Returning a 503 response instead of a 500 response

2011-06-23 Thread Steven L Smith
Some of our apps have to talk to databases outside of our control, and their 
operators don't have the same uptime standards that we do...

What can I do to make Django return a "503 Service Unavailable" instead of a 
"500 Internal Server Error", when it encounters a DatabaseError or 
ProgrammingError while trying to access the database? Bonus points if I could 
make the 503 page say "there was a temporary database communication problem."

I have some ideas of what I *could* modify, but I'd rather incorporate this 
into a product or setting instead of having to patch the actual django database 
backend code itself.

========
Steven L Smith, Web Developer
Department of Information Technology Services
Nazareth College of Rochester
585-389-2085 | ssmit...@naz.edu | KC2YTC
http://www.naz.edu/pub/~ssmith46


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



Re: GET vs POST for read-only views

2011-06-14 Thread Steven L Smith
Hi Shawn-

There is a consensus in the web development community at large -- the HTTP Spec 
itself touches on it, and the W3C has released a few supporting statements as 
well.

http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
This is the HTTP 1.1 spec, section 9, which defines the difference between the 
various verbs, including GET and POST, in terms of idempotence.

And this helps clarify:
http://www.w3.org/2001/tag/doc/whenToUseGet-20040321

For your use case, I would definitely use GET. The user may wish to bookmark 
the report, for example, or send it to a colleague. Searches and such should 
always use GET, unless there's a truly compelling reason not to.

POST should only be used for things that change stuff on the server... a 
contact form, a form that creates something in a database, etc...


Cheers!
-Steve


Steven L Smith, Web Developer
Department of Information Technology Services
Nazareth College of Rochester
585-389-2085 | ssmit...@naz.edu | KC2YTC
http://www.naz.edu/pub/~ssmith46


- Original Message -
From: "Shawn Milochik" 
To: django-users@googlegroups.com
Sent: Monday, June 13, 2011 12:45:39 PM GMT -05:00 US/Canada Eastern
Subject: GET vs POST for read-only views

Is there a consensus in the community that GET should be used for
requests that don't write to the database? As a specific example, let's
say there's a report form that allows a user to select a start and end
date, and maybe some other search fields. What would you use for this,
and why?

I use POST for almost everything, but I admit it's mainly to avoid
super-ugly URLs full of querystring content.

Thanks,
Shawn

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

2011-04-18 Thread Steven L Smith
There's a great wrapper you can use to generate these in PIL using a
postscript library.
http://pypi.python.org/pypi/elaphe/

I did something similar with pyqrnative to generate QR Codes for a
conference, basically just create a URL that wraps the output of the
library in an HTTPResponse.



On Apr 18, 1:58 pm, Bobby Roberts  wrote:
> anyone know if there is a django module to generate code 128 or 39
> barcodes for printing out on a webpage?

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



How to create multi-leveled forms with freeform entry options

2011-01-20 Thread Steven L Smith
One of our internal clients has asked for a form with the following
structure:
http://ssecdn.net/marcomm_form.pdf

As you can see, there are a lot of checkboxes, and they (the client)
need to be able to add more via the admin.

I initially thought I'd store "Request Types" and "Requests" like
this:

class MarcommRequestType(models.Model):
name = models.CharField(max_length=255)
order = models.IntegerField()
is_active = models.BooleanField(blank=True, default=True)

class MarcommRequest(models.Model):
request_type = models.ForeignKey('MarcommRequestType')
name = models.CharField(max_length=255)
is_active = models.BooleanField(blank=True, default=True)


...and then, store each instance of the form with a ManyToManyField on
MarcommRequest, like this:

class MarcommTicket(models.Model):
created = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=255)
department = models.CharField(max_length=255)
email = models.EmailField()
date_needed = models.DateTimeField()
requests = models.ManyToManyField('MarcommRequest')


That works perfectly, except for those questions that have "other" or
"date of event" or things of that sort. As far as I can tell, there's
no good way to have a third level of question to my form, if that
third level is any kind of text entry / non-relationship field.

I thought a possible solution might be to have a "sub question" model
that lets the admin users specify a label and field type, but then,
where do I save the *answers* to the sub-questions?

What's the most Djangonic / Pythonic way to do this type of thing? It
seems like the kind of problem someone might have faced before...

Thanks!
Steven L Smith
Web Developer, Nazareth College

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



Connecting to Multiple MSSQL Databases... I've hit an edge case. Help, please!

2010-10-25 Thread Steven L Smith
For one of our apps, I'm using django-pyodbc to connect to an MS SQL
2005 database (not my choice...) This database contains, among other
things, rows for the Person model. I've written a function to connect
to "Lenel", an access-card system used by our campus security
department, which pulls the photos (stored as blobs in their MS SQL
2008 database).

Both the Person model queries, and the Lenel-photo-pulling function
work great... by themselves. But when they're put together, they don't
work. Basically, if I've loaded *anything* from myapp.models, the
get_photo_from_lenel function fails.

>From what I can tell, Django (or django-pyodbc) isn't cleaning up its
connection to MSSQL DB #1, and when I use pyodbc to connect to MSSQL
DB #2, it seems to be routing it somewhere else. But that's just a
guess?

I read that the connection persists as long as the object exists, so I
tried "del me" and "del Person", but the error message still shows up,
unless I restart my python shell.

This is my function:
http://dpaste.com/hold/263816/

And this is what happens when I use it:
>>> from naz.directories.getphotos import get_photo_from_lenel
>>> nazid = u'1237946'
>>> tuple(get_photo_from_lenel(naz_id=nazid))
(14439, '1234567', )


>>> from naz.directories.getphotos import get_photo_from_lenel
>>> from naz.directories.models import Person
>>> me = Person.objects.get(nazid=1234567)
>>> nazid = me.nazid
>>> nazid = u'1234567'
>>> get_photo_from_lenel(naz_id=nazid)
>>> tuple(get_photo_from_lenel(naz_id=nazid))
Traceback (most recent call last):
  File "", line 1, in 
  File "/var/django/naz/../naz/directories/getphotos.py", line 112, in
get_photo_from_lenel
cursor.execute(query)
Error: ('IM001', '[IM001] [unixODBC][Driver Manager]Driver does not
support this function (0) (SQLColAttribute)')

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



Customizing the login generic view with a custom backend

2010-09-02 Thread Steven L Smith
I've written a custom backend for Django auth to hook into our Active
Directory. It works great, but some users can't seem to figure out
that "username" does not equal "email address". Since our AD is kind
of borked, multiple users *might* have the same email addresses, so
simply changing it to also allow auth based on email won't work.

We had the idea that, if we checked for the presence of an "@" sign in
the code, we could raise a validation error in our backend, and it
would be a nice "user education" opportunity.


Inside my authenticate() method, I have:
if "@" in username:
 raise ValidationError("Hey idiot")

In the template, when I access {{ form.errors }} it shows up, but it
is wrapped very strangely. Likewise when I try to loop through it.

How can I get *just* the text of the error? I tried looping over
form.errors.itervalues, but that still returns html.

I could *settle* for the extra html, but we're using the same backend
for the admin, and my ValidationError is not trapped by its login
view, so I end up with a 500.

Thanks!


AD Backend:
http://dpaste.com/237935/

Template Examples:
http://dpaste.com/237938/


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



Specifying column names for ManyToMany fields

2010-08-05 Thread Steven L Smith
Hello,

I've been charged with creating a front-end in Django for a MSSQL
database. It
has to stay in MSSQL for various other reasons, so just using our
normal
Postgres stuff won't work.

It is all working, except for the internal names of ManyToMany Fields.
Our DBA
likes to follow the CamelCaseStyle, and Django likes the
underscore_style.

The two options I've found are:

1.) Define the field like this, using through:
websites = models.ManyToManyField('Website',
through='DepartmentsWebsites',
blank=True, null=True)

The problem there is that a lot of the ORM is disabled when you use
"through",
and the admin won't display the MultipleSelectWidgets for a table that
uses
"through".


2.) Define the field like this, using "db_table":
websites = models.ManyToManyField('Website',
db_table='Departments_Websites',
blank=True, null=True)

The problem there is that the Departments_Websites table contains
columns
called ID, DepartmentID, and WebsiteID, but Django is still looking
for id,
department_id, and website_id.

Any thoughts? Or would it be a LOT more difficult than just telling
the DBA
that we have to be slightly inconsistent in our naming schemes?


Thanks!


Steven L Smith, Web Developer
Department of Information Technology Services
Nazareth College of Rochester
585-389-2085   |   ssmit...@naz.edu
http://www.naz.edu/pub/~ssmith46


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



re: i can't import newforms(newbie)

2010-06-08 Thread Steven L Smith
Hello, and welcome to Django.

A long time ago, the original "forms" was removed and replaced with 
"newforms". To keep applications working during the transition, both "forms" 
and "newforms" were kept side-by-side for awhile. The idea was, after the 
transition was complete, you could simply change "import newforms as forms" to 
"import forms" and it would continue working.

So, yes, anytime you see "import newforms as forms" it is safe to replace it 
with "import forms".




Steven L Smith, Web Developer
Department of Information Technology Services
Nazareth College of Rochester
585-389-2085   |   ssmit...@naz.edu
http://www.naz.edu/pub/~ssmith46


- Original Message -
From: "refreegrata" 
To: "Django users" 
Sent: Tuesday, June 8, 2010 3:46:46 PM GMT -05:00 US/Canada Eastern
Subject: i can't import newforms(newbie)

hello list
i'm a newbie with django trying to learn
Now i have a question
when i do
---
from django import newforms as forms

django throw an exception : "Error was: cannot import name newforms"

But when i do
---
from django import forms
---
all works fine

Mi question is, in all tutorial that i read, the writter say something
like "the recommended way to import is 'from django import newforms as
forms'".

Why this way don't work now?.In the last version of Django newforms
was replaced for form?. I can't find nothing in the official
documention.

Mi PC have Django 1.2.1(the latest stable version)

That's my question. Thank's all. And sorry for my poor english, the
english isn't my mother language.

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

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



Re: Using array of URLs for MEDIA_URL

2010-06-08 Thread Steven L Smith
Looks like my email client screwed up the indentation I've added some 
indents...

random_media.py
-
from django import template
from random import choice

register = template.Library()

def media_url():
media_urls = ['site1.example.com', 'site2.example.com', 
'site3.example.com']
return choice(media_urls)
register.simple_tag(media_url)


in some template
--
{% load random_media %}
{% media_url %}





========
Steven L Smith, Web Developer
Department of Information Technology Services
Nazareth College of Rochester
585-389-2085 begin_of_the_skype_highlighting  585-389-2085  
end_of_the_skype_highlighting | ssmit...@naz.edu
http://www.naz.edu/pub/~ssmith46


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



Re: Using array of URLs for MEDIA_URL

2010-06-08 Thread Steven L Smith
Hi Martin-

Yes, that is what that code would do... I guess I forgot about how context 
processors work. :-P

I think most people do this type of thing with a round-robin server setup. If 
you wanted to do it django-side, you'd probably need to do a template tag. 
Note the callable...

-Steve



random_media.py
-
from django import template
from random import choice

register = template.Library()

def media_url():
   media_urls = ['site1.example.com', 'site2.example.com', 
'site3.example.com']
   return choice(media_urls)
register.simple_tag(media_url)


in some template
--
{% load random_media %}
{% media_url %}





========
Steven L Smith, Web Developer
Department of Information Technology Services
Nazareth College of Rochester
585-389-2085   |   ssmit...@naz.edu
http://www.naz.edu/pub/~ssmith46


- Original Message -
From: "Martin Siniawski" 
To: "Django users" 
Sent: Tuesday, June 8, 2010 8:32:53 AM GMT -05:00 US/Canada Eastern
Subject: Re: Using array of URLs for MEDIA_URL

Steve,

Thanks for the answer.

If I understand correctly your idea and code, each template would have
only one value for the MEDIA_URL (randomly chosen from the array),
right?

What I was looking for was a way of distributing the value of the
MEDIA_URL uniformly along the values of an array, in each template. So
in a certain template the MEDIA_URL would have more than one value.
Maybe if I set it as a callable (with the logic that choses the values
inside it) that would work.

I cannot quite understand why there isn't anymore people running into
this issue.

Best and thanks again for the answer,
Martin

On Jun 7, 10:46 am, Steven L Smith  wrote:
> Hi Martin-
>
> I don't know what the "official" answer would be, but you could write your 
own
> context processor that had something like:
>
> from random import choice
> MEDIA_URLS =  'static1.site.com', 'static2.site.com', 'static3.site.com' ]
> def media(request):
> return {'MEDIA_URL': choice(MEDIA_URLS)}
>
> Then, in settings.py, include your custom context processor instead of the 
one
> built-in to to Django.
>
> -Steve
>
> 
> Steven L Smith, Web Developer
> Department of Information Technology Services
> Nazareth College of Rochester
> 585-389-2085   |   ssmit...@naz.eduhttp://www.naz.edu/pub/~ssmith46
> 

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

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



Re: Using array of URLs for MEDIA_URL

2010-06-07 Thread Steven L Smith
Hi Martin-

I don't know what the "official" answer would be, but you could write your own 
context processor that had something like:

from random import choice
MEDIA_URLS =  'static1.site.com', 'static2.site.com', 'static3.site.com' ]
def media(request):
return {'MEDIA_URL': choice(MEDIA_URLS)}

Then, in settings.py, include your custom context processor instead of the one 
built-in to to Django.

-Steve




Steven L Smith, Web Developer
Department of Information Technology Services
Nazareth College of Rochester
585-389-2085   |   ssmit...@naz.edu
http://www.naz.edu/pub/~ssmith46


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



UnicodeDecodeError Solution?

2010-03-19 Thread Steven L Smith
We have a freelance designer that, for various political reasons, we need to 
give access to our templates directory. The problem is, he frequently pastes 
from Microsoft Word, and other sources, and then we're seeing HTTP 500 errors 
because the output contains unescaped UTF-8 / unicode characters.

For example, "UnicodeDecodeError: 'utf8' codec can't decode byte 0x94 in 
position 30076: unexpected code byte".

Is there a way to prevent these errors, other than revisiting the level of 
access we give folks like this? Some kind of middleware that would filter 
these characters out? Some kind of way to replace weird characters with a 
bright pink blinking exclamation point? Something else?

Thanks!

Steven L Smith
Web Developer
Nazareth College of Rochester
http://www.naz.edu/

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