【问题标题】:Django UpdateView formsDjango UpdateView 表单
【发布时间】:2017-01-02 16:03:53
【问题描述】:

我有一个看起来像..的表单类。

#forms.py

class ExampleForm(forms.Form):
    color = forms.CharField(max_length=25)
    description = forms.CharField(widget=forms.Textarea, max_lenght=2500)

我的观点是这样的..

#views.py



class EditExample(UpdateView):
model = Example
fields = ['color', 'description']
template_name = 'example.html'

def get_success_url(self):
    pass

模板:

#example.html
{% for field in form %}
    {% if field.errors %}
            <div class="control-group error">
                <label class="control-label">{{ field.label }}</label>
                <div class="controls">{{ field }}
                    <span class="help-inline">
                        {% for error in  field.errors %}{{ error }}{% endfor %}
                    </span>
                </div>
            </div>
            {% else %}
                <div class="control-group">
                <label class="control-label">{{ field.label }}</label>
                <div class="controls">{{ field }}
                    {% if field.help_text %}
                        <p class="help-inline"><small>{{ field.help_text }}</small></p>
                    {% endif %}
                </div>
     {% endif %}
{% endfor %}

渲染模板时,所有字段都会显示并正确填充,但“描述”不会显示在 Textarea 中,而是显示在普通字段中。我假设这是因为 UpdateView 使用“model = something”而不是“form = something”。

我试过了..

#views.py
class EditExample(UpdateView):
    model = Example
    form_class = Exampleform
    template_name = 'example.html'

    def get_success_url(self):
        pass

但我收到一个 Django 错误,提示“init() 有一个意外的关键字参数 'instance'。

有什么方法可以使用 Updateview 成功地让描述在 Textarea 中呈现?如果没有,我将如何实现?

谢谢!

【问题讨论】:

    标签: django django-forms django-views


    【解决方案1】:

    您的表单需要继承自 forms.ModelForm,而不是基 Form 类。

    【讨论】:

    • 我创建了一个 ModelForm 并使用 'form_class=' 将其插入到视图中。一切都很好,但我仍然没有让描述显示在文本区域小部件中。尝试以正常大小的形式编辑数百个字长的描述是一件很痛苦的事情!还有什么想法吗?谢谢
    猜你喜欢
    • 2018-05-10
    • 2014-02-01
    • 2021-12-15
    • 1970-01-01
    • 2021-05-29
    • 2016-10-23
    • 2017-12-03
    • 1970-01-01
    • 2021-09-22
    相关资源
    最近更新 更多