Re: issues with file upload

2012-08-21 Thread
finished
sorry, I clone the new source( for review) but use an old source on python 
environment



在 2012年8月21日星期二UTC+8下午6时36分46秒,软刀写道:
>
>
> I now  work with mongoengine, mongoForm
> and set this in setting.py
> DEFAULT_FILE_STORAGE = 'mongoengine.django.storage.GridFSStorage'
>
> I need to upload a picture, and I wrote a form like this:
>
> from django.forms import ImageField
>
>   from mongoforms import MongoForm
>   from documents import UserProfile
>   
>   class ProfileForm(MongoForm):
>   photo = ImageField()
>   class Meta:
>   document = UserProfile
>   exclude = ('user', 'photo')
>
> but I get a Invalid Image Error when I submit a picture( how ever, it's ok 
> when I use PIL.Image.open(photo).verify() )
> I review the code, and found the exception was raise on 
> django.forms.fields.ImageField.to_python method
> code snippet for to_python method:
>   def to_python(self, data):
>
>if hasattr(data, 'temporary_file_path'):
>   file = data.temporary_file_path()
>
>try:
> Image.open(file).verify()
> except ImportError:
> raise
> except Exception: # Python Imaging Library doesn't recognize it as 
> an image
> raise ValidationError(self.error_messages['invalid_image'])
> ...
>
>well, I don't know well to set temporary_file_path and how to 
> storage it with mongoengine.django.storage.GridFSStorage
>
>
> # this was snippet for class ImageField
> def to_python(self, data):
> """
> Checks that the file-upload field data contains a valid image 
> (GIF, JPG,
> PNG, possibly others -- whatever the Python Imaging Library 
> supports).
> """
> f = super(ImageField, self).to_python(data)
> if f is None:
> return None
>
> # Try to import PIL in either of the two ways it can end up 
> installed.
> try:
> from PIL import Image
> except ImportError:
> import Image
>
> # We need to get a file object for PIL. We might have a path or we 
> might
> # have to read the data into memory.
> if hasattr(data, 'temporary_file_path'):
> file = data.temporary_file_path()
> else:
> if hasattr(data, 'read'):
> file = StringIO(data.read())
> else:
> file = StringIO(data['content'])
>
> try:
> # load() could spot a truncated JPEG, but it loads the entire
> # image in memory, which is a DoS vector. See #3848 and #18520.
> # verify() must be called immediately after the constructor.
> Image.open(file).verify()
> except ImportError:
> # Under PyPy, it is possible to import PIL. However, the 
> underlying
> # _imaging C module isn't available, so an ImportError will be
> # raised. Catch and re-raise.
> raise
> except Exception: # Python Imaging Library doesn't recognize it as 
> an image
> raise ValidationError(self.error_messages['invalid_image'])
> if hasattr(f, 'seek') and callable(f.seek):
> f.seek(0)
> return f
>
>  
>
>  
> this was exception stack
>
> Environment:
>
>
> Request Method: POST
> Request URL: http://localhost:8000/accounts/profile/
>
> Django Version: 1.4
> Python Version: 2.7.3
> Installed Applications:
> ['django.contrib.auth',
>  'django.contrib.contenttypes',
>  'django.contrib.sessions',
>  'django.contrib.messages',
>  'django.contrib.staticfiles',
>  'registration',
>  'bussiness',
>  'accounts',
>  'debug_toolbar']
> Installed Middleware:
> ['django.middleware.common.CommonMiddleware',
>  'django.contrib.sessions.middleware.SessionMiddleware',
>  'django.middleware.csrf.CsrfViewMiddleware',
>  'django.contrib.auth.middleware.AuthenticationMiddleware',
>  'django.contrib.messages.middleware.MessageMiddleware',
>  'debug_toolbar.middleware.DebugToolbarMiddleware']
>
>
> Traceback:
> File 
> "/home/yan/env/haoyoubang/local/lib/python2.7/site-packages/django/core/handlers/base.py"
>  
> in get_response
>   111.

issues with file upload

2012-08-21 Thread

I now  work with mongoengine, mongoForm
and set this in setting.py
DEFAULT_FILE_STORAGE = 'mongoengine.django.storage.GridFSStorage'

I need to upload a picture, and I wrote a form like this:

