Reputation: 907
Not able to upload image in Django Model.
I have installed Pillow , added MEDIA_URL and MEDIA_ROOT to my settings, added
static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
to my urls.py .
forms.py:
class PostForm(forms.ModelForm) :
class Meta :
model = Post
fields = ['name', 'image', 'description', 'age', 'cost', 'address', 'seller', 'phone', ]
post_edit.html:
{% extends 'blog/base.html' %}
{% block content %}
<h2>New post</h2>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% endblock %}
models.py:
image = models.ImageField(upload_to='images/', null=True, blank=True)
urls.py:
path('edit/', views.post_edit, name='post_edit'),
views.py:
@login_required
def post_edit(request, pk) :
post = get_object_or_404(Post, pk=pk)
if request.method == "POST" :
form = PostForm(data=request.POST, files=request.FILES, instance=post)
if form.is_valid() :
post = form.save(commit=False)
post.save()
return redirect('post_detail', pk=post.pk)
else :
form = PostForm(instance=post)
return render(request, 'blog/post_edit.html', {'form' : form})
If I add an image to a new object , the image is not uploaded to media/images/
.
With my modest level of understanding ,I'm not able to find the mistake . Can anyone help me please?
Upvotes: 1
Views: 1091
Reputation: 47374
You need to add enctype="multipart/form-data"
form attribute to your template:
<form method="POST" class="post-form" enctype="multipart/form-data">{% csrf_token %}
From the doc:
Note that request.FILES will only contain data if the request method was POST and the that posted the request has the attribute enctype="multipart/form-data"
Upvotes: 1