Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image upload field works in django admin but not working in template

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 ?

like image 619
habib Avatar asked Feb 01 '26 12:02

habib


2 Answers

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" >
like image 60
Astik Anand Avatar answered Feb 04 '26 01:02

Astik Anand


One more general error is we can forget the request.FILES attribute in views: e.g.

form = someModelForm(request.POST,request.FILES)
like image 27
MbeforeL Avatar answered Feb 04 '26 02:02

MbeforeL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!