开发者

moving a function out of my method in django

Hay i have a method in my view which uploads an image, the image is then saved to a db object. I want to remove this from my view and either put it in my model or a seperate file.

filename_bits = request.FILES['image'].name.split(".")
filename_bits.reverse()
extension = filename_bits[0]

# create filename and open a destination
filename = '_'+force_unicode(random.randint(0,10000000))+'_'+force_unicode(random.randint(0,10000000))+'.开发者_运维问答'+force_unicode(extension)
path = 'assests/uploads/'+filename
destination = open(path, 'wb+')

# write to that destination
for chunk in request.FILES['image'].chunks():
    destination.write(chunk)
destination.close()

picture = CarPicture(car=car, path=path, filename=filename)
picture.save()

as you can see it uploads a file (after creating random filenames) then create a carPicture object and saves it.

Any ideas? Could this be done in the model by overwriting the save method?


You should consider using an ImageField in your model. For example in models.py you would have:

def get_random_filename(car_picture, filename):
    extension = filename.split('.')[-1]
    return u'_%s_%s.%s' % (random.randint(0,10000000),
                           random.randint(0,10000000),
                           extension)

class CarPicture(models.Model):
    title = models.TextField()
    image = models.ImageField(upload_to=get_random_filename)

And in your views you would just have:

picture = CarPicture(title="Some Title", image=request.FILES['image'])
picture.save()

This will store the image to disk, using the randomly generated filename, and set the image field in the database to the path of the image. You can also get the url for the image with:

picture.image.url()

so a template might have:

<img src="{{picture.image.url}}" title="{{picture.image.title}}"/>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