python - Django 表单打印无错误且无效

标签 python django django-forms django-views

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

models.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

forms.py

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

views.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
        [...]

template.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>

最佳答案

问题出在你的字形模型上的词法外键。

由于您使用的是 django Modelforms,如果您没有将 blank=Truenull=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']

关于python - Django 表单打印无错误且无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50794276/

相关文章:

python - 我如何在管理页面中关闭 django 的复数表示法

python - conda 更新 anaconda 的问题

python - 用Python调用gcc编译多个文件

python - 在 forloop 上向 datetime.time() django 添加 +1 小时

python - 你能优化这段代码吗? ( Django , python )

django admin fieldsets - 添加相关模型的字段

python - 没有 HTML 转义的 Django 表单值

python - captureWarnings 设置为 True 不捕获警告

python - 保留子文件夹结构的递归ffmpeg脚本

django - 将文件从一个模型复制到另一个模型