我用Django表单创建了一个表单。我在HTML页面上实现。一切正常,但我的图像未上传到数据库。另外,我在数据库上设置了默认图像,但未与默认图像链接
我正在尝试查找问题。我尝试了print(request.FILES)
,它返回了<MultiValueDict: {}>
,我知道我上传的图片未正确上传到数据库中。虽然已提交表单,但当我尝试从产品模型查询时。它将出现错误ValueError at /
The 'image' attribute has no file associated with it.
这是我的回溯
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 2.2.5
Python Version: 3.7.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'users.apps.UsersConfig',
'product.apps.ProductConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template error:
In template /home/asad/PycharmProjects/eShop/templates/base.html, error at line 8
The 'image' attribute has no file associated with it.
1 : {% load staticfiles %}
2 : <!DOCTYPE html>
3 : <html lang="en">
4 : <head>
5 : <meta charset="UTF-8">
6 : <title>{% block title %}{% endblock %}</title>
7 : <!-- Latest compiled and minified CSS -->
8 : <link rel="stylesheet" href="https://maxcd n.bootstrapcdn.com/ bootstrap/4.3.1/css/bootstrap.min.css">
9 :
10 :
11 : </head>
12 : <body>
13 :
14 : <div class="container">
15 : <div class="row">
16 : <div class="col-md-4">
17 : <a href="{% url 'product:home' %}">Logo</a>
18 : </div>
Traceback:
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/template/base.py" in _resolve_lookup
829. current = current[bit]
During handling of the above exception ('ImageFieldFile' object is not subscriptable), another exception occurred:
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/asad/PycharmProjects/eShop/product/views.py" in product_list
12. return render(request, 'product/home.html', context)
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/shortcuts.py" in render
36. content = loader.render_to_string(template_name, context, request, using=using)
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/template/loader.py" in render_to_string
62. return template.render(context, request)
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/template/backends/django.py" in render
61. return self.template.render(context)
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/template/base.py" in render
171. return self._render(context)
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/template/base.py" in _render
163. return self.nodelist.render(context)
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/template/base.py" in render
937. bit = node.render_annotated(context)
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/template/base.py" in render_annotated
904. return self.render(context)
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/template/loader_tags.py" in render
150. return compiled_parent._render(context)
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/template/base.py" in _render
163. return self.nodelist.render(context)
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/template/base.py" in render
937. bit = node.render_annotated(context)
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/template/base.py" in render_annotated
904. return self.render(context)
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/template/loader_tags.py" in render
62. result = block.nodelist.render(context)
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/template/base.py" in render
937. bit = node.render_annotated(context)
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/template/base.py" in render_annotated
904. return self.render(context)
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/template/defaulttags.py" in render
209. nodelist.append(node.render_annotated(context))
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/template/base.py" in render_annotated
904. return self.render(context)
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/template/base.py" in render
987. output = self.filter_expression.resolve(context)
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/template/base.py" in resolve
671. obj = self.var.resolve(context)
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/template/base.py" in resolve
796. value = self._resolve_lookup(context)
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/template/base.py" in _resolve_lookup
837. current = getattr(current, bit)
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/db/models/fields/files.py" in url
61. self._require_file()
File "/home/asad/PycharmProjects/eShop/venv/lib/python3.7/site-packages/django/db/models/fields/files.py" in _require_file
38. raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
Exception Type: ValueError at /
Exception Value: The 'image' attribute has no file associated with it.
models.py文件
class Product(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
name = models.CharField(max_length=200)
image = models.ImageField(upload_to='product/', default='product.png')
quantity = models.IntegerField(default=0)
purchase_price = models.FloatField()
sales_price = models.FloatField()
product_type = models.CharField(max_length=2, choices=PRODUCT_TYPE)
measure = models.ForeignKey(Measure, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
forms.py文件
class ProductForms(forms.Form):
name = forms.CharField(max_length=200, widget=forms.TextInput(
attrs={
'class': 'form-control',
}
))
image = forms.ImageField(required=False, widget=forms.FileInput(
attrs={
'class': 'form-control',
}
))
quantity = forms.IntegerField(widget=forms.NumberInput(attrs={'class': 'form-control'}))
purchase_price = forms.FloatField(widget=forms.NumberInput(attrs={'class': 'form-control'}))
sales_price = forms.FloatField(widget=forms.NumberInput(attrs={'class': 'form-control'}))
product_type = forms.ChoiceField(choices=PRODUCT_TYPE, widget=forms.Select(attrs={'class': 'form-control'}))
measure = forms.ModelChoiceField(queryset=Measure.objects.all(), widget=forms.Select(attrs={'class': 'form-control'}))
views.py文件
def create_product(request):
if request.method == 'POST':
form = ProductForms(request.POST, request.FILES or None)
print(request.FILES)
if form.is_valid():
data = form.cleaned_data
product = Product.objects.create(
user=request.user,
name=data['name'],
image=data['image'],
quantity=data['quantity'],
purchase_price=data['purchase_price'],
sales_price=data['sales_price'],
product_type=data['product_type'],
measure=data['measure'],
)
product.save()
messages.success(request, 'Form is successfully submitted')
else:
messages.warning(request, 'Form is not submitted')
form = ProductForms()
return render(request, 'product/product_create.html', {'form': form,})
<form action="" class="was-validated" method="post">
{% csrf_token %}
{% for field in form.visible_fields %}
<div class="form-group">
{{ field.label_tag }}
{{ field }}
</div>
{% endfor %}
<button type="submit" class="btn btn-success">Submit Product</button>
</form>
答案 0 :(得分:1)
在enctype = "multipart/form-data"
标记中添加form
,就像这样
<form action="" class="was-validated" method="post" enctype = "multipart/form-data">
答案 1 :(得分:1)
您应该在enctype="multipart/form-data"
标签上使用form
。
您的模板如下:
<form action="" class="was-validated" method="post" enctype="multipart/form-data">
HTML表单提供了三种编码方法:
当表单包含任何multipart/form-data
元素时,我们将使用<input type="file">
。
To know more..