Hi i created a generic form to insert data everything is working fine but image could not upload in template form but when i upload image in admin it works perfectly and image display on template page.
Here is my code:
views.py:
class ArticleCreate(CreateView):
model = article
fields = ['title', 'cat', 'img', 'disc', 'tags']
models.py:
class article(models.Model):
title = models.CharField(max_length=250)
disc = models.TextField(verbose_name="Discription")
cat = models.ForeignKey(category, verbose_name="Category")
tags = models.ManyToManyField(Tag, blank=True)
img = models.ImageField(blank=True, verbose_name='Image')
Settings.py:
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Template page:
{% for list in data %}
{{ list.title }}
{% if list.img %}
{{ list.img.url }}
{% endif %}
{% endfor %}
What can i do to upload image with generic form ?
In template add enctype="multipart/form-data" in <form> it will allow image to get uploaded from template also.
template form:
<form method="post" enctype="multipart/form-data" >
One more general error is we can forget the request.FILES attribute in views: e.g.
form = someModelForm(request.POST,request.FILES)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With