简体   繁体   English

django1.6 ModelForm使字段只读

[英]django1.6 ModelForm Make fields readonly

I have a django model 我有一个Django模型

models.py models.py

class Item(models.Model):
        author = models.ForeignKey(User)
        name = models.CharField('Brief summary of job', max_length=200)
        created = models.DateTimeField('Created', auto_now=True,auto_now_add=True)
        description = models.TextField('Description of job')

I would like to update the description field in a modelform using UpdateView. 我想使用UpdateView更新模型表单中的描述字段。 I would like to see the other fields (author,name etc) but want editing and POST disabled 我想查看其他字段(作者,姓名等),但要禁用编辑和POST

forms.py forms.py

from django.forms import ModelForm
from todo.models import Item

class EditForm(ModelForm):
    class Meta:
        model = Item
        fields = ['author', 'job_for', 'name', 'description']

urls.py urls.py

urlpatterns = patterns('',
              # eg /todo/
              url(r'^$', views.IndexView.as_view(), name='index'),
              #eg /todo/5
              url(r'^(?P<pk>\d+)/$', views.UpdateItem.as_view(), name='update_item'),                
 )

views.py views.py

class UpdateItem(UpdateView):
    model = Item
    form_class = EditForm
    template_name = 'todo/detail.html'
    # Revert to a named url
    success_url = reverse_lazy('index')

I have looked at the solution suggesting form.fields['field'].widget.attrs['readonly'] = True but I am unsure where to put this or how to implement 我已经看过建议form.fields['field'].widget.attrs['readonly'] = True的解决方案,但是我不确定该放在哪里或如何实现

Field.disabled New in Django 1.9. Field.disabled Django 1.9中的新增功能。 The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won't be editable by users. 禁用的布尔参数设置为True时,将使用禁用的HTML属性禁用表单字段,以便用户无法对其进行编辑。 Even if a user tampers with the field's value submitted to the server, it will be ignored in favor of the value from the form's initial data. 即使用户篡改了提交给服务器的字段的值,也将忽略该字段,而使用表单的初始数据中的值。

def MyForm(forms.ModelForm):
 class Meta:
  model = MyModel
 def __init__(self):
  self.fields['field'].disabled = True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM