Re: Exclude form field when calling form from view

2010-11-09 Thread Knut Ivar Nesheim
The problem is here:

 if request.method == 'POST':
   form = UploadFileForm(request.POST, request.FILES)

You need to make sure you always pass in show_title correctly when
instantiating the form.

Regards
Knut


On Tue, Nov 9, 2010 at 3:57 AM, Ed  wrote:
> I can fall back on the subclassing suggestion.  But I'd like to give
> this one more shot for a fix.  I think it has something to do with the
> request.FILES that I need.  Here is my complete form:
>
> class UploadFileForm(forms.Form):
>        def __init__(self, show_title=True, *args, **kwargs):
>                super(UploadFileForm, self).__init__(*args, **kwargs)
>                if not show_title:
>                        del self.fields['title']
>
>        def clean_file(self):
>                content = self.cleaned_data['file']
>                content_type = content.content_type.split('/')[0]
>                if content_type in settings.CONTENT_TYPES:
>                        if content._size > settings.MAX_UPLOAD_SIZE:
>                                raise forms.ValidationError(_('Please keep 
> filesize under %s.
> Current filesize %s') % (filesizeformat(settings.MAX_UPLOAD_SIZE),
> filesizeformat(content._size)))
>                else:
>                        raise forms.ValidationError(_('File type is not 
> supported'))
>                return content
>
>        title = forms.CharField(max_length=50)
>        file = forms.ImageField(label='Select photo to upload')
>
>
> And here is my complete view:
>
> def upload_file(request, modelname, id):
>        if modelname == 'film':
>                form = UploadFileForm()
>        else:
>                form = UploadFileForm(show_title=False)
>
>        object = get_object_or_404(modelname, id__iexact=id)
>        if request.method == 'POST':
>                form = UploadFileForm(request.POST, request.FILES)
>                if form.is_valid():
>                        file = request.FILES["file"]
>                        filename = file.name
>                        content = file.read()
>
>                        # Assign unique name to file
>                        new_image_name, extension = unique_name(filename, 
> object,
> modelname)
>
>                        #FUTURE: Resize middle and resize remaining in 
> background
>                        #SMALL
>                        #img_resizer(content)
>                        u_small = new_image_name + '_small.jpg'
>                        store_in_s3(u_small, img_resizer(content,250,250,90))
>
>                        # Save thumbnail url to object
>                        object.url_small = u_small
>                        object.save()
>
>                        # Grab Next param to determine where to redirect back 
> to
>                        redirect_to = request.GET.get('next', 
> reverse('index_view'))
>                        return HttpResponseRedirect(redirect_to)
>                else:
>                        # If form validation fails, use original reverse url
>                        redirect_to = request.GET.get('next', 
> reverse('index_view'))
>
>        else:
>                # If first loading form, grab referer and pass to form
>                referer = request.META.get('HTTP_REFERER', None)
>
>                # Pass original location in next url param
>                if referer is None:
>                        redirect_to = reverse('index_view')
>                else:
>                        try:
>                                redirect_to = urlsplit(referer, 'http', 
> False)[2]
>                        except IndexError:
>                                redirect_to = reverse('index_view')
>
>
>        return render_to_response('upload.html', {'form': form,'obj':
> object,'redirect_to':redirect_to}, context_instance =
> RequestContext(request))
>
> If I remove the def __init__ from the form class, it works perfectly,
> but always shows the title.  But with that in the form class, it
> always says "This field is required."  For just the imagefield if the
> title is suppressed or for both the title and the imagefield if the
> title is not suppressed.
>
> Suggestions?
>
> On Nov 8, 3:47 pm, Knut Ivar Nesheim  wrote:
>> Maybe you could just use subclassing instead of doing stuff at run-time:
>>
>> class UploadForm(forms.Form):
>>     file = ...
>>     # custom upload and validation code here
>>
>> class ThumbnailUploadForm(UploadForm):
>>     pass
>>
>> class UploadFileForm(UploadForm):
>>     title = ...
>>
>> As for your current approach, it looks correct. I've done the same
>> several times and it works as expected. Make sure you are really
>> really passing show_title correctly in your thumbnail case.
>>
>> Regards
>> Knut
>>
>> On Mon, Nov 8, 2010 at 9:29 PM, Ed  wrote:
>> > I have an image upload form that takes a title and a file for its
>> > field. I have two uses for it. Most of the time I call it, I need both
>> > a title and the image itself. But when I call it simply to grab a
>> > thumbnai

Re: Using Django's auth for Trac too

2010-11-09 Thread Knut Ivar Nesheim
Hi,

See the following link to the docs. This should be exactly what you want.

http://docs.djangoproject.com/en/dev/howto/apache-auth/

Regards
Knut

On Tue, Nov 9, 2010 at 6:51 AM, Torsten Bronger
 wrote:
> Hallöchen!
>
> I know that my question has a strong Apache component, but can
> anybody here give me hints for how to use Django's auth system for a
> Trac installation running on the same Apache?  I.e., iff someone is
> logged in in Django, it is also authenticated in Trac.  I already
> have my own Django auth module that just needed to be fleshed out.
> Maybe Django keeps a file up-to-date with all logged-in users, which
> Apache uses for Trac authentication?
>
> Thank you!
>
> Tschö,
> Torsten.
>
> --
> Torsten Bronger, aquisgrana, europa vetus
>                   Jabber ID: torsten.bron...@jabber.rwth-aachen.de
>                                  or http://bronger-jmp.appspot.com
>
> --
> You received this message because you are subscribed to the Google Groups 
> "Django users" group.
> To post to this group, send email to django-us...@googlegroups.com.
> To unsubscribe from this group, send email to 
> django-users+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/django-users?hl=en.
>
>

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



Re: Using Django's auth for Trac too

2010-11-09 Thread Torsten Bronger
Hallöchen!

Knut Ivar Nesheim writes:

> See the following link to the docs. This should be exactly what
> you want.
>
> http://docs.djangoproject.com/en/dev/howto/apache-auth/

We use WSGI.  But if all else fails, switching to mod_python may be
an alternative.  Thank you!

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
   Jabber ID: torsten.bron...@jabber.rwth-aachen.de
  or http://bronger-jmp.appspot.com

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



Re: Validator for \t

2010-11-09 Thread Ralf Peschke
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Thank you for your response, Cliff.
But the strip-command wasn't my problem. I wondered why Django let pass
these kind of invalid input and if there is an easy way to toggle this
behavior for the whole project. I could not find anything in the Django
docs.
Now I'm thinking of overwriting the to_python-Method of the models
charField-class.
Or are there better solutions?


Am 08.11.2010 21:55, schrieb J. Cliff Dyer:
> On Mon, 2010-11-08 at 12:21 -0800, Ralf wrote:
>> Hi,
>>
>> my users put values like 'Paul\t\t' per copy and paste into html-
>> formfields and suceeded, the values ended up in the database.
>> I wonder whether there is no build-in-validator to prevent these kind
>> of invalid input.
>>
>> Is there a cheap way to validate or strip these kind of input?
>>
> 
> Yep.  A string in python has a strip() method that will take any
> whitespace off the beginning and end of the string.
> 
> >>> username = username.strip()
> 
> You can also specify characters to strip off.
> 
> >>> username = ' abcd .,.'
> >>> username = username.strip('.,')
> >>> username
> ' abcd '
> 
> You should really check out the python tutorial at
> http://docs.python.org/tutorial/
> 
> Cheers,
> Cliff
> 
> 


- -- 

Peschke IT-Beratung

Ralf Peschke
Hüffener Heide 3
32257  Bünde
Tel:   05223/ 97 89 07 90
Fax:   05223/ 97 89 07 99
Mobil: 0175/ 32 72 561
E-Mail: rpesc...@peschke-it.de

- --
Diese E-Mail könnte vertrauliche und/oder rechtlich geschützte
Informationen enthalten. Wenn Sie nicht der richtige Adressat sind oder
diese E-Mail irrtümlich erhalten haben, informieren Sie bitte sofort den
Absender und vernichten Sie diese Mail. Das unerlaubte Kopieren sowie die
unbefugte Weitergabe dieser Mail sind nicht gestattet.

This e-mail may contain confidential and/or privileged information. If you
are not the intended recipient (or have received this e-mail in error)
please notify the sender immediately and destroy this e-mail. Any
unauthorised copying, disclosure or distribution of the material in this
e-mail is strictly forbidden.

-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.10 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iEYEARECAAYFAkzZEBQACgkQb2+5ZL6Nh6FJgACeNtfWTC3DNBx+2f2KCHKZt8GT
CwMAnixjz5w6GYSEzK6qfX4+iMaex3Ho
=DKYk
-END PGP SIGNATURE-

-- 
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: Validator for \t

2010-11-09 Thread Daniel Roseman
On Nov 9, 9:11 am, Ralf Peschke  wrote:

> Thank you for your response, Cliff.
> But the strip-command wasn't my problem. I wondered why Django let pass
> these kind of invalid input and if there is an easy way to toggle this
> behavior for the whole project. I could not find anything in the Django
> docs.
> Now I'm thinking of overwriting the to_python-Method of the models
> charField-class.
> Or are there better solutions?

Why should Django think that input is invalid? It's perfectly valid
content for a textbox - it's just your business rules that say
otherwise. So you need to tell Django about your business rules, which
you do via validation:
http://docs.djangoproject.com/en/1.2/ref/validators/
--
DR.

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



Re: Using Django's auth for Trac too

2010-11-09 Thread Graham Dumpleton


On Nov 9, 7:54 pm, Torsten Bronger 
wrote:
> Hall chen!
>
> Knut Ivar Nesheim writes:
> > See the following link to the docs. This should be exactly what
> > you want.
>
> >http://docs.djangoproject.com/en/dev/howto/apache-auth/
>
> We use WSGI.  But if all else fails, switching to mod_python may be
> an alternative.  Thank you!

http://code.google.com/p/modwsgi/wiki/AccessControlMechanisms

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



Mysql Quires using raw()

2010-11-09 Thread Jagdeep Singh Malhi
hi
I am facing problem with raw() mysql quiers
for example :
maxid = Client.objects.raw('SELECT Max(id) FROM client')

print maxid

output is :-


I am using Django 1.2 version.
where I am 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-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: non-ASCII characters in {{}}

2010-11-09 Thread bruno desthuilliers


On 9 nov, 00:13, Sébastien RAGONS  wrote:
> Hello,
>
> I try to display an article but there is char like 'é'.

Django uses only unicode internally. If you take care of using utf8
encoding all the way down (python source files, template source files,
database, webserver etc) you shouldn't have any problem with non-ascii
characters.

But anyway : I don't see how it relates to your problem:

> The template is correctly displayed but there is no trace
> of the article (and no error are logged).
>
> the line 'print html' show th article correctky:
> Table des matières
> Erreur
> 404
> Erreur 404
> 
> La page demandée n'existe pas !
> 


Is that really the content you're expecting ?

> If i remove all the 'é', the page is correct and full
>
> def displayArticle(request, nomArticle):
>     article = Article()

This creates a new empty instance of class Article - whatever that
class is.

>     html = article.lecture(nomArticle)

What is this code supposed to do ?

>     print html
>     return render_to_response('article.html',
>         {'article': html})
>
> It's not a probleme with the template

hard to tell without seeing the template code.

> because if i send 'é'
> throw it, it's ok.

And ?

> could you help me

How do you think we can help you when you don't provide enough
informations ?

-- 
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 extra() be used to implement JOIN?

2010-11-09 Thread bruno desthuilliers
On 8 nov, 16:52, Daniel Roseman  wrote:

> This is exactly what `select_related()` does. The only gotcha is that
> you have to start with the Answer model, rather than Question, but the
> result is the same:
>
>     answers = Answer.objects.filter(question_id=1).select_related()
>
> Now each answer object has a pre-fetched 'question' attribute, and
> accessing it won't hit the db again.

Note that this also requires replacing the 'question_id' IntegerField
in Answer with a 'question' ForeignKey ;)

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



A cache-busting sledge-hammer

2010-11-09 Thread Ole Laursen
Hi!

If you have the problem of visitors getting errors from using the old
Javascripts and CSS when you roll out a release, I have a sledge-
hammer solution that only requires a single-line change in your
settings.py.

It's a middleware that examines the HTML from your views and appends a
little timestamp to all URLs pointing to local files it can find. No
further setup required, although with an extra three-line
configuration to lighttpd or nginx (or whatever you're using to serve
static files), you can achieve near-perfect caching.

You can grab the middleware here, modtimeurls.py:

  http://people.iola.dk/olau/python/


I also blogged about the rationale behind here:

  http://ole-laursen.blogspot.com/2010/11/cache-busting-in-django.html

Ole

-- 
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: "Include" tag and dynamically generated file to include

2010-11-09 Thread Daniel Roseman
On Nov 9, 10:25 am, "samuele.mattiuzzo"  wrote:
> Hi all,
> i have a problem with a django template.
>
> i have a value (a number) stored into a mysql database and i'm
> accessing it using {{ totem.layout.communitySpace }}
>
> This number sould be used to get a page:
> {% include "bacheche/clip_{{ totem.layout.communitySpace }}.html" %}
>
> and it should return "clip_2.html" (for example).
>
> This doesn't seem possible, since i receive "Page
> clip_{{ totem.layout.communitySpace }}.html not found"
> I also tried without using parenthesis, but i get the same error
> ("Page clip_totem.layout.communitySpace.html not found") and i have to
> use the "ifequal" tag to include the correct page, but this isn't
> dynamic at all, everytime we add a new page, we also have to edit the
> main template if - else's statements!
>
> How can i manage this? Thank you all for your suggestions!

There's nothing in the documentation to imply that you can use
variable tags inside other tags. You simply can't do that.

You can use a variable (without the braces) as the argument to
include, so you should build up that value in your view.
Alternatively, you could add a method to totem or totem.layout,
whatever they are, to generate the name based on the value of
communitySpace.
--
DR.

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



Re: get_absolute_url and root url

2010-11-09 Thread devbird
you should set the "root url" as '^$'(an empty string), without any
'/', and remove the slash from the url pattern regexp.


On Nov 8, 2:07 pm, Dirk Eschler  wrote:
> Hello,
>
> i've built an app which is based on Django's flatpages app. It reuses most of
> its features including the FlatPageFallbackMiddleware.
>
> Everything works fine except when the root url '/' is used as url, in which
> case get_absolute_url returns '//'. The hostname defined in the sites app is
> not included, so the browser will treat the link as 'http:///'.
>
> How can i get around this problem? Setting APPEND_SLASH to False doesn't make
> any difference.
>
> models.py:
> ==
> class ContentPage(MediaAwareManagedContent):
>     url = models.CharField(_(u'URL'), max_length=100, db_index=True)
>
>     @models.permalink
>     def get_absolute_url(self):
>         url = self.url
>         if self.url[0] == '/' and self.url != '/':
>             url = self.url[1:]
>         return ('content_page_detail', (), {'url': url})
>
> url.py:
> ===
> urlpatterns = patterns('cms.contentpage.views',
>     url(r'^(?P.*/)$', 'contentpage', name='content_page_detail'),
> )
>
> Best Regards,
> Dirk Eschler
>
> --
> Dirk Eschler 

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



"Include" tag and dynamically generated file to include

2010-11-09 Thread samuele.mattiuzzo
Hi all,
i have a problem with a django template.

i have a value (a number) stored into a mysql database and i'm
accessing it using {{ totem.layout.communitySpace }}

This number sould be used to get a page:
{% include "bacheche/clip_{{ totem.layout.communitySpace }}.html" %}

and it should return "clip_2.html" (for example).

This doesn't seem possible, since i receive "Page
clip_{{ totem.layout.communitySpace }}.html not found"
I also tried without using parenthesis, but i get the same error
("Page clip_totem.layout.communitySpace.html not found") and i have to
use the "ifequal" tag to include the correct page, but this isn't
dynamic at all, everytime we add a new page, we also have to edit the
main template if - else's statements!

How can i manage this? Thank you all for your suggestions!

-- 
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: Exclude form field when calling form from view

2010-11-09 Thread Ed
I'm still a bit confused, apologies.

This is the beginning of the view:

def upload_file(request, modelname, id):
if modelname == 'film':
form = UploadFileForm()
else:
form = UploadFileForm(show_title=False)
object = get_object_or_404(modelname, id__iexact=id)
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)

