Opened 10 years ago
Last modified 10 years ago
#23501 new Bug
remove/add fields programatically in modelform fails in admin — at Initial Version
Reported by: | hadisunyoto | Owned by: | nobody |
---|---|---|---|
Component: | contrib.admin | Version: | 1.7 |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Accepted | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Pull Requests: | How to create a pull request | ||
Description ¶
model:
class Thickness(models.Model): value = models.DecimalField(primary_key=True, max_digits=7, decimal_places=2) is_active = models.BooleanField()
model form:
class ThicknessForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ThicknessForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) # edit if instance and instance.pk: del self.fields['value'] else: del self.fields['is_active'] class Meta: model = Thickness fields = '__all__'
admin:
class ThicknessAdmin(admin.ModelAdmin): list_display = ('value', 'is_active') form = ThicknessForm admin.site.register(Thickness, ThicknessAdmin)
refresh page, go to admin->Thickness, create one:
KeyError at /admin/thicknesses/thickness/add/
"Key 'is_active' not found in 'ThicknessForm'"
...
Error during template rendering
In template D:\env\lib\site-packages\django\contrib\admin\templates\admin\includes\fieldset.html, error at line 7
The highlighted line is number 7
6 {% for line in fieldset %}
7 <div class="form-row{% if line.fields|length_is:'1' and line.errors %} errors{% endif %}{% if not line.has_visible_field %} hidden{% endif %}{% for field in line %}{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% endfor %}">
8 {% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %}
go to admin->Thickness again, modify one (without using model form):
KeyError at /admin/thicknesses/thickness/0.55/
"Key 'value' not found in 'ThicknessForm'"
...
same error as above
Without admin, model form works as expected, it remove is_active when create, and it remove value when edit
According to the ticket's flags, the next step(s) to move this issue forward are:
- To provide a patch by sending a pull request. Claim the ticket when you start working so that someone else doesn't duplicate effort. Before sending a pull request, review your work against the patch review checklist. Check the "Has patch" flag on the ticket after sending a pull request and include a link to the pull request in the ticket comment when making that update. The usual format is:
[https://github.com/django/django/pull/#### PR]
.