简体   繁体   中英

Django: How do I make fields non-editable by default in an inline model formset?

I have an inline model formset, and I'd like to make fields non-editable if those fields already have values when the page is loaded. If the user clicks an "Edit" button on that row, it would become editable and (using JavaScript) I would replace the original widgets with editable ones. I'd like to do something like this when loading the page:

for field in form.fields:
    if field.value:
        # display as text
    else:
        # display as my standard editable widget for this field

I see that inlineformset_factory has an argument called formfield_callback . I suspect that this could be useful, but so for I haven't found any documentation for it. Can anyone point me to some useful documentation for this, and how it can help me solve this problem?

This one stumped me for a bit too. Hopefully this is what you're looking for.

<TABLE>
    <form method="post" action=".">
        {{ formset.management_form }}
        {% for form in formset.forms %}
            {{ form.id }}
            <tr>
                <td>{{ form.FirstName }}</td> <!-- This is a normal, editable field -->
                <td>{{ form.instance.LastName }}</td> <!-- 'instance' is your actual Django model. LastName displays the text from the last name field -->
            </tr>
        {% endfor %}
    </form>
</TABLE>

This thread is a bit old, but for anyone looking:

in the form:

myfield=forms.CharField( widget=forms.TextInput(attrs={'class':'disabled', 'readonly':'readonly'}))

The "readonly" is an HTML attribute that makes the form uneditable. "disabled" is a CSS class as you'll want to modify the default styling, also it makes the jQuery simpler.

To make readonly inputs editable when clicked, here's a jQuery example:

$('input.disabled').click(function(){
    $(this).removeAttr('readonly').removeClass('disabled');
});

I think you might be able to override the init function of your form that is used in a formset. There you could check for initial_data, and dynamically build your forms like you're hoping to do. At least, it sounds plausible in my head.

I had a question where I wanted to " Auto-generate form fields ", can found a solution for dynamically creating forms, it may help:

Auto-generate form fields for a Form in django

It's not clean and there's probably a better way to handle this.

How about just sending the data as editable (normal formset) from django and do the value check with javascript, using javascript to toggle the widgets?

form.instance.LastName 将显示值,form.initial.LastName 将显示主键。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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