How would I pass in show_title correctly?  I tried rewriting the last
line: form = UploadFileForm(request.POST, request.FILES,
show_title=False) , but I got an error on submission: __init() got
multiple values for keyword argument 'show_title'

And in terms of correctly passing the variable, does it need to be
explicitly passed in the 3rd line above: form = UploadFileForm(), when
I want the title shown?  Or simply when grabbing the request.POST/
FILES?

Thank you for your help so far,
Ed

On Nov 9, 3:33 am, Knut Ivar Nesheim  wrote:
> The problem is here:
>
>  if request.method == 'POST':
>                form = UploadFileForm(request.POST, request.FILES)
>
> You need to make sure you always pass in show_title correctly when
> instantiating the form.
>
> Regards
> Knut
>
>
>
>
>
>
>
> On Tue, Nov 9, 2010 at 3:57 AM, Ed  wrote:
> > I can fall back on the subclassing suggestion.  But I'd like to give
> > this one more shot for a fix.  I think it has something to do with the
> > request.FILES that I need.  Here is my complete form:
>
> > class UploadFileForm(forms.Form):
> >        def __init__(self, show_title=True, *args, **kwargs):
> >                super(UploadFileForm, self).__init__(*args, **kwargs)
> >                if not show_title:
> >                        del self.fields['title']
>
> >        def clean_file(self):
> >                content = self.cleaned_data['file']
> >                content_type = content.content_type.split('/')[0]
> >                if content_type in settings.CONTENT_TYPES:
> >                        if content._size > settings.MAX_UPLOAD_SIZE:
> >                                raise forms.ValidationError(_('Please keep 
> > filesize under %s.
> > Current filesize %s') % (filesizeformat(settings.MAX_UPLOAD_SIZE),
> > filesizeformat(content._size)))
> >                else:
> >                        raise forms.ValidationError(_('File type is not 
> > supported'))
> >                return content
>
> >        title = forms.CharField(max_length=50)
> >        file = forms.ImageField(label='Select photo to upload')
>
> > And here is my complete view:
>
> > def upload_file(request, modelname, id):
> >        if modelname == 'film':
> >                form = UploadFileForm()
> >        else:
> >                form = UploadFileForm(show_title=False)
>
> >        object = get_object_or_404(modelname, id__iexact=id)
> >        if request.method == 'POST':
> >                form = UploadFileForm(request.POST, request.FILES)
> >                if form.is_valid():
> >                        file = request.FILES["file"]
> >                        filename = file.name
> >                        content = file.read()
>
> >                        # Assign unique name to file
> >                        new_image_name, extension = unique_name(filename, 
> > object,
> > modelname)
>
> >                        #FUTURE: Resize middle and resize remaining in 
> > background
> >                        #SMALL
> >                        #img_resizer(content)
> >                        u_small = new_image_name + '_small.jpg'
> >                        store_in_s3(u_small, img_resizer(content,250,250,90))
>
> >                        # Save thumbnail url to object
> >                        object.url_small = u_small
> >                        object.save()
>
> >                        # Grab Next param to determine where to redirect 
> > back to
> >                        redirect_to = request.GET.get('next', 
> > reverse('index_view'))
> >                        return HttpResponseRedirect(redirect_to)
> >                else:
> >                        # If form validation fails, use original reverse url
> >                        redirect_to = request.GET.get('next', 
> > reverse('index_view'))
>
> >        else:
> >                # If first loading form, grab referer and pass to form
> >                referer = request.META.get('HTTP_REFERER', None)
>
> >                # Pass original location in next url param
> >                if referer is None:
> >                        redirect_to = reverse('index_view')
> >                else:
> >                        try:
> >                                redirect_to = urlsplit(referer, 'http', 
> > False)[2]
> >                        except IndexError:
> >                                redirect_to = reverse('index_view')
>
> >        return render_to_response('upload.html', {'form': form,'obj':
> > object,'redirect_to':redirect_to}, context_instance =
> > RequestContext(request))
>
> > If I remove the def __init__ from t

Re: Mysql Quires using raw()

2010-11-09 Thread Jani Tiainen
On Tuesday 09 November 2010 12:25:30 Jagdeep Singh Malhi wrote:
> hi
> I am facing problem with raw() mysql quiers
> for example :
> maxid = Client.objects.raw('SELECT Max(id) FROM client')
> 
> print maxid
> 
> output is :-
> 
> 
> I am using Django 1.2 version.
> where I am wrong?

Nowhere. Output is correct and as documented - you get back *RawQuerySet*. Not 
a single value.

So you have to do something like:

maxid = Client.objects.raw('SELECT MAX(job_no) as max_job_no FROM 
CLIENT').values_list('max_job_no', flat=True)[0]

-- 

Jani Tiainen


-- 
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: A cache-busting sledge-hammer

2010-11-09 Thread Cal Leeming [Simplicity Media Ltd]
That's a pretty neat idea, originally I was having to use { now|date:"u" 
} to put the current epoch timestamp on the end of the urls...


On 09/11/2010 10:35, Ole Laursen wrote:

Hi!

If you have the problem of visitors getting errors from using the old
Javascripts and CSS when you roll out a release, I have a sledge-
hammer solution that only requires a single-line change in your
settings.py.

It's a middleware that examines the HTML from your views and appends a
little timestamp to all URLs pointing to local files it can find. No
further setup required, although with an extra three-line
configuration to lighttpd or nginx (or whatever you're using to serve
static files), you can achieve near-perfect caching.

You can grab the middleware here, modtimeurls.py:

   http://people.iola.dk/olau/python/


I also blogged about the rationale behind here:

   http://ole-laursen.blogspot.com/2010/11/cache-busting-in-django.html

Ole



--
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: Custom formset validation: having a "save?" checkbox for each form

2010-11-09 Thread Carsten Fuchs

Dear Knut,

thank you very much for your reply!
I guess I didn't see the forest for the trees...

Somehow I thought there is a way to validate only those forms in a formset whose "should save" 
boolean field is set - which in turn would have required validating only this field of every form 
independently first.


But of course your suggestion is much clearer: Require the entire formset to be valid first, no 
matter if the individual forms have "should save" set or not, then proceed from there.


Many thanks, and best regards,
Carsten



On 08.11.2010 21:42, Knut Ivar Nesheim wrote:

Hi,

Every Form subclass defines a method called 'is_valid()', even the
FormSet has one, which will repeatedly call it on every form. After
running is_valid(), form.cleaned_data will contain cleaned data from
the forms.

On subclasses of FormSet you can also override the clean method, which
allows you to do validation that depends on multiple forms, for
example making sure the same day is not reported twice, etc. See
http://docs.djangoproject.com/en/dev/topics/forms/formsets/#custom-formset-validation

Rewriting your view to take advantage of this, as well as a nice idioms:

def my_view(...):
 formset = FormsetFactory(request.POST or None)

 if formset.is_valid():
 for form in formset.forms:
 if form.cleaned_data['should_save']:
 # save stuff here
 return redirect(my_other_view)

 return render_to_response('template', { 'formset': formset })

Replace with meaningful variables specific to your forms and models.

As a side note, every subclass of Form allows overriding the clean
method for doing custom validation. This can be extremely helpful in
cases like this, as you can move complex logic from your view, into
the forms which have access to everything.

As another side note, you mentioned in the comment to pause that you
actually want to store a timedelta. See this snippet for a Field which
does exactly that: http://djangosnippets.org/snippets/1060/ See the
following SO question for how to do it yourself:
http://stackoverflow.com/questions/801912/how-to-put-timedelta-in-django-model

Regards
Knut

On Mon, Nov 8, 2010 at 6:48 PM, Carsten Fuchs  wrote:

Hi all,

my name is Carsten Fuchs, and this is my first post here. I'm normally a C++
developer for Windows and Linux desktop and server applications, and have
begun my first (big) database-web project in mid summer. Let me start with
saying that Django is utterly awesome: I've been able to complete a very
large part of this project in very short time, reading the excellent Django
online documentation and the Django online book. A huge thanks to everyone
who is involved!

My Django application is for recording and managing the work hours of the
staff of a company with about 1000 employees, implemented on Ubuntu 10.04
with Django 1.2, Python 2.6, Apache2 as webserver, and an Oracle 10g
database.

My question is about validating the formset that is used for editing the
work hours (but I'm happy about all comments on whatever strikes you odd in
the code below ;-) ).


The main model is (slightly simplified for clarity):

# This model should really be named "Workday", not "Erfasst".
class Erfasst(models.Model):
key= models.ForeignKey(Mitarbeiter, db_column='key', to_field='key')
datum  = models.DateField()
anfang = models.TimeField()   # Begin of work.
ende   = models.TimeField()   # End of work.
pause  = models.CharField(max_length=8, blank=True) # (Need a
timedelta field...)


