I am trying to get my app to validate the image upload field in my app's template and save any new image that is uploaded. Everything works fine on the admin side of things but when I make an image change on the front, it doesn't get saved.
我正在尝试让我的应用验证应用模板中的图片上传字段,并保存上传的任何新图片。在管理方面,一切都运行良好,但是当我在前面进行图像更改时,它不会被保存。
Here is my model
这是我的模特
def imageupload(instance, filename):
return os.path.join('static/petition-photos/', filename)
# Create your models here.
class Petition(models.Model):
title = models.CharField(max_length= 90, default="Enter petition title here")
created_on = models.DateTimeField(auto_now_add=True)
image = models.ImageField(null=False, upload_to=imageupload)
video = models.CharField(max_length=600, default="Enter an external video link")
petition = models.TextField(null=False, default="Type your petition here")
created_by = models.ForeignKey(User)
Here is my view class:
这是我的观点类:
class NewPetitionView(generic.edit.CreateView):
model = Petition
template_name = 'petition/petition_form.html'
fields= ['title','petition', 'image', 'video']
success_url = '/dashboard/'
def form_valid(self, form):
form.instance.created_by = self.request.user
return super(NewPetitionView, self).form_valid(form)
And this is my form template:
这是我的表单模板:
{% include 'layout/header.html' %}
{% block content %}
<form action="" method="post">
{{form.as_p}}
<button type="submit">Submit</button>
{% csrf_token %}
</form>
{% endblock %}
When I upload an image to a new post or try to edit the image field of one of the posted items, I get a "This field is required" notification.
当我将图像上传到新帖子或尝试编辑其中一个已发布项目的图像字段时,我会收到“此字段是必填项”通知。
What am I doing wrong?
我究竟做错了什么?
1 个解决方案
#1
0
You need in your <form>
add enctype="multipart/form-data"
in order to let file upload work.
您需要在
<form action="" method="post" enctype="multipart/form-data">
#1
0
You need in your <form>
add enctype="multipart/form-data"
in order to let file upload work.
您需要在
<form action="" method="post" enctype="multipart/form-data">