from django.forms import ImageField

  from mongoforms import MongoForm
  from documents import UserProfile
  
  class ProfileForm(MongoForm):
  photo = ImageField()
  class Meta:
  document = UserProfile
  exclude = ('user', 'photo')

but I get a Invalid Image Error when I submit a picture( how ever, it's ok 
when I use PIL.Image.open(photo).verify() )
I review the code, and found the exception was raise on 
django.forms.fields.ImageField.to_python method
code snippet for to_python method:
  def to_python(self, data):
   
   if hasattr(data, 'temporary_file_path'):
  file = data.temporary_file_path()
   
   try:
Image.open(file).verify()
except ImportError:
raise
except Exception: # Python Imaging Library doesn't recognize it as 
an image
raise ValidationError(self.error_messages['invalid_image'])
...

   well, I don't know well to set temporary_file_path and how to 
storage it with mongoengine.django.storage.GridFSStorage


# this was snippet for class ImageField
def to_python(self, data):
"""
Checks that the file-upload field data contains a valid image (GIF, 
JPG,
PNG, possibly others -- whatever the Python Imaging Library 
supports).
"""
f = super(ImageField, self).to_python(data)
if f is None:
return None

# Try to import PIL in either of the two ways it can end up 
installed.
try:
from PIL import Image
except ImportError:
import Image

# We need to get a file object for PIL. We might have a path or we 
might
# have to read the data into memory.
if hasattr(data, 'temporary_file_path'):
file = data.temporary_file_path()
else:
if hasattr(data, 'read'):
file = StringIO(data.read())
else:
file = StringIO(data['content'])

try:
# load() could spot a truncated JPEG, but it loads the entire
# image in memory, which is a DoS vector. See #3848 and #18520.
# verify() must be called immediately after the constructor.
Image.open(file).verify()
except ImportError:
# Under PyPy, it is possible to import PIL. However, the 
underlying
# _imaging C module isn't available, so an ImportError will be
# raised. Catch and re-raise.
raise
except Exception: # Python Imaging Library doesn't recognize it as 
an image
raise ValidationError(self.error_messages['invalid_image'])
if hasattr(f, 'seek') and callable(f.seek):
f.seek(0)
return f

 

 
this was exception stack

Environment:


Request Method: POST
Request URL: http://localhost:8000/accounts/profile/

Django Version: 1.4
Python Version: 2.7.3
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'registration',
 'bussiness',
 'accounts',
 'debug_toolbar']
Installed Middleware:
['django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware']


Traceback:
File 
"/home/yan/env/haoyoubang/local/lib/python2.7/site-packages/django/core/handlers/base.py"
 
in get_response
  111. response = callback(request, *callback_args, 
**callback_kwargs)
File 
"/home/yan/env/haoyoubang/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py"
 
in _wrapped_view
  20. return view_func(request, *args, **kwargs)
File "/home/yan/git/haoyoubang/accounts/views.py" in profile
  31. processFile(request.FILES['photo'])
File "/home/yan/git/haoyoubang/accounts/views.py" in processFile
  21. s = f.clean(photo)
File 
"/home/yan/env/haoyoubang/local/lib/python2.7/site-packages/django/forms/fields.py"
 
in clean
  535. return super(FileField, self).clean(data)
File 
"/home/yan/env/haoyoubang/local/lib/python2.7/site-packages/django/forms/fields.py"
 
in clean
  153. value = self.to_python(value)
File 
"/home/yan/env/haoyoubang/local/lib/python2.7/site-packages/django/forms/fields.py"
 
in to_python
  593. raise 
ValidationError(self.error_messages['invalid_image'])

