【问题标题】:Displaying different Django forms at different template locations在不同的模板位置显示不同的 Django 表单
【发布时间】: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


    【解决方案1】:

    只需传递 foo:

    context={'foo': foo}
    

    不是 foo.text,而是在模板中使用 if...else 语句来确定您想要做什么。

    这也可以让您访问type 变量:

    {% if foo.type == some_type %}
        {{ form }}
        {% endif %}
    

    【讨论】:

    • 这种方法不允许我在指定位置放置多个表格。使用这种方法我怎么可能在下面的文本"Mixed form [[@shorttext_1@]] and another form [[@multipleselect_1@]] random text."中放置两种不同的形式?
    猜你喜欢
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 2020-06-14
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多