python - 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>
解决方案
问题是您的字形模型上的词位外键。
由于您使用的是 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']
推荐阅读
- c++ - 关于模板的使用
- java - 如何查找哪个用户正在更新项目并在 sonarqube 上进行项目分析报告
- javascript - 使用 javascript 对 Json 对象进行 Json 模式验证
- sql - SQL 查询 - 超过阈值的聚合总和
- bash - 如何从我的 git repos 中彻底删除所有远程分支
- java - 当一个方法具有泛型类型参数而另一个具有非泛型参数时,java如何确定将调用哪个重载方法?
- mysql - MySQL:使用每个人的父母获取所有行
- c++ - C++:我可以在另一个向量中定义向量吗?
- jquery - 使用数据表显示数据时,我可以获得 ajax 成功响应吗?
- node.js - nodejs-slackbot - 下载的文件已损坏