无法弄清楚如何在Django表单提交中摆脱字段必填消息

0yg35tkg  于 2023-08-08  发布在  Go
关注(0)|答案(2)|浏览(117)

我有一个模型表单,其中有一个名称字段,当我提交表单时,即使填写了名称字段,我也会得到“字段必填”的消息。

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方法来查看返回图像的名称是否会修复它,但无济于事。

kkih6yb8

kkih6yb81#

检查request.POST数据是否包含字段name。另外,直接尝试在clean方法中添加数据一次。

wrrgggsh

wrrgggsh2#

我想明白了,在模板中我忘记将enctype='mulitpart-form-data添加到表单中。谢谢你的帮忙。原来错误是在image field而不是name field上。

相关问题