Reputation: 855
I need to customize the admin panel added to the model page related inputs from another model. But I can not figure out how to save them.
admin.py
class OrderAdmin(admin.ModelAdmin):
change_form_template = 'admin/testapp/order/change_form.html'
def change_view(self, request, object_id, extra_context=None):
order = Order.objects.get(id=object_id)
card_list = Card.objects.all().filter(type=order.type)
result = super(OrderAdmin, self).change_view(request, object_id, extra_context={
'card_list': card_list,
})
return result
change_form.html
{% for card in card_list %}
<input type="text" name="card-{{ card.id}}" value="{{ card.qty }}"></td>
{% endfor %}
How to save the changed values in the Card model?
I tried to do as described here: https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#adding-custom-validation-to-the-admin
But self.cleaned_data does not include my data from inputs.
Thanks.
UPD: Well, I caught the data, but I think it's pretty messy way. I'm hardly can imagine how I would calculate the id from inputs.
def save_model(self, request, obj, form, change):
request.POST['card-288']
Upvotes: 0
Views: 3810
Reputation: 18530
You are getting exactly what you produced :), nothing unexpected there!
You must override clean
(take a look here for instance) if you want some fields that you manually added in the change_list to be taken care of.
If you go that way, to retrieve the ID is up to you, but a simple split('-')[-1]
would work.
This answers your specific need.
On the other side, I think your are not going the right way. The django admin is good enough to deal with ForeignKeys ManyToMany, so I see no need to do things yourself.
While you can get it working with the above hint, I suggest you start all over - if you want, a new SO question where you publish the initial Model and what exactly you are trying to achieve.
Upvotes: 0
Reputation: 14190
Saving should be done in save_model. Your card_list
data should also be would have been available in the form
parameter if you had used django forms. Although you could still access it through request
as you correctly pointed out.
You will also have to sanitize the data yourself, something that django forms does for your automatically.
Upvotes: 1