将空白对象传递给自实例模型

Pass a blank object to a self instance model

我想在通过 Django 中的 from 输入时为模型设置 blank/null 的父类别。是否可以通过空白表单传递空值?

这是我的 models.py

from django.db import models

class Category(models.Model):
    category_name = models.CharField(max_length=300)
    category_code = models.CharField(max_length=100)
    category_parent = models.ForeignKey('self', blank=True, null=True)
    category_image = models.ImageField(upload_to='category')

    def __str__(self):
        return self.category_name

和forms.py

from django import forms
from backend.models import Category


class CategoryForm(forms.ModelForm):
    category_parent = forms.ModelChoiceField(
        queryset=Category.objects.all(), empty_label='None')
    category_image = forms.ImageField()

    class Meta:
        model = Category
        fields = ('category_name', 'category_code',)

如果没有 selected,我想为父 select 字段设置一个空值。或者,如果我在类别中输入第一个值,当没有父项时它应该指向 null。

我希望我做对了,但我猜即使 empty_label 设置为 None,您仍然会看到所选列表中的第一个类别。

当您覆盖 ModelForm 字段时,就像您现在对 category_parent 所做的那样,您将丢失模型中 blank=True 的自动连接的 required=False 表单对应者。

尝试将 required=False 添加到表单字段,如下所示:

category_parent = forms.ModelChoiceField(queryset=Category.objects.all(), empty_label='None', required=False)