我在models.py中使用下面的类来限制文件上传到某些文件扩展名。
class ExtensionValidator(RegexValidator):
def __init__(self, extensions, message=None):
if not hasattr(extensions, '__iter__'):
extensions = [extensions]
regex = '\.(%s)$' % '|'.join(extensions)
if message is None:
message = 'File type not supported. Accepted types are: %s.' % ', '.join(extensions)
super(ExtensionValidator, self).__init__(regex, message)
def __call__(self, value):
super(ExtensionValidator, self).__call__(value.name)
以下是调用它的模型形式:
class Product(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=100)
description = models.CharField(max_length=300)
price = models.DecimalField(max_digits=10, decimal_places=2)
url = models.CharField(max_length=200, blank=True)
product_type = models.CharField(max_length=15, choices=product_types, default='choose')
image = models.ImageField(upload_to='product_images', blank=True, null=True)
image_url = models.CharField(max_length=200, blank=True)
product_file = models.FileField(upload_to='product_files', validators=[ExtensionValidator(['jpg', 'jpeg', 'png', 'zip'])], blank=True, null=True)
likes = models.IntegerField(default=0)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('index', kwargs={})
我已经过测试,但功能正常,但是当用户提交表单时,错误消息不会显示。对于我正在使用include - form.html的所有表单:
{% load widget_tweaks %}
{% for hidden_field in form.hidden_fields %}
{{ hidden_field }}
{% endfor %}
{% if form.non_field_errors %}
<div class="alert alert-danger" role="alert">
{% for error in form.non_field_errors %}
{{ error }}
{% endfor %}
</div>
{% endif %}
{% for field in form.visible_fields %}
<div class="form-group">
{{ field.label_tag }}
{% if form.is_bound %}
{% if field.errors %}
{% render_field field class="form-control is-invalid" %}
{% for error in field.errors %}
<div class="invalid-feedback">
{{ error }}
</div>
{% endfor %}
{% else %}
{% render_field field class="form-control is-valid" %}
{% endif %}
{% else %}
{% render_field field class="form-control" %}
{% endif %}
{% if field.help_text %}
<small class="form-text text-muted">{{ field.help_text }}</small>
{% endif %}
</div>
{% endfor %}
我猜我需要在form.html中添加一些内容来显示错误消息,但不确定是什么或在哪里。我还在研究这个,但任何指导都会感激不尽。
修改:
根据要求,这是表单类:
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = ['name', 'description', 'url', 'product_type', 'price', 'image', 'image_url', 'product_file']
labels = {
'name': 'Product Name',
'url': 'Product URL',
'product_type': 'Product Type',
'description': 'Product Description',
'image': 'Product Image',
'image_url': 'Product Image URL',
'price': 'Product Price',
'product_file': 'Product File',
}
widgets = {
'description': Textarea(attrs={'rows': 5}),
}
编辑2 :
...这是HTML:
<div class="product card card-default">
<div class="card-header">
<h3 class="card-title mb-4">Add Product</h3>
</div>
<div class="card-body">
<form enctype="multipart/form-data" action="post_url/" method="post" >
{% csrf_token %}
{% include 'includes/form.html' with form=form %}
<input class="btn btn-product" type="submit" value="Upload" />
</form>
</div>
</div>