models.py
from PIL import Image
class Award_list(models.Model):
award_id=models.AutoField(primary_key=True)
award_name=models.CharField(max_length=50,blank=False)
award_image = models.ImageField(upload_to='award_pics',default='award.jpg')
def __str__(self):
return f'{self.award_name} award'
def save(self,*args,**kwargs):
super().save(*args,**kwargs)
img = Image.open(self.award_image.path)
if img.height > 300 or img.width > 300:
output_size = (300, 300)
img.thumbnail(output_size)
img.save(self.award_image.path)
class Meta:
verbose_name_plural = 'Award'
forms.py
from django import forms
from movies_list.models import Award_list
class Create_Award_list_form(forms.ModelForm):
class Meta:
model=Award_list
fields=['award_name','award_image']
views.py
from .models import Award_list
from .forms import Create_Award_list_form
def Award_list_create(request):
form=Create_Award_list_form(request.POST,request.FILES or None)
if form.is_valid():
# print(request.POST['award_name'])
form.save()
else:
print(form.errors)
context={
"hell":'sanjeet',
"form":form
}
return render(request,'movies_list/award_list_create.html',context)
urls.py
urlpatterns = [
path('movies/awards/new/',Award_list_create,name="award-list-create"),
]
award_list_create.html
{% extends "users/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Blog Post</legend>
{{form.as_p}}
{{hell}}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Submit</button>
</div>
</form>
</div>
{% endblock content %}
这所有代码行都可以在管理页面上正常工作,并选择将图像保存到MEDIA_URL / awards_pics文件中,但是当我创建基于模型的表单时,即使选择了.html表单中的图像,它也会选择默认选项。
答案 0 :(得分:0)
<form method="POST" enctype="multipart/form-data">
在表单标签中添加enctype="multipart/form-data"
,以便您可以从html上传图像