Created
April 19, 2012 12:34
-
-
Save Natim/2420717 to your computer and use it in GitHub Desktop.
Django UploadFile
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def upload_to_valid_name(prefix_dir): | |
''' Create the right function ''' | |
def get_valid_name(instance, name): | |
from django.template.defaultfilters import slugify | |
from django.utils.encoding import smart_str | |
import os | |
n = name.rsplit('.',1)[0] | |
ext = name.rsplit('.',1)[1] | |
n = smart_str(slugify(n).replace('-', '_')) | |
return os.path.join(prefix_dir, '%s.%s' % (n, ext)) | |
return get_valid_name | |
class Firm(models.Model): | |
name = models.CharField(_(u'name'), max_length=50, | |
help_text=_(u"Champ obligatoire.")) | |
image = models.ImageField(_(u'logo'), | |
upload_to=upload_to_valid_name('uploads/logo'), | |
null=True, blank=True)) | |
@login_required | |
def firm(request, firm_id): | |
firm = get_object_or_404(Firm, pk=firm_id) | |
if request.method == 'POST': | |
form = FirmForm(request.POST, request.FILES, instance=firm) | |
if form.is_valid(): | |
form.save() | |
return HttpResponseRedirect('/') | |
else: | |
form = FirmForm(instance=firm) | |
return render_to_response('firm/form.html', | |
{'form': form, | |
'firm': firm}, | |
context_instance=RequestContext(request)) | |
<form enctype="multipart/form-data" method="post" action="/"> | |
{{ form.as_p }} | |
<p class="submit"><input type="submit" /></p> | |
</form> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment