如何将django ModelForm字段显示为uneditable [英] how to show a django ModelForm field as uneditable

查看:168
本文介绍了如何将django ModelForm字段显示为uneditable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

django ModelForm ,我想给用户一个在博客中编辑条目的能力。 BlogEntry 有一个日期,postedTime,标题和内容。我想向用户显示一个editform,显示所有这些字段,但只有标题和内容可编辑 date和postedTime应显示为不可编辑的

taking my initial lessons with django ModelForm ,I wanted to give the user ,ability to edit an entry in a blog.The BlogEntry has a date,postedTime, title and content.I want to show the user an editform which shows all these fields,but with only title and content as editable. The date and postedTime should be shown as uneditable.

class BlogEntry(models.Model):
   title = models.CharField(unique=True,max_length=50)
   description = models.TextField(blank=True)
   date = models.DateField(default=datetime.date.today)
   postedTime = models.TimeField(null=True)

...

对于添加条目,我以正常的方式使用ModelForm。

For adding an entry ,I use a ModelForm in the normal way..

class BlogEntryAddForm(ModelForm):
    class Meta:
        model = BlogEntry
...

但是如何创建编辑表单?我希望它可以显示日期,postTime作为不可编辑的(但仍然在表单上显示),并让用户编辑标题和描述

But how do I create the edit form?I want it to show the date,postedTime as uneditable (but still show them on the form) and let the user edit the title and description.

如果我使用,在类Meta中排除 for date和postedTime,这将导致它们不会出现在表单上。所以,我如何将它们显示为不可编辑?

if I use,exclude in class Meta for date and postedTime,that will cause them not to appear on the form.So,how can I show them as uneditable?

class BlogEntryEditForm(ModelForm):
    class Meta:
        model = BlogEntry
        ...?...


推荐答案

在表单对象中,将该字段的属性声明为 readonly

In the form object, declare the attribute of the field as readonly:

form.fields['field'].widget.attrs['readonly'] = True

这篇关于如何将django ModelForm字段显示为uneditable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