Django: Custom "add only" inline
I want an inline form to only show its fields contents, and not let users to edit or remove entries, only add them. That means that the values would be similar when using the readonly_fields
option, and the "Add another ..." link at the bottom would make a form appear, letting users add more entries.
The can_delete
option it's useful here, but the readonly_fields
lock both add and change possibilities. I imagine that building a new inline开发者_开发技巧 template would do. In that case, how would I just show the field values for each entry and then put a form at the bottom?
Edit: what I got until now:
# models.py
class AbstractModel(models.Model):
user = models.ForeignKey(User, editable = False)
... some more fields ...
class Meta:
abstract = True
class ParentModel(AbstractModel):
... fields ...
class ChildModel(AbstractModel):
parent = models.ForeignKey(ParentModel, ... options ...)
... fields ...
# admin.py
class ChildModelInline(admin.TabularInline):
model = ChildModel
form = ChildModelForm
can_delete = False
class ParentModelAdmin(admin.ModelAdmin):
... options ...
inlines = (ChildModelInline,)
# forms.py
class ChildModelForm(models.ModelForm):
user = forms.CharField(required = False)
... some more fields and stuff needed ...
def __init__(self, *args, **kwargs):
super(ChildModelForm, self).__init__(*args, **kwargs)
try: user = User.objects.get(id = self.instance.user_id)
except: return None
self.fields['user'].initial = user.first_name
self.fields['user'].widget.attrs['readonly'] = 'readonly'
In this example I'm doing like I wanted the user
field as readonly.
In the last line, If I change the widget attribute to ['disabled'] = True
, it works fine, but I need a text entry, not a disabled form field. I'm also aware that I'll need to override the save_model()
and save_formsets()
for this to work properly.
I would use extra=1
to get that last working form.
Then loop through all the forms except the last one in your view and change, like this, every field: In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?
You don't have to do it in the __init__
, you can access those attributes after the entire formset is created of course.
精彩评论