I wrote a view with a formset for editing the work hours in the above model
of an entire week or month. The form is:

class ErfasseZeitForm(forms.Form):
# ID of "Erfasst" entry, if present in database.
ErfasstID = forms.IntegerField(required=False,
widget=forms.HiddenInput())

# We must pass the date for days that are not yet mentioned in the
database.
Datum = forms.DateField(widget=forms.HiddenInput())

# Begin, end, and pause of work.
Anfang= forms.TimeField(required=False)
Ende  = forms.TimeField(required=False)
Pause = forms.TimeField(required=False)

# A checkbox for "Save this form?" (which is part of a formset that
covers an entire month)
Speichern = forms.BooleanField(required=False)


Some notes about this form and the derived formset:
- We do not have data in table "Erfasst" for every day in the month, e.g.
Sundays or days in the future are usually not present, but the Formset is
still expected to have forms with empty data for such days.
- We do not use a ModelForm, so that we can have additional form fields
that have no correspondence in the model, such as "Speichern" above.

At  I've uploaded a
screenshot of how the form renders, with default data for days in the
future, and the "Save?" checkbox that the user can use to have his changes
saved into the database or not.
(The full, current source code o

Re: Exclude form field when calling form from view

2010-11-09 Thread Knut Ivar Nesheim
Whenever you create an instance of UploadFileForm you need to
explicitly tell it to not show the title. In the first 4 lines of your
view, you do it correctly, but if you receive post data, your code
does not do anything with show_title, and since you set it to True by
default, it will get included.

By the way, here is an updated UploadFileForm, which preservers *args
and **kwargs

class UploadFileForm(forms.Form):
   def __init__ (self, *args, **kwargs):
   show_title = kwargs.pop('show_title', Ttrue)
   super (BaseClass, self).__init__(*args, **kwargs)
   if not show_title:
   del self.fields['title']

   ...

You still need to explicitly pass in show_title = False if you do not
want the title to be present on the form. Otherwise you could change
it to kwargs.pop('show_title', False), but then you need to explicitly
tell it when you want the title field.

I still think it would be better to simply use subclasses of the same
form. With the example I gave in a previous message, you could use it
as follows:

def upload_image(request, ...):
model_class = Image
form_class = UploadForm
return upload_file(request, model_class, form_class)

def upload_thumbnail(request, ...):
model_class = Thumbnail
form_class = UploadThumbnailForm
return upload_file(request, model_class, form_class)

def upload_file(request, model_class, form_class):
object = get_object_or_404(model, )
form = form_class(request.POST or None)
if form.is_valid():
 ...



Regards
Knut

On Tue, Nov 9, 2010 at 1:16 PM, Ed  wrote:
> I'm still a bit confused, apologies.
>
> This is the beginning of the view:
>
> def upload_file(request, modelname, id):
>        if modelname == 'film':
>                form = UploadFileForm()
>        else:
>                form = UploadFileForm(show_title=False)
>        object = get_object_or_404(modelname, id__iexact=id)
>        if request.method == 'POST':
>                form = UploadFileForm(request.POST, request.FILES)
>
> How would I pass in show_title correctly?  I tried rewriting the last
> line: form = UploadFileForm(request.POST, request.FILES,
> show_title=False) , but I got an error on submission: __init() got
> multiple values for keyword argument 'show_title'
>
> And in terms of correctly passing the variable, does it need to be
> explicitly passed in the 3rd line above: form = UploadFileForm(), when
> I want the title shown?  Or simply when grabbing the request.POST/
> FILES?
>
> Thank you for your help so far,
> Ed
>
> On Nov 9, 3:33 am, Knut Ivar Nesheim  wrote:
>> The problem is here:
>>
>>  if request.method == 'POST':
>>                form = UploadFileForm(request.POST, request.FILES)
>>
>> You need to make sure you always pass in show_title correctly when
>> instantiating the form.
>>
>> Regards
>> Knut
>>
>>
>>
>>
>>
>>
>>
>> On Tue, Nov 9, 2010 at 3:57 AM, Ed  wrote:
>> > I can fall back on the subclassing suggestion.  But I'd like to give
>> > this one more shot for a fix.  I think it has something to do with the
>> > request.FILES that I need.  Here is my complete form:
>>
>> > class UploadFileForm(forms.Form):
>> >        def __init__(self, show_title=True, *args, **kwargs):
>> >                super(UploadFileForm, self).__init__(*args, **kwargs)
>> >                if not show_title:
>> >                        del self.fields['title']
>>
>> >        def clean_file(self):
>> >                content = self.cleaned_data['file']
>> >                content_type = content.content_type.split('/')[0]
>> >                if content_type in settings.CONTENT_TYPES:
>> >                        if content._size > settings.MAX_UPLOAD_SIZE:
>> >                                raise forms.ValidationError(_('Please keep 
>> > filesize under %s.
>> > Current filesize %s') % (filesizeformat(settings.MAX_UPLOAD_SIZE),
>> > filesizeformat(content._size)))
>> >                else:
>> >                        raise forms.ValidationError(_('File type is not 
>> > supported'))
>> >                return content
>>
>> >        title = forms.CharField(max_length=50)
>> >        file = forms.ImageField(label='Select photo to upload')
>>
>> > And here is my complete view:
>>
>> > def upload_file(request, modelname, id):
>> >        if modelname == 'film':
>> >                form = UploadFileForm()
>> >        else:
>> >                form = UploadFileForm(show_title=False)
>>
>> >        object = get_object_or_404(modelname, id__iexact=id)
>> >        if request.method == 'POST':
>> >                form = UploadFileForm(request.POST, request.FILES)
>> >                if form.is_valid():
>> >                        file = request.FILES["file"]
>> >                        filename = file.name
>> >                        content = file.read()
>>
>> >                        # Assign unique name to file
>> >                        new_image_name, extension = unique_name(filename, 
>> > object,
>> > modelname)
>>
>> >                        #FUT

Re: Generic Views - do you use them?

2010-11-09 Thread ringemup

I don't use them either for much the same reasons, and because I often
end up using custom render_to_response shortcuts that set common
context or handle custom template loading.  Although the new class-
based views may make them more customizable.

I don't see much need for an alternative, though (I'm perfectly happy
writing my own views), and don't know what sort of alternate approach
you're suggesting.



On Nov 8, 6:42 pm, Ted  wrote:
> What are their pros and cons?  How often do you use them when you're
> coding?
>
> The more I code in django the less I find generic views to be useful
> shortcuts (direct to template being the exception).
>
> My biggest complaints are:
> * You don't end up saving many keystrokes unless you have 3 or more
> views that are going to use the same info_dict.
> * They can't be tweaked or changed much before you have to move the
> code to the views file, destroying the keystroke savings.
> * Second syntax for doing the same thing makes Django harder to
> learn.
>
> Am I alone on this?
>
> I've thought about it and i think there is a better way.  I want to
> see if there are others in the community who aren't in love with
> generic views before I develop the alternate approach.
>
> I'm not trying to start a flame war.

-- 
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: "Include" tag and dynamically generated file to include

2010-11-09 Thread samuele.mattiuzzo
Ok, i'll stick with the building up into the view!
Thanks, by searching older posts i found something, so i'll read
those.
Thanks again!

On 9 Nov, 13:09, Daniel Roseman  wrote:
> On Nov 9, 10:25 am, "samuele.mattiuzzo"  wrote:
>
>
>
>
>
> > Hi all,
> > i have a problem with a django template.
>
> > i have a value (a number) stored into a mysql database and i'm
> > accessing it using {{ totem.layout.communitySpace }}
>
> > This number sould be used to get a page:
> > {% include "bacheche/clip_{{ totem.layout.communitySpace }}.html" %}
>
> > and it should return "clip_2.html" (for example).
>
> > This doesn't seem possible, since i receive "Page
> > clip_{{ totem.layout.communitySpace }}.html not found"
> > I also tried without using parenthesis, but i get the same error
> > ("Page clip_totem.layout.communitySpace.html not found") and i have to
> > use the "ifequal" tag to include the correct page, but this isn't
> > dynamic at all, everytime we add a new page, we also have to edit the
> > main template if - else's statements!
>
> > How can i manage this? Thank you all for your suggestions!
>
> There's nothing in the documentation to imply that you can use
> variable tags inside other tags. You simply can't do that.
>
> You can use a variable (without the braces) as the argument to
> include, so you should build up that value in your view.
> Alternatively, you could add a method to totem or totem.layout,
> whatever they are, to generate the name based on the value of
> communitySpace.
> --
> DR.

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



Re: A cache-busting sledge-hammer

2010-11-09 Thread Łukasz Rekucki
I would recommend using one of asset managers that provide JS/CSS
versioning instead. Their aren't very hard to install. You can compare
some of the more popular at djangopackages.com:
http://djangopackages.com/grids/g/asset-managers/

In most cases you get things like JS/CSS combining and compression as
an extra bonus. Definitly something you will want in the long run.


On 9 November 2010 13:07, Cal Leeming [Simplicity Media Ltd]
 wrote:
> That's a pretty neat idea, originally I was having to use { now|date:"u" }
> to put the current epoch timestamp on the end of the urls...
>
> On 09/11/2010 10:35, Ole Laursen wrote:
>>
>> Hi!
>>
>> If you have the problem of visitors getting errors from using the old
>> Javascripts and CSS when you roll out a release, I have a sledge-
>> hammer solution that only requires a single-line change in your
>> settings.py.
>>
>> It's a middleware that examines the HTML from your views and appends a
>> little timestamp to all URLs pointing to local files it can find. No
>> further setup required, although with an extra three-line
>> configuration to lighttpd or nginx (or whatever you're using to serve
>> static files), you can achieve near-perfect caching.
>>
>> You can grab the middleware here, modtimeurls.py:
>>
>>   http://people.iola.dk/olau/python/
>>
>>
>> I also blogged about the rationale behind here:
>>
>>   http://ole-laursen.blogspot.com/2010/11/cache-busting-in-django.html
>>
>> Ole
>>
>
> --
> 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.
>
>



-- 
Łukasz Rekucki

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



django models: two foreignky for "User"

2010-11-09 Thread luckrill
I write following models:

class article(models.Model):
created_by = models.ForeignKey('User')
edited_by = models.ForeignKey('User')

django report error. How to ForeignKey "User" for two field.

-- 
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: clean method in a model

2010-11-09 Thread refreegrata
ok, thanks for the answer, but I want use the clean method in a model,
not in a form. For that in the clean method I throw a ValidationError,
but the error message isn't associated to the field form of the
modelform.

On 8 nov, 19:17, cootetom  wrote:
> If you want to associate an error to a specific field in a model form
> then you need to populate self._errors with the error you find. Have a
> read about this on the Django docs to see how it is done.
>
> http://docs.djangoproject.com/en/1.1/ref/forms/validation/#ref-forms-...
>
> The last example shows how to associate a error with a specific field
> in a form class.
>
> On Nov 8, 8:40 pm, refreegrata  wrote:
>
> > Hello list. I want to use the clean method in a model.
> > --
> > class myModel(models.Model):
> >     fields 
>
> >     def clean(self):
> >             raise ValidationError('The Error.')
> > ---
>
> > Thats works fine. My question  is, how can I associate this error to
> > the field in the modelform?. With this method the form validation can
> > be controlled, but I can't pick the error dynamically to show at the
> > user.
>
> > Thanks for read.
>
>

-- 
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: "Include" tag and dynamically generated file to include

2010-11-09 Thread Łukasz Rekucki
On 9 November 2010 11:25, samuele.mattiuzzo  wrote:
> Hi all,
> i have a problem with a django template.
>
> i have a value (a number) stored into a mysql database and i'm
> accessing it using {{ totem.layout.communitySpace }}
>
> This number sould be used to get a page:
> {% include "bacheche/clip_{{ totem.layout.communitySpace }}.html" %}
>
> and it should return "clip_2.html" (for example).
>
> This doesn't seem possible, since i receive "Page
> clip_{{ totem.layout.communitySpace }}.html not found"
> I also tried without using parenthesis, but i get the same error
> ("Page clip_totem.layout.communitySpace.html not found") and i have to
> use the "ifequal" tag to include the correct page, but this isn't
> dynamic at all, everytime we add a new page, we also have to edit the
> main template if - else's statements!
>
> How can i manage this? Thank you all for your suggestions!
>

You should first create the name as a string and then pass it to the
{% include %}. You can do this in view (with a simple "clip_%d.html" %
num), a custom tag or with something horrible like this:

{% with totem.layout.communitySpace|stringformat:"d" as page_number %}
{% with "bacheche/clip_"|add:page_number|add:".html" as template_name %}
{% include template_name %}
{% endwith %}
{% endwith %}


-- 
Łukasz Rekucki

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



move up tree in {% include "/dir/name.html" %} statement

2010-11-09 Thread Brian
Thanks for the help.

I'm using Python 2.5 and Django Template 1.1

I can't seem to move up the directory tree for inserting of html files
using  {% include file %} statement

Sample dir structure:

---/lib/Top.html
---/lib/
root/
---/main/
---/main/include/HomeLogo.html
---/main/HOME.html

Inside HOME.html I can use {% include "/include/HomeLogo.html" %} =
Works just fine to any where up the tree.

BUT

I can not find a way to include the top.html file in home.html.
I tried {% include "/lib/Top.html" %}, {% include "lib/Top.html" %} ,
{% include "../lib/Top.html" %}, {% include "./lib/Top.html" %}
can not find a way to insert the html in.

Thanks again.




-- 
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: get_absolute_url and root url

2010-11-09 Thread devbird
Sorry, I was wrong.
The url pattern must have a trailing slash.

On Nov 9, 9:33 am, devbird  wrote:
> you should set the "root url" as '^$'(an empty string), without any
> '/', and remove the slash from the url pattern regexp.
>
> On Nov 8, 2:07 pm, Dirk Eschler  wrote:
>
>
>
> > Hello,
>
> > i've built an app which is based on Django's flatpages app. It reuses most 
> > of
> > its features including the FlatPageFallbackMiddleware.
>
> > Everything works fine except when the root url '/' is used as url, in which
> > case get_absolute_url returns '//'. The hostname defined in the sites app is
> > not included, so the browser will treat the link as 'http:///'.
>
> > How can i get around this problem? Setting APPEND_SLASH to False doesn't 
> > make
> > any difference.
>
> > models.py:
> > ==
> > class ContentPage(MediaAwareManagedContent):
> >     url = models.CharField(_(u'URL'), max_length=100, db_index=True)
>
> >     @models.permalink
> >     def get_absolute_url(self):
> >         url = self.url
> >         if self.url[0] == '/' and self.url != '/':
> >             url = self.url[1:]
> >         return ('content_page_detail', (), {'url': url})
>
> > url.py:
> > ===
> > urlpatterns = patterns('cms.contentpage.views',
> >     url(r'^(?P.*/)$', 'contentpage', name='content_page_detail'),
> > )
>
> > Best Regards,
> > Dirk Eschler
>
> > --
> > Dirk Eschler 

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



Re: django models: two foreignky for "User"

2010-11-09 Thread Marcos Moyano

Use related_name
(http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name)

Rgds,
Marcos

At Tue, 9 Nov 2010 07:20:45 -0800 (PST),
luckrill wrote:
> 
> I write following models:
> 
> class article(models.Model):
> created_by = models.ForeignKey('User')
> edited_by = models.ForeignKey('User')
> 
> django report error. How to ForeignKey "User" for two field.
> 
> -- 
> 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: A cache-busting sledge-hammer

2010-11-09 Thread Ole Laursen
On Nov 9, 1:13 pm, Łukasz Rekucki  wrote:
> I would recommend using one of asset managers that provide JS/CSS
> versioning instead. Their aren't very hard to install. You can compare
> some of the more popular at 
> djangopackages.com:http://djangopackages.com/grids/g/asset-managers/

Seems like there's a parsing one now, which is neat. It doesn't appear
to help with images though.


> In most cases you get things like JS/CSS combining and compression as
> an extra bonus. Definitly something you will want in the long run.

Definitely is a strong word. I know some people, especially at Google,
are pushing for this, but the obfuscation involved really goes against
the principles that make the web so powerful.


Ole

-- 
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: clean method in a model

2010-11-09 Thread cootetom
You say you want to do the clean in the model but then say you want
the error to be associated with the field in the ModelForm? If you
need that clean functionality to exist for both a model and a form of
that model then you could shift the checks into a function of it's own
out side of the class's then have a clean in both the model and the
form which calls the function to do the checks before deciding how to
raise the error.

The issue is that a form and a model use validation errors in
different ways. A form will send errors back to the templating layer
to show to a user but a model doesn't work like that as it would only
be manipulated directly in python code.

Does that make sense?



On Nov 9, 2:39 pm, refreegrata  wrote:
> ok, thanks for the answer, but I want use the clean method in a model,
> not in a form. For that in the clean method I throw a ValidationError,
> but the error message isn't associated to the field form of the
> modelform.
>
> On 8 nov, 19:17, cootetom  wrote:
>
>
>
>
>
>
>
> > If you want to associate an error to a specific field in a model form
> > then you need to populate self._errors with the error you find. Have a
> > read about this on the Django docs to see how it is done.
>
> >http://docs.djangoproject.com/en/1.1/ref/forms/validation/#ref-forms-...
>
> > The last example shows how to associate a error with a specific field
> > in a form class.
>
> > On Nov 8, 8:40 pm, refreegrata  wrote:
>
> > > Hello list. I want to use the clean method in a model.
> > > --
> > > class myModel(models.Model):
> > >     fields 
>
> > >     def clean(self):
> > >             raise ValidationError('The Error.')
> > > ---
>
> > > Thats works fine. My question  is, how can I associate this error to
> > > the field in the modelform?. With this method the form validation can
> > > be controlled, but I can't pick the error dynamically to show at the
> > > user.
>
> > > Thanks for read.

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



translate user registration errors

2010-11-09 Thread Andrea Imparato
Hello to all,

I have to translate Username can only contain alphanumeric characters
and the underscore. error when my users have to register to my site.
How can I do that? I tried blocktrans without success :(

Thanks

P.S.: django is so cool :)

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



Excessive tmp table creation for mysql

2010-11-09 Thread Nick
Yesterday I received a warning from our DB monitoring system stating
that my django DB had an excessive amount of temp tables created. Here
is the error:

* Nagios 2.10 *

Notification Type: PROBLEM

Service: mysql_tmp_disk_tables
Host:
Address:
State: WARNING

Date/Time: Mon Nov 8 15:19:18 CST 2010

Additional Info:

WARNING - 53.71% of 551680 tables were created on disk




 I was doing some light querying in the shell following a few
recursive relationships for some foreignkeys but nothing major. I have
several applications with full API's making requests constantly. This
warning has only just now popped up.

Has anyone seen anything like this?

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



Re: Excessive tmp table creation for mysql

2010-11-09 Thread Marc Aymerich
On Tue, Nov 9, 2010 at 7:49 PM, Nick  wrote:
> Yesterday I received a warning from our DB monitoring system stating
> that my django DB had an excessive amount of temp tables created. Here
> is the error:
>
> * Nagios 2.10 *
>
> Notification Type: PROBLEM
>
> Service: mysql_tmp_disk_tables
> Host:
> Address:
> State: WARNING
>
> Date/Time: Mon Nov 8 15:19:18 CST 2010
>
> Additional Info:
>
> WARNING - 53.71% of 551680 tables were created on disk
>
>
>
>
>  I was doing some light querying in the shell following a few
> recursive relationships for some foreignkeys but nothing major. I have
> several applications with full API's making requests constantly. This
> warning has only just now popped up.
>
> Has anyone seen anything like this?


This tables are created on disk when a query needs a tmp table bigger
than tmp_table_size and max_heap_table_size. The common situations
when a tmp table is needed are[1]:

*If there is an ORDER BY clause and a different GROUP BY clause, or if
the ORDER BY or GROUP BY contains columns from tables other than the
first table in the join queue, a temporary table is created.
*DISTINCT combined with ORDER BY may require a temporary table.
*If you use the SQL_SMALL_RESULT option, MySQL uses an in-memory
temporary table, unless the query also contains elements (described
later) that require on-disk storage.

You can lookup in your django code where this conditions are met or
you can just can increase the tmp_table_size and max_heap_table_size
thresholds on mysql server. :)

[1] http://dev.mysql.com/doc/refman/5.1/en/internal-temporary-tables.html

br
-- 
Marc

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



question about involve "vncserver" command with django

2010-11-09 Thread Bill
Hi all,

I met a problem, I can use python to execute the the command
"vncserver " to start vncserver use subprocess,
like this:
process = subprocess.Popen('vncserver' , shell=True)

but when I write this code to views.py it didn't work as I hope.
The Xvnc process listened on the port which Django used.

For example,  django listen on tcp port 8000, and the Xvnc also listen
on tcp port 8000.
It's wired.

Is there any way to involve the vncserver?


Regards,
Bill

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



change the color of messages fr .validate

2010-11-09 Thread John Fabiani
Hi,
Newbie here!  Therefore I'll need a little detail (like show the code).

How in the heck can I change the color of the messages from jquery.validate.js
Here's my code:

$("#registration_form").validate({

rules: {
first_name : "required",
last_name : "required",
  mailing_address : "required",
mailing_city : "required",
mailing_state : "required",
mailing_zip : "required",
daytime_phone : "required",
dob : "required",
txtPassword : "required",
txtConfirm : "required"

},

messages: {
first_name : jQuery.format("First Name is required"),
last_name : "Last Name is required",
  mailing_address : " A Mailing Address is required",
mailing_city : "Mailing City is required",
mailing_state : "Mailing State is required",
mailing_zip : "Mailing Zip is required",
daytime_phone : "Daytime Phone is required",
dob : "Date of Birth is required",
txtPassword : "Password is required",
txtConfirm : "Confirm Password is required"
},
submitHandler : function(form){$(form).ajaxSubmit({ beforeSubmit : 
showRequest, success: showResponse, dataType : "json"});}

Thanks in advance,
Joihnf

-- 
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: question about involve "vncserver" command with django

2010-11-09 Thread Jirka Vejrazka
> For example,  django listen on tcp port 8000, and the Xvnc also listen
> on tcp port 8000.
> It's wired.

  Hi Bill,

  this is technically impossible, two programs cannot listen on the
same TCP port (on one interface). It's very likely that it was Django
webserver listening there.

  Overall, starting VNC from a web application seems like a bad idea
in principle as the request-response cycle is not well suited for this
(as well as other reasons). Can you describe what are you trying to
achieve and why?

  Cheers

Jirka

-- 
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: clean method in a model

2010-11-09 Thread refreegrata
Thanks for answer. You have reason, I don't need do that. With a clean
method in the modelform is enough. This question appear, because
initialy I just wanted add a validator to the field of the model, but
for the validation the  parameter  "self" was necessary and I could
not find a way to pass this parameter. However I don't need this, with
a clean method in the form, I can solve this quickly.

On 9 nov, 13:44, cootetom  wrote:
> You say you want to do the clean in the model but then say you want
> the error to be associated with the field in the ModelForm? If you
> need that clean functionality to exist for both a model and a form of
> that model then you could shift the checks into a function of it's own
> out side of the class's then have a clean in both the model and the
> form which calls the function to do the checks before deciding how to
> raise the error.
>
> The issue is that a form and a model use validation errors in
> different ways. A form will send errors back to the templating layer
> to show to a user but a model doesn't work like that as it would only
> be manipulated directly in python code.
>
> Does that make sense?
>
> On Nov 9, 2:39 pm, refreegrata  wrote:
>
> > ok, thanks for the answer, but I want use the clean method in a model,
> > not in a form. For that in the clean method I throw a ValidationError,
> > but the error message isn't associated to the field form of the
> > modelform.
>
> > On 8 nov, 19:17, cootetom  wrote:
>
> > > If you want to associate an error to a specific field in a model form
> > > then you need to populate self._errors with the error you find. Have a
> > > read about this on the Django docs to see how it is done.
>
> > >http://docs.djangoproject.com/en/1.1/ref/forms/validation/#ref-forms-...
>
> > > The last example shows how to associate a error with a specific field
> > > in a form class.
>
> > > On Nov 8, 8:40 pm, refreegrata  wrote:
>
> > > > Hello list. I want to use the clean method in a model.
> > > > --
> > > > class myModel(models.Model):
> > > >     fields 
>
> > > >     def clean(self):
> > > >             raise ValidationError('The Error.')
> > > > ---
>
> > > > Thats works fine. My question  is, how can I associate this error to
> > > > the field in the modelform?. With this method the form validation can
> > > > be controlled, but I can't pick the error dynamically to show at the
> > > > user.
>
> > > > Thanks for read.
>
>

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



Admin Inlines only show up after a browser refresh

2010-11-09 Thread vjimw
We have an odd situation where, for one of our model forms, the
inlines do not regularly show up on the form page, but if you refresh
the browser window, they will appear with the correct data.

Has anyone else run into this before? I am not really sure how to
debug it since it is not consistent. However, i do know that it is not
tied to a specific browser (I can make it happen in Safari, Chrome or
Firefox) and sometimes they do show up. When I have django toolbar
debug turned on in my development environment it does not show any
indication of the inlines when they don't show up so it tells me
something is happening further upstream.

Here is the admin code to build the ModelAdmin form in this instance:

class LegalObjectActionInline(admin.TabularInline):
model = LegalObjectAction


class LegalObjectAdmin(admin.ModelAdmin):

save_on_top = True
form = LegalObjectForm
list_display = ( 'offer_code', 'legal_site', 'created_by',
'copyright_or_trademark', 'store', 'current_state', 'overdue' )
list_filter = ( 'created', 'modified', 'copyright_or_trademark',
'legal_site',)
list_select_related = True
search_fields = ['legal_site', 'store', 'copyright_or_trademark']
fields = ('offer_code', 'store', 'copyright_or_trademark',
'page_found', 'legal_site', )

inlines = [LegalObjectActionInline,]

Thanks!

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



Trouble accessing development server

2010-11-09 Thread Engywook
I have django running on HostMonster, and am having a problem reaching
the Development server.

According to a reply to somebody having a similar issue, what I'm
supposed to do is this:

python manage.py runserver www.yourhost.yourdomain.com:8000.

Tried that, with several different port numbers. When I try to connect
on my browser, nothing happens.

Something I'm missing here?

-- 
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: Trouble accessing development server

2010-11-09 Thread Shawn Milochik
Instead of the domain try 0.0.0.0 or your public IP address.

python manage.py runserver 0.0.0.0:8000

or

python manage.py runserver 82.165.105.204:8000 #this is just a sample
IP address for Host Monster


Shawn

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



Re: question about involve "vncserver" command with django

2010-11-09 Thread Bill
Hi Jirka,

Thank you for your quickly reply.

>   this is technically impossible, two programs cannot listen on the
> same TCP port (on one interface). It's very likely that it was Django
> webserver listening there.

You are right, sorry for that stupid question, and I check it again, I
find the Xvnc process used the 8000 port and killed the Django
webserver
=
[r...@sun]# lsof -P -i -n |grep Xvnc
Xvnc  3691   bill0u  IPv4  14835   TCP *:6001 (LISTEN)
Xvnc  3691   bill3u  IPv4  14371   TCP *:8000 (LISTEN)
Xvnc  3691   bill4u  IPv4  14745   TCP 10.1.1.1:8000-
>10.1.1.144:52607 (ESTABLISHED)
Xvnc  3691   bill6u  IPv4  14838   TCP *:5901 (LISTEN)
Xvnc  3691   bill7u  IPv4  14839   TCP *:5801 (LISTEN)

==
Development server is running at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
Error: That port is already in use.

>
>   Overall, starting VNC from a web application seems like a bad idea
> in principle as the request-response cycle is not well suited for this
> (as well as other reasons). Can you describe what are you trying to
> achieve and why?

What am I doing is want to simplify using vnc.
I'm a Linux administrator. As you know, if users want to use vnc they
must login the server with ssh to start vnc server first.
Then get the port or id number, then use vncviewer or http link to
access the vncserver.
I just want them to access the http link let django start the
vncserver and use it. they don't need to install any ssh client.


Thanks in advance.

Bill

-- 
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: question about involve "vncserver" command with django

2010-11-09 Thread CLIFFORD ILKAY

On 11/09/2010 05:50 PM, Bill wrote:

What am I doing is want to simplify using vnc.
I'm a Linux administrator. As you know, if users want to use vnc they
must login the server with ssh to start vnc server first.
Then get the port or id number, then use vncviewer or http link to
access the vncserver.
I just want them to access the http link let django start the
vncserver and use it. they don't need to install any ssh client.


I've found FreeNX with the NoMachine client to be a much better 
alternative. You can distribute ready-made profiles to your users and 
their setup will be next to nothing. It's faster and more secure than 
VNC, too.

--
Regards,

Clifford Ilkay
Dinamis
1419-3266 Yonge St.
Toronto, ON
Canada  M4N 3P6


+1 416-410-3326

--
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: Create a ContentType object on model save

2010-11-09 Thread Kenny Meyer
Kenny Meyer (knny.m...@gmail.com) wrote:
> Hello,
> 
> I have two models, 1) FlashCard and 2) Practice, and I have a generic relation
> in the FlashCard model pointing to the Practice model using the contenttypes
> framework.
> The Practice model tracks information like how many times something was
> practiced, and calculates an `easy factor'.
> Each time I save a FlashCard I want at the same time to create Practice
> object for the flashcard, automatically.
> 
> 
> class Practice(models.Model):
> content_type = models.ForeignKey(ContentType)
> object_id = models.PositiveIntegerField()
> item = generic.GenericForeignKey('content_type', 'object_id')
> 
> user = models.ForeignKey(User)
> 
> 
> class FlashCard(models.Model):
> """
> A basic Flashcard.
> 
> Has a front and a back view.
> """
> front = models.TextField(
> max_length = 255,
> verbose_name = "Front")
> back = models.TextField(
> max_length = 255,
> verbose_name = "Back")
> user = models.ForeignKey(User)
> practice = generic.GenericRelation(Practice)
> 
> 
> I read the contenttypes documentation, and as far as I understand to create a
> related Practice object for a flashcard instance I should do the following:
> 
> >>> user = User.objects.get(username="kenny")
> # Create a sample flashcard
> >>> flashcard = ("bla", "bla", user)
> # ...and create a Practice object for it
> >>> new_practice = Practice(item=flashcard)
> # then I try to save it, but that fails with a large backtrace
> >>> new_practice.save()
> [snip]
> 
> Here the actual backtrace: http://dpaste.com/hold/272617/

Ok, this is my error. Creating a flashcard was actually this:

   FlashCard(front="front side", back="back side", user)

then it worked, and so I could also create a Practice object.

> Well, but this is not the reason I opened this thread. Still I want to create
> Practice object for my FlashCard object.
> 
> I started a research on Google, but I really haven't found anything really
> helping me to do that.
> 
> Can you guys give me a helping hand on this with your expertise, please?
> 
> Additional information about my environment:
>   - Django 1.2.3
>   - PostgreSQL 8.4.5
> 
> Cheers,
> Kenny
> 
> -- 
> - Kenny Meyer 
> To understand recursion, we must first understand recursion.
> --

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



Help!!: creating a combined form linked via foreign key??

2010-11-09 Thread sosurim kim
This message isn't going through for some reason...

-- Forwarded message --
From: sosurim kim 
Date: Mon, Nov 8, 2010 at 1:55 PM
Subject: Re: creating a combined form linked via foreign key??
To: django-users@googlegroups.com


Oops, I meant to say addressbook, not phonebook... sorry.

# models.py
class Myuser(User):
  bio = models.TextField()

class AddressBook(models.Model):
  userid = models.ForeignKey(CustomUser, blank=True, null=True)
  address = models.CharField(max_length=50)
  city = models.CharField(max_length=50)
  zip = models.CharField(max_length=20)
  state = models.CharField(max_length=50)

# admin.py
from django.contrib import admin
from models import *

class AddressBookInline(admin.TabularInline):
  model = AddressBook
  can_delete = True

class CustomUserAdmin(admin.ModelAdmin):
  inlines = ( AddressBookInline )
  fk_name = 'userid'

admin.site.register(Myuser, CustomUserAdmin)

>
>
> So when I go into django admin, I see all the fields for Myuser, but
> AddressBook fields appear three times. It doesn't matter whether I subclass
> StackedInline or TabularInline, I get the AddressBook three times.
>
> Is there a better way to create a combo form that contains two (or more)
> models linked with a foreign key (or manytomany, onetomany, etc.)??
>
> Thanks,
>
> S
>

-- 
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: question about involve "vncserver" command with django

2010-11-09 Thread Bill
Hi Clifford,

Thank you, sounds like good,  I will try FreeNX later.
but you know, I already wrote the python code, it works except I use
it on Django.


BTW, we are very close, I'm at Eglinton subwaystation.
Best regards,
Bill

> I've found FreeNX with the NoMachine client to be a much better
> alternative. You can distribute ready-made profiles to your users and
> their setup will be next to nothing. It's faster and more secure than
> VNC, too.
> --
> Regards,
>
> Clifford Ilkay
> Dinamis
> 1419-3266 Yonge St.
> Toronto, ON
> Canada  M4N 3P6
>
> 
> +1 416-410-3326

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



Making MODEL.objects.raw() query with LIKE input%

2010-11-09 Thread xvga
Hi All,

 my question is linked to this thread, so I post here

I need to run sql query with LIKE and % in the end - I have tried %%
and :
CLASSNAME.objects.raw("select * from table where full_name like %s%%
", [user_input])
this is what I get as sql:
select * from table where full_name LIKE 'user_input'%

I would like to use raw() method as it nicely maps data to model.

Is there a way to append % to parameter so that LIKE works as
startswith?
or can I somehow securely escape input to use with format string?

PS. I need object.raw(). I learned about djangoish way - but
unfortunately it is not enough - I need raw sql

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



Please help me figure out this UnicodeEncodeError

2010-11-09 Thread Eric Chamberlain
Hi, can anyone tell me how to work around this UnicodeEncodeError?

>>> from hashlib import md5
>>> full_jid = u'e...@example.com/Eric\u2019s iPhone 3GS'
>>> hash = md5(full_jid)
Traceback (most recent call last):
  File "", line 1, in 
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 
21: ordinal not in range(128)

--
Eric Chamberlain




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



Can't move down then up the directory tree for inserting of html files

2010-11-09 Thread Brian
Thanks for the help.
I'm using Python 2.5 and Django Template 1.1

I can't seem to move down then up the directory tree for inserting of
html files using  {% include file %} statement

Sample dir structure:
root/
root/lib/
root/lib/Top.html
root/main/
root/main/include/HomeLogo.html
root/main/HOME.html

Inside HOME.html I can use {% include "/include/HomeLogo.html" %} =
Works just fine to any where up the tree.
BUT
I can not find a way to include the top.html file in home.html.
I tried {% include "/lib/Top.html" %}, {% include "lib/Top.html" %} ,
{% include "../lib/Top.html" %}, {% include "./lib/Top.html" %}
can not find a way to insert the html in.
Thanks again.

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