Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a field be disabled in View.py of Django project?

Tags:

python

django

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)

I tried to do this but its not working, i know how to do it in Forms.py , but i want to know in views its possible or not?

Im using Django 2.0

like image 633
Chidananda Nayak Avatar asked Oct 17 '25 15:10

Chidananda Nayak


1 Answers

Yes, since django-1.9, a field has a .disabled attribute that can be set to True:

So we can use:

def resume_edit(request, r_id):
    r = Resume.get.object(pk=r_id)
    resume = ResumeModelForm(instance=r)

    resume.fields['email'].disabled = True 

    return render(request, 'resumes/resume.html', context)

This will not only ensure that the HTML of the corresponding form parts is disabled, but will also ignore possible changes when you post the Form (note that you of course first need to disable the field).

Since the render(..) call produces the HTML, the field should of course be altered before it is rendered, validated, or .save()'d.

The .disabled attribute is typically better than using readonly, etc. Since some form elements have a special way to disable the element at the HTML level (some use disabled instead). Furthermore like said before it does not only disable the form element at the HTML level. If a user wants to post malicuous values, then the form will simply ignore these.

like image 174
Willem Van Onsem Avatar answered Oct 20 '25 06:10

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!