Ryan Oh
Ryan Oh

Reputation: 657

Why can't I upload images to Django app running on Ubuntu server?

I'm trying to upload images to my Django application running on Ubuntu server. I have everything required, but somehow when I post it, I don't see any images saved. I've checked the Admin, but the field is empty.

The thing is, I DON'T GET ANY ERROR MESSAGES. The whole process works fine, except that the field remains empty. Let me show you my code first.
models.py

class NewEvent(models.Model):
    objects = models.Manager()
    img1 = models.ImageField(null=True, blank=True, upload_to="everyday_img")
    ...

forms.py

class NewEventForm(forms.ModelForm):
    ...
    img1 = forms.ImageField(required=False)
...

views.py

def inputNew(request):
    form = NewEventForm(initial={'authuser':request.user})
    
    if request.method == 'POST':
        form = NewEventForm(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.authuser = request.user
            instance.img1 = request.FILES.get('img1')
            instance.save()
...

And the template for uploading image.

<form method="post" class="form-group" enctype="multipart/form-data">{% csrf_token %}
    <div class="row">
        <div class="col">
            <div class="everyday-img-input">{{form.img1|as_crispy_field}}</div>
        </div>
    </div>
</form>

I've also tried the chmod command, and taken care of the permission. There's nothing wrong there. What do you think is the problem? Thank you very much in advance. :)

+++ I have everything set fine in my settings.py as well. That's why I'm stuck :(

MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('main.urls')),
...
    path('newevent/', include('newevent.urls')),

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Upvotes: 0

Views: 95

Answers (1)

Pruthvi Barot
Pruthvi Barot

Reputation: 2018

you should do like this into your view function

if request.method == 'POST':
    form = NewEventForm(request.POST, request.FILES)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.authuser = request.user
        instance.save()

Upvotes: 1

Related Questions