In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?

后端 未结 26 959
-上瘾入骨i
-上瘾入骨i 2020-11-22 04:09

In a Django form, how do I make a field read-only (or disabled)?

When the form is being used to create a new entry, all fields should be enabled - but when the recor

相关标签:
26条回答
  • 2020-11-22 04:26

    One simple option is to just type form.instance.fieldName in the template instead of form.fieldName.

    0 讨论(0)
  • 2020-11-22 04:27

    awalker's answer helped me a lot!

    I've changed his example to work with Django 1.3, using get_readonly_fields.

    Usually you should declare something like this in app/admin.py:

    class ItemAdmin(admin.ModelAdmin):
        ...
        readonly_fields = ('url',)
    

    I've adapted in this way:

    # In the admin.py file
    class ItemAdmin(admin.ModelAdmin):
        ...
        def get_readonly_fields(self, request, obj=None):
            if obj:
                return ['url']
            else:
                return []
    

    And it works fine. Now if you add an Item, the url field is read-write, but on change it becomes read-only.

    0 讨论(0)
  • 2020-11-22 04:27

    Is this the simplest way?

    Right in a view code something like this:

    def resume_edit(request, r_id):
        .....    
        r = Resume.get.object(pk=r_id)
        resume = ResumeModelForm(instance=r)
        .....
        resume.fields['email'].widget.attrs['readonly'] = True 
        .....
        return render(request, 'resumes/resume.html', context)
    

    It works fine!

    0 讨论(0)
  • 2020-11-22 04:28

    You can elegantly add readonly in the widget:

    class SurveyModaForm(forms.ModelForm):
        class Meta:
            model  = Survey
            fields = ['question_no']
            widgets = {
            'question_no':forms.NumberInput(attrs={'class':'form-control','readonly':True}),
            }
    
    0 讨论(0)
  • 2020-11-22 04:29

    Setting readonly on a widget only makes the input in the browser read-only. Adding a clean_sku which returns instance.sku ensures the field value will not change on form level.

    def clean_sku(self):
        if self.instance: 
            return self.instance.sku
        else: 
            return self.fields['sku']
    

    This way you can use model's (unmodified save) and avoid getting the field required error.

    0 讨论(0)
  • 2020-11-22 04:32

    I think your best option would just be to include the readonly attribute in your template rendered in a <span> or <p> rather than include it in the form if it's readonly.

    Forms are for collecting data, not displaying it. That being said, the options to display in a readonly widget and scrub POST data are fine solutions.

    0 讨论(0)
提交回复
热议问题