我有一个模型表单,其中有一个名称字段,当我提交表单时,即使填写了名称字段,我也会得到“字段必填”的消息。
models.py
from django.db import models
from user.models import User
class Image(models.Model):
"""This model holds information for user uploaded images"""
# Status of the image
class Status(models.TextChoices):
PUBLIC = 'public', 'Public'
PRIVATE = 'private', 'Private'
name = models.CharField(max_length=150)
image = models.ImageField(upload_to='images/')
status = models.CharField(
max_length=7, choices=Status.choices, default=Status.PUBLIC)
upload_date = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='photos')
def __str__(self) -> str:
return self.name
class Meta:
indexes = [
models.Index(fields=['name'], name='name_idx'),
models.Index(fields=['user'], name='user_idx')
]
ordering = ['-upload_date']
字符串
forms.py
from django import forms
from .models import Image
from utils.forms.widgets import text_input, select_input, image_input
class ImageUploadForm(forms.ModelForm):
"""Use this form to upload images"""
class Meta:
model = Image
fields = [
'name',
'image',
'status',
]
widgets = {
'name': text_input,
'image': image_input,
'status': select_input,
}
型
The Error that I'm getting
这是在尝试提交表单后选择了一个图像并填写了名字。
我试过使用clean_name方法来查看返回图像的名称是否会修复它,但无济于事。
2条答案
按热度按时间kkih6yb81#
检查
request.POST
数据是否包含字段name
。另外,直接尝试在clean
方法中添加数据一次。wrrgggsh2#
我想明白了,在模板中我忘记将
enctype='mulitpart-form-data
添加到表单中。谢谢你的帮忙。原来错误是在image field
而不是name field
上。