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" >
一个更普遍的错误是我们可以忘记视图中的 request.FILES 属性:例如
form = someModelForm(request.POST,request.FILES)
试试这个:
<img src="{% if list.img %}{{ list.img.url }}">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.