首页 > 解决方案 > Django 表单不打印错误且无效

问题描述

为了在我的网站中创建表单,我创建了一些与我的字段相对应的模型。然后我从它们、一些视图和模板中创建了 ModelForms。我的问题是我从来没有首先看到我的表单错误,其次,这个特定字段的表单总是无效,即使其中有一个属性。你能解释一下我做错了什么吗?

模型.py

class Grapheme(models.Model):
    lexeme = models.ForeignKey(Lexeme, on_delete=models.CASCADE)

    value = models.CharField(max_length=256)

    class Meta:
        verbose_name = "grapheme"
        ordering = ["value"]

    def __str__(self):
        return self.value

表格.py

class GraphemeForm(forms.ModelForm):
    class Meta:
        model = Grapheme
        fields = ['value']

视图.py

@login_required
def lexeme_edit_view(request, lexicon_id):
    [...]

    if request.method == 'POST':
        lexeme_form = LexemeForm(request.POST)
        grapheme_form = GraphemeForm(request.POST)
        [...]

        if grapheme_form.is_valid(): # This line fails
        [...]

模板.html

{% if grapheme_form.non_field_errors %}
    <div class="alert alert-danger" role="alert">
        {% for error in grapheme_form.non_field_errors %}
            {{ error }}
        {% endfor %}
    </div>
{% endif %}

[...]

<div class="form-group row">
    <label for="graphemeInput" class="control-label col-lg-2">{{ grapheme_form.value.label }}</label>
    <div class="col-lg-6">
        {% if grapheme_form.is_bound %}
            {% if grapheme_form.value.errors %}
                {% for error in grapheme_form.value.errors %}
                    <div class="invalid-feedback">
                        {{ error }}
                    </div>
                {% endfor %}
            {% endif %}

            {% if grapheme_form.value.help_text %}
                <small class="form-text text-muted">{{ grapheme_form.value.help_text }}</small>
            {% endif %}
        {% endif %}

        {% render_field grapheme_form.value type="text" class+="form-control" id="graphemeInput" %}
    </div>
</div>

标签: pythondjangodjango-formsdjango-views

解决方案


问题是您的字形模型上的词位外键。

由于您使用的是 django Modelforms,如果您不设置blank=True,null=True到外键关系,它会自动成为必填字段。

在您的表单中,您声明您不想显示词位外键选择,因此它不会出现在您的表单上:

fields = ['value']

这就是为什么您在表单上收到必填字段缺失错误的原因。

您有两种可能的解决方案:
解决方案 1
将 blank=True, null=True 添加到您的外键关系中:

lexeme = models.ForeignKey(Lexeme, blank=True,null=True on_delete=models.CASCADE)


解决方案 2: 在初始化表单时设置词位值:

class GraphemeForm(Form):
def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    lexeme = Lexeme.objects.get(id=1)
    self.fields['lexeme'].initial = lexeme

class Meta:
    model = Grapheme
    fields = ['value']

推荐阅读