Exception Type: ValidationError at /accounts/profile/
Exception Value: 
[u'\u8bf7\u4e0a\u4f20\u4e00\u5f20\u6709\u6548\u7684\u56fe\u

Re: Django, nginx, Passenger

2012-03-03 Thread
is  proxy_send_timeout too small ?
I newer

2012/3/3 赵帅 

> I suggest you do a pressure test on the url that have triggered the
> problem to see whether it will show up again.If yes, to see the system
> status such as the number of sockets being used and the number of
> connections from nginx to fastcgi service in the status of waiting to be
> accepted.
>
>
> 2012/3/3 Daniele Procida 
>
>> We're having a devil of a time with our new server, which went live
>> yesterday after two months of testing.
>>
>> Every so often, nginx will display a 502 gateway error page, and
>> something like this will appear in the logs:
>>
>> 2012/03/02 18:05:38 [error] 29743#0: *1479 upstream prematurely closed
>> connection while reading response header from upstream, client:
>> nn.nn.nn.nn, server: nn.nn.nn.nn, request: "GET /some/path/ HTTP/1.1",
>> upstream: "passenger:unix:/passenger_helper_server:", host: "example.com"
>>
>> This only occurs on some pages, but once it has happened on a page, it
>> seems to keep happening.
>>
>> It doesn't happen straight away - the server can run happily for some
>> time before the errors start occurring.
>>
>> The pages that trigger the error don't seem to be particularly hard work
>> for the server. However, the same pages can be expected to trigger it,
>> while some never do.
>>
>> Merely restarting nginx doesn't get rid of the errors - they come back
>> again.
>>
>> As soon as DEBUG = True is applied in settings and nginx restarted, the
>> errors disappear.
>>
>> Some things that seem to have improved matters:
>>
>> * increasing somaxconn to 1024
>> * turning off cacheing
>>
>> In fact after turning off cacheing it was some hours before the errors
>> returned.
>>
>> We are running nginx, with a passenger_wsgi.py file setting up the path
>> and pointing to the settings.py file.
>>
>> I'd appeciate any tips on what the problem might be, or how to go about
>> isolating it.
>>
>> Obviously an error that occurs under heavy load is not unusual, though I
>> don't think the load is particualrly heavy (and this server has taken over
>> from one rather less powerful that has been doing the same job for two
>> years).
>>
>> What is puzzling is the error that occurs only on particular apparently
>> arbitrary pages, and then persists, even after the load conditions (we were
>> using ApacheBench to test) have disappeared.
>>
>> Daniele
>>
>> --
>> 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.
>



-- 
as I learning english, any help about english grammar is welcome

-- 
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: Please help me with django form 2.

2012-01-11 Thread
as I unflod your code
I think may be you should create a Form-class like this:
class RegisterForm(ModelForm):
class Meta:
model = Register


and in your view should be:
@csrf_exempt
def welcome(request):
if request.method=='POST':
form=RegisterForm(request.POST)
new_user=form.save()
return HttpResponseRedirect('/logpage/')
else:
form=RegisterForm()
return render_to_response('mainpage.html', {'form':form})


-- 
as I learning english, any help about english grammar is welcome

-- 
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: sorting of foreign key elements

2011-12-30 Thread
may be attribute  ModelAdmin.ordering can work for you , it was in
docs/ref/contrib/admin/index.txt

attribute:: ModelAdmin.ordering
Set ordering to spcify how lists of objects should be ordered in the
Django admin views. This should be a list or tuple in the same format as a
models's django.db.models.Options.ordering parameter
If this isn't provided, the Django admin will use the models's default
ordering

-- 
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: question about django-admin.py

2011-12-25 Thread
I don't know why u get this
I run it well

maybe u can reinstall it

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



how to change form field in method is_valid()

2011-12-24 Thread
I have two model
class Friend(models.Model):
   me = models.ForeignKey(User)
   friend = models.ForeignKey(User)
   remark = models.CharField(max_length=15)

  def __unicode__(self):
return self.remark

class Message(models.Model):
   from_user = models.ForeignKey(User)
   to_user = models.ForeignKey(User)
   ...

I make a form for Message
class MessageForm(ModelForm):
class Meta:
  model = Message

but when i display the form in html, i hope i display to_user's choice
list just by 'remark' ( in Friend model)

and I override MessageForm 's __init__ method like follow:
class MessageForm(ModelForm):
class Meta:
  model = Message
def __init__(self,*args,**kwargs):
  super(MessageForm, self).__init__(*args,**kwargs)
  init = kwargs.get('initial')
  if init:
  if 'from_user' in init:
   me = init['from_user']
   self.fields['to_user'].queryset =
Friend.objects.filter(me=me)

well when  the data post, the form.is_valid() raise error :  Cannot
assign "": "Message.to_user" must be a "User" instance.

so i want to change self.fields['to_user'] 's value  before is_valid()
is call like:
def is_valid(self):
 # do something  to fix the problem
 super(MessageForm, self).is_valid()

but I don't know how to fix it
any suggestion is welcome
thks
 I don't know how to do it ,

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