【发布时间】:2021-01-28 22:08:35
【问题描述】:
我想通过BoundField.as_widget() 将HTML 属性传递给方法中的attrs。 Django doc 说
BoundField.as_widget(widget=None, attrs=None, only_initial=False)¶
通过渲染传递的小部件来渲染字段,添加作为 attrs 传递的任何 HTML 属性。如果未指定小部件,则将使用该字段的默认小部件。
所以我尝试像这样传递属性:BoundField.as_widget(attrs={'class': 'container'}),但没有成功。
forms.py
class HiddenForm(forms.Form):
testfield = forms.CharField(max_length=100, widget=forms.HiddenInput())
class BlahForm(forms.ModelForm):
class Meta:
model = Blah
views.py。模型Blah 是与模型A 的一对一字段关系。
def myview(request, arg):
a = get_object_or_404(A, somefieldname=arg)
initial = {'blah': a}
form = BlahForm(request.POST or None, initial=initial) # ModelForm from Model Blah
value = a.pk
hidden_input = HiddenForm(request.POST or None)
hidden_input['testfield'].as_widget(attrs={'value': value }) # This is the reason I want to pass attrs with as_widget. I want to pass value to the hidden input form, so that the hidden form can handle submitting disabled form value, which I did on purpose to keep user from changing the value.
if form.is_valid():
form.save()
return redirect('somewhere', someparameter=arg)
context = {
'form': form,
'value': value,
'hidden_input': hidden_input
}
return render(request, 'someapp/sometemplate.html', context)
一些模板.html
<form method="post">
{% csrf_token %}
{{ form|crispy }}
{# disabled input data not submitted, so submit it with hidden data #}
<input type="hidden" name="blah" value="{{ value }}"> <!-- hard coded part, which I try to avoid -->
{{ hidden_input }} <!-- What I want -->
<button class="btn btn-primary" type="submit">저장</button>
</form>
以及我在下面看到的开发者控制台页面:
<input type="hidden" name="blah" value="2632"> <!-- hard coded -->
<input type="hidden" name="blah" id="id_blah"> <!-- rendered with {{ hidden_input }}-->
据我了解,Django 不鼓励将设计直接放在模板中,而是将业务模型放在视图和其他.py 文件中,所以我希望我的模板看起来更优雅。
谁能告诉我我错过了什么,或者做错了什么?
提前感谢您的建议。
【问题讨论】: