Stephen
Stephen

Reputation:

Make a foreign key field in a django form read-only, and still enable the form to be submitted

How do I make a foreign key field in a form read only but still allow this field to be recognized as valid once the form is submitted? According to W3C, disabled fields are left out once the form is submitted....using the code below, I can set the field as disabled, thus readonly, but my form doesn't go through

    def __init__(self, *args, **kwargs):
       super(IssuesForm, self).__init__(*args, **kwargs)
       self.fields['vehicle'].widget.attrs['readonly'] = True

Ideas....?

Upvotes: 6

Views: 3462

Answers (5)

David Grigoryev
David Grigoryev

Reputation: 124

My solution is :

def __init__(self, *args, **kwargs):
    super(TechCustomForm, self).__init__(*args, **kwargs)
    if self.initial['status'] == 'Done' or self.initial['status'] == 'Reject':
        self.fields['status'].disabled = True

Its work for Model ForeignKey Field

Upvotes: 1

Evan
Evan

Reputation: 2038

I came across this question after many other solutions didn't seem to work. Here's example code of how I got it work successfully using the "hidden" suggestion, in case it's helpful to anyone else.

class EditExifForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(EditExifForm, self).__init__(*args, **kwargs)
        self.fields['image'].widget.attrs['hidden'] = True    # This is the solution
        # Setting as 'readonly' didn't make a difference
        # Setting as 'disabled' made the form not update the database

    class Meta:
        model = exif
        ...

Upvotes: 4

Vinicius
Vinicius

Reputation: 1965

I've had this problem and I used JavaScript to solve

Upvotes: 0

Stephen
Stephen

Reputation:

Maybe I can try the hidden field...I knew this was a possibility, but I wanted to be sure there was no other way

Upvotes: 0

Terry G Lorber
Terry G Lorber

Reputation: 2962

I don't know the Django or Python syntax, however, an input field of type="hidden" might be what you're looking for. If you wanted to still display the value using a disabled field, you could do that too, and rely on the hidden field for the actual value.

Upvotes: 2

Related Questions