[英]Django ModelForm in template
我有一个问题。我是 Django 新手,学习了 3 周。 我需要为大学的一个项目开发一个带有 optin 的 Cookie 弹出窗口。 我的问题是。 我在 Django python 中开发它。 在后端,我有收集所有 Cookie 信息并将其传递到 Cookie 模型的服务。 所以现在我有了 Cookie 模型,需要将它作为视图中的上下文传递。 目前我看到服务在浏览器中收集的所有 Cookie。 但是我需要验证 typ 是 Essential 还是 Marketing 并在模板的折叠中将其分开。 我怎么能做到这一点? 我的想法是用这一行在模板中验证它
{% if cookie.typ == 'Essenziell' %}
如果 typ 是 Essenziell,我会在折叠中显示这一点。
查看.py
def optin(request):
if request.method == 'POST':
form = CookieForm(request.POST)
if form.is_valid():
return HttpResponseRedirect
else:
form = CookieForm
cookie_list = Cookie.objects.all()
context_dict = {'form': form, 'cookie_list': cookie_list}
template = 'cookies/cookie.html'
return render(request, template,
context_dict
)
这是模板的一部分
<button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#Marketing" aria-expanded="false" aria-controls="Marketing">
Marketing
</button>
<div class="collapse" id="Essenziell">
<div class="card card-body">
{% for cookie in cookie_list %}
{% if cookie.typ == 'Essenziell' %}
<p>{{ cookie.cookie }}</p>
<p>{{ cookie.provider }}</p>
<p>{{ cookie.description }}</p>
<p>{{ cookie.typ }}</p>
<p>{{ cookie.runTime }}</p>
{% endif %}
{% endfor %}
</div>
</div>
模型.py
class Cookie(models.Model):
"""
:cookie: The defined name of the Cookie
:provider: Who will set this Cookie ex. Google, Matomo, Shopprovider
:description: The description of the seted Cookie
:cookieRuntime: The lifetime of the Cookie
:typ: Type of the Cookie
"""
cookie = models.CharField(max_length=50)
provider = models.CharField(max_length=100)
description = models.CharField(max_length=300)
typ = models.ForeignKey(Typ)
表单.py
class CookieForm(forms.ModelForm):
class Meta:
model = Cookie
field = {
'cookie',
'provider',
'description',
'typ',
}
您应该使用Serializers
进行验证和其他内容。 读这个:
https://www.django-rest-framework.org/topics/html-and-forms/
为什么我需要序列化程序? 我不知道我应该使用它的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.