【发布时间】:2019-04-29 19:32:57
【问题描述】:
我有一个这样的模型:
models.py
from django.db import models
class Foo(models.Model):
text = models.TextField()
此模型的示例是:
Foo.objects.create(text="My first text [[@shorttext_1@]] random text.")
Foo.objects.create(text="Select something from below [[@multipleselect_1@]]. text.")
Foo.objects.create(text="A different form [[@shorttext_1@]] and another"
"form [[@shorttext_2@]] random texts.")
Foo.objects.create(text="Mixed form [[@shorttext_1@]] and another"
"form [[@multipleselect_1@]] random text.")
值[[@shorttext_1@]]、[[@multipleselect_1@]] 表示要放置在下面模板中的表单的位置和类型。 [[@ @]] 是随机选择的降价样式占位符。
forms.py
from django import forms
class ShortTextForm(forms.Form): # [[@shorttext_1@]] form
short_text = forms.CharField(max_length=300)
class MultipleSelectionForm(forms.Form): # [[@multipleselect_1@]] form
selection = forms.ChoiceField(
choices=[('A', 'A text'), ('B', 'B text')],
widget=forms.RadioSelect())
views.py
from django.shortcuts import render
def text_view(request):
if request.method == 'POST':
# get the info for each form
else:
foo = Foo.objects.order_by('?').first()
return render(
request=request,
template_name='templates/index.html',
context={'text': foo.text})
templates/index.html
{% extends "base.html" %}
{% block body %}
{{ text }}
{% endblock %}
是否可以在模板中显示foo.text 并呈现所需的表单?
目前,我的Foo 类中有一个type 变量来指定表单的类型。而且我的视图只能呈现一种只能放在文本末尾的所需类型的表单。我想只使用一个模板在文本的任何位置呈现多个表单。
编辑:
举一个我想要实现的输出示例:
Foo.objects.create(text="The age of the person is [[@shorttext_1@]] and "
"another attribute is [[@shorttext_2@]]. "
"Additionally select one:<br>[[@multipleselect_1@]]")
此对象应在模板中呈现,输出如下所示:
【问题讨论】:
标签: python django django-forms django-templates