【发布时间】:2021-05-20 10:02:02
【问题描述】:
如何将数据传递给 django 模板中的表单字段? ,例如我的项目中有以下代码:
<td class="col-3">
{{form.number|as_crispy_field}}
</td>
我可以使用
<td class="col-3">
{{form.number}} = 10
</td>
在 django 模板中?
【问题讨论】:
如何将数据传递给 django 模板中的表单字段? ,例如我的项目中有以下代码:
<td class="col-3">
{{form.number|as_crispy_field}}
</td>
我可以使用
<td class="col-3">
{{form.number}} = 10
</td>
在 django 模板中?
【问题讨论】:
@mosi -
<td class="col-3">
{{form.number}} = 10
</td>
不,您不能使用它。如果您打算将数据从视图传递到模板,请执行以下操作 假设你有一个像这样的表格 forms.py
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=30)
email = forms.EmailField(max_length=254)
views.py
def home(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
pass # your logic here
else:
form = ContactForm()
return render(request, 'home.html', {'form': form})
模板.html
<form method="post" novalidate>
{% csrf_token %}
{{ form.name }}
{{form.email}}
<button type="submit">Submit</button>
</form>
或 简单的
<form method="post" novalidate>
{% csrf_token %}
{{ form }}
<button type="submit">Submit</button>
</form>
现在,如果您想在模板中为表单设置初始值 假设您有以下内容
class ContactForm(forms.Form):
name = forms.CharField(max_length=30,initial='test')
然后在你的模板中你做这样的事情
<form method="post" novalidate>
{% csrf_token %}
<input type="text" name="name" id="name" value="{{ form.name.value }}">
<button type="submit">Submit</button>
</form>
现在,在 UpdateView 的情况下,根据假设产品 ID 从数据库中动态提取数据。以下只是一个例子
class ProductForm(forms.ModelForm):
class Meta:
model = Product
exclude = (
"created_by",
"slug",
)
class ProductUpdateView(UpdateView):
# specify the model you want to use
model = Product
form_class = ProductForm
template_name = "catalog/product/update_product.html"
product_update.html
<form method="post" enctype="multipart/form-data">
<div class="card-body">
{% csrf_token %}
{{ form.as_p}}
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
Or
<form method="post" enctype="multipart/form-data">
<div class="card-body">
{% csrf_token %}
<input type="text" name="name" id="name" value="{{ form.name.value }}">
<input type="text" name="description" id="description" value="{{ form.description.value }}">
.........
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
【讨论】: