[Answered ]-Save an image field from django template to a table

2👍

Are you having a specific problem with the way django explains how to do this? https://docs.djangoproject.com/en/dev/topics/http/file-uploads/

First of all, you need to assign enctype="multipart/form-data" inside the <form> tag.

If you must do this manually instead of leveraging the power of Django’s forms framework, you need to manually assign the file / field data to your model.

def myview(request):
    image = request.FILES['imageName_1'] 
    tour = Tour()
    tour.Name = request.POST.get('name')
    tour.capacity = request.POST.get('capacity')
    tour.image.save(image.name, image)
    tour.save()

I’d recommend checking out django’s ModelForms as a view / template combo that does this and much more (error checking / redisplaying) can be written in one minute.

class MyForm(forms.ModelForm):
   class Meta:
       model = Tour

def myview(self):     
    if request.method == 'POST':
        form = MyForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
    else:
        form = MyForm()
    return render(request, 'my_template.html', {'form': form})


<form method='POST' enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" />
</form>    

Leave a comment