我正在尝试将5个图像字段添加到我的表中,3个是必需的,2个不是..当我尝试仅上传3个图像时出现错误,但是当我上传5个图像时一切都很好。这是我的文件:
创建主表的models.py :
class Item(models.Model):
# custom validators
alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.')
# fields
dress_name = models.ForeignKey(Name, on_delete=models.DO_NOTHING, blank=False, verbose_name='نوع الفستان',)
dress_rate = models.ForeignKey(Rate, on_delete=models.DO_NOTHING, blank=False, verbose_name='تصنيف الفستان',)
dress_size = models.ForeignKey(Size, on_delete=models.DO_NOTHING, verbose_name='مقاس الفستان', blank=False)
dress_color = models.CharField(max_length=50, verbose_name='لون الفستان', blank=False)
dress_description = models.TextField(max_length=800, verbose_name=' وصف إضافى للفستان', blank=False, default='وصف الفستان')
dress_image1 = models.ImageField(upload_to='documents/%Y/%m/%d', null=False, blank=False, verbose_name='الصورة الأساسية للفستان',
help_text='لا يمكنك تركها فارغة',default=1)
dress_image2 = models.ImageField(upload_to='documents/%Y/%m/%d', null=False, blank=False, verbose_name='صورة إضافية ',default=1)
dress_image3 = models.ImageField(upload_to='documents/%Y/%m/%d', null=False, blank=False, verbose_name='صورة إضافة ',default=1)
dress_image4 = models.ImageField(upload_to='documents/%Y/%m/%d', null=True, blank=True, verbose_name='صورة إضافة ',default=1)
dress_image5 = models.ImageField(upload_to='documents/%Y/%m/%d', null=True, blank=True, verbose_name='صورة إضافة ',default=1)
dress_action = models.ForeignKey(Action, on_delete=models.DO_NOTHING, verbose_name='الفستان معروض لل ',
help_text='للبيع او للإيجار ', blank=False)
dress_price = models.IntegerField(default=1, verbose_name='السعر', blank=False)
dress_mobile = models.CharField(max_length=20, validators=[alphanumeric], verbose_name='رقم الهاتف ', blank=False)
created_by = models.CharField(max_length=250,)
created_username = models.CharField(max_length=250, default='unknown')
created_at = models.DateTimeField(auto_now=True)
dress_active = models.BooleanField(default=False)
dress_special = models.BooleanField(default=False)
dress_town = models.ForeignKey(Town, on_delete=models.DO_NOTHING, verbose_name='المحافظة', blank=False)
views.py 在表格中添加项目的视图:
def dress_add(request):
current_user = request.user
if request.method == "POST":
add_dress_form = AddDressForm(request.POST, request.FILES)
if add_dress_form.is_valid():
model_instance = add_dress_form.save(commit=False)
model_instance.created_by = current_user.name
model_instance.created_username = current_user.email
model_instance.save()
return redirect('dress_confirm')
else:
add_dress_form = AddDressForm()
context = {
'add_dress_form': add_dress_form,
}
return render(request, 'fostania_web_app/dress_add.html', context)
forms.py 创建了添加项目的位置:
class AddDressForm(ModelForm):
class Meta:
model = Item
exclude = ['created_by', 'created_at', 'dress_active', 'dress_special', 'created_username']
HTML :
<form action="" method="post" name="AddDressForm" align="right" enctype="multipart/form-data">
{% csrf_token %}
{{ add_dress_form.non_field_errors }}
{% for field in add_dress_form %}
<span style="color: red; ">{{ field.errors }}</span>
<div class="row">
<div class="col">
{{ field.label_tag }} {% if field.field.required %}<span style="color: red; font-size: xx-small; ">مطلوب</span> {% endif %}
</div>
<div class="col" align="right">
{{ field }}
</div>
</div>
<br>
以下是错误的 Traceback :我看到了:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/dress/add
Django Version: 2.0.5
Python Version: 3.6.5
Installed Applications:
['social_django',
'storages',
'django_filters',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'fostania_web_app.apps.FostaniaWebAppConfig']
Installed Middleware:
('whitenoise.middleware.WhiteNoiseMiddleware',
'social_django.middleware.SocialAuthExceptionMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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')
Traceback:
File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner
35. response = get_response(request)
File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
21. return view_func(request, *args, **kwargs)
File "F:\django\fostania\fostania_web_app\views.py" in dress_add
67. model_instance.save()
File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py" in save
729. force_update=force_update, update_fields=update_fields)
File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py" in save_base
759. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py" in _save_table
842. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py" in _do_insert
880. using=using, raw=raw)
File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py" in _insert
1125. return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
1282. for sql, params in self.as_sql():
File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py" in as_sql
1235. for obj in self.query.objs
File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py" in <listcomp>
1235. for obj in self.query.objs
File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py" in <listcomp>
1234. [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py" in pre_save_val
1184. return field.pre_save(obj, add=True)
File "C:\Users\LiTo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\fields\files.py" in pre_save
285. if file and not file._committed:
Exception Type: AttributeError at /dress/add
Exception Value: 'int' object has no attribute '_committed'
答案 0 :(得分:1)
您无法将ImageField
设置为默认值1
,这是一个整数。您需要将其更改为合理的值,例如'image/default.jpg'
。
您可能需要考虑使用django-imagekit
来帮助管理django模型的图像。