Reputation: 245
I was trying out ImageField in the models, But Image upload do not work when I try to upload from the forms. But it works when I upload it from the admin page.
Any way to debug is also helpful
My model-
class Inventory(models.Model):
"""docstring for Inventory"""
name = models.CharField(max_length=100,default='Something')
image = models.ImageField(null=True, blank=True)
description = models.CharField(max_length=100, default='Describe Something')
price = models.IntegerField( default=0)
My Form-
class InventoryForm(forms.ModelForm):
class Meta:
model = Inventory
fields = ['name','description','price','image']
widgets = {
'name' : forms.TextInput(attrs={"placeholder":"Name", "onfocus":"this.value = '';","onblur":"if (this.value=='') this.value = this.defaultValue","required":""}),
'description' : forms.TextInput(attrs={"placeholder":"Email", "onfocus":"this.value = '';","onblur":"if (this.value=='') this.value = this.defaultValue","required":""}),
'price' : forms.NumberInput(attrs={"placeholder":"Price","onfocus":"this.value = '';","onblur":"if (this.value=='') this.value = this.defaultValue","required":""}),
}
Settings -
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media/")
template -
<form action="" method="post" enctype="multipart/form-data"> {% csrf_token %}
{{form}}
<input type="submit" value="Send">
</form>
url -
from django.contrib import admin
from django.urls import path, include, re_path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('',include('inventory.urls')),
path('<int:id>',include('inventory.urls')),
path('admin/', admin.site.urls),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My Views-
def index(request):
form = InventoryForm(request.POST or None)
if form.is_valid():
form.save()
form = InventoryForm()
else:
form = InventoryForm()
inventory = Inventory.objects.all()
context = {'form' : form, 'all_inventory' : inventory}
return render(request, 'inventory/index.html',context)
Regards, Deepak Dash
Upvotes: 0
Views: 45
Reputation: 1928
In your views.py. Change:
form = InventoryForm(request.POST or None)
to
form = InventoryForm(request.POST, request.FILES or None)
Because, Files in django post request are in request.FILES dictionary. You have to send that to forms as well.
Upvotes: 1
Reputation: 59
How about adding upload_to in models in image field and add default image also this will come in handy later on or not your choice:
models.py
class Inventory(models.Model):
"""docstring for Inventory"""
name = models.CharField(max_length=100,default='Something')
image = models.ImageField(upload_to='/your_file_name/',default='default.png')
description = models.CharField(max_length=100, default='Describe Something')
price = models.IntegerField(default=0)
Upvotes: 0