1

I have some problem with adding image to my project.

Settings:

MEDIA_ROOT = '/static/uploads'
MEDIA_URL = '/uploads/'

Model:

class UserLogo(models.Model):
upload_path = '/static/uploads'
logo = models.ImageField(verbose_name="Logo", upload_to=upload_path)

Form:

class LogoUploadForm(forms.Form):
logo = forms.ImageField(label='Logo')

View:

def add_user_logo(request):
if request.method == 'POST':
    form = LogoUploadForm(request.POST, request.FILES)
    if form.is_valid():
        user_logo = UserLogo
        user_logo.logo = form.cleaned_data['logo']
        user_logo.save()
return HttpResponseRedirect('/user_settings/show_user/')

Template:

<form id="logo_upload_form" role="form" action="/user_settings/add_user_logo/" method="post" enctype="multipart/form-data" >
   {% csrf_token %}
   {% if logo_upload_form %}
       <table class="table table-striped">
       <tbody>
       <tr>
       <td>{{logo_upload_form.logo.label</td>
       <td{{logo_upload_form.logo}}</td>
       </tr>
       </tbody>
       </table>
   {% endif %}
    </form>

I choose img and submit but img dont want to add. I cant find img file in my 'upload_to' place.

Patryk
  • 23
  • 1
  • 4
  • There are examples with file upload it is similar to uploading images. I recommend looking at it and understand it carefully. (http://stackoverflow.com/questions/5871730/need-a-minimal-django-file-upload-example) – Javier Clavero Jan 17 '16 at 16:53

2 Answers2

0

Django appends the upload_to path to MEDIA_ROOT to find the location to save your file. According to your code it will be /static/uploads/static/upload/

Also the MEDIA_ROOT should be an absolute path like /home/username/path/ (in unix) or C:/path/ (in windows).

Tony Joseph
  • 1,802
  • 2
  • 14
  • 17
  • I changed to full path but nothing change – Patryk Jan 17 '16 at 17:46
  • Ok works, i can add images, problem was in view ( forgot change one line). But now i have problem because i want to make thumbnail. I can`t use 'user_logo.thumbnail((128, 128))' because ''UserLogo' object has no attribute 'thumbnail'' @Tony Joseph – Patryk Jan 17 '16 at 18:05
  • Because user_logo does not have an attribute named 'thumbnail'. user_logo is a model object. If you are trying to generate thumbnails from images, consider using pillow. [Pillow](https://pillow.readthedocs.org/en/3.1.x/) – Tony Joseph Jan 17 '16 at 18:28
0

modify your MEDIA_ROOT as follows:

MEDIA_ROOT = os.path.join(BASE_DIR, 'static/uploads/')

open urls.py file:

Add the following:

...
from django.conf import settings
...

urlpatterns = patterns('',
   ...    
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Serjik
  • 10,543
  • 8
  • 61
  • 70