portman
portman

Reputation: 33

submit form to django-admin model with filter

I would like to have a custom snippet of html form code that takes allows the user to select a 'training' that is then used as a query parameter to a django-admin model filter for 'participants'.

I've successfully created the filter on the modeladmin:

class ParticipantAdmin(RestrictedModelAdmin):
    list_filter = ('training__name',)

It's probably worth noting that RestrictedModleAdmin is a subclass of ModelAdmin that provides row-level security for the model; logged in users should only see rows they own.

Thus, urls using this filter look something like this when just using that admin interface:

/admin/core/participant/?training__name=Menno+Ropes

All that works great. Now I think I should be able to create a very simple form that allows selecting a valid 'training' and submitting that to /admin/core/participant/ as a GET.

<form method="GET" action="/admin/core/participant/">{% csrf_token %}
    <ol>
        <li>Select your training:
            <select name='training__name'>
                <option value=''>&mdash;</option>
                {% for training in trainings %}
                <option value='{{ training.name }}'>{{ training }}</option>
                {% endfor %}
            </select>
        </li>
        <li>See participants for that training.
            <input type='submit' name='submit' value='Submit' /></li>
    </ol>
</form>

This last bit doesn't see to work. Some magic foo in the django innards seems to always mangle the submission to be:

/admin/core/participant/?e=1

This obviously doesn't select the appropriate filter value and thus shows an unfiltered list of 'participants'.

What's going on? What can I do to get it to allow my GET parameter to pass through to the admin model?

Thanks in advance.

PS) Django 1.3+

Upvotes: 0

Views: 1527

Answers (2)

glic3rinu
glic3rinu

Reputation: 221

It's a little bit tricky, but it works for me:

def changelist_view(self, request, bill_id, extra_context=None):
    """queryset is an extra parameter"""
    req = request.GET.copy()
    if 'queryset' in req:
        queryset = req.pop('queryset')[0]
    else:
        queryset = request.META['HTTP_REFERER'].split('queryset=')[1]
        url = "/admin/billing/invoice/%s/select_to_move/?%s&queryset=%s" % (bill_id, request.GET.urlencode(), queryset)
        return HttpResponseRedirect(url)  
    request.GET = req
    # Do stuff with queryset.
    return super(MyAdminClass, self).changelist_view(request, context)    

Upvotes: 0

The problem is that you have a name attribute in your <input type="submit">, causing an extra GET parameter: submit which is throwing the invalid lookup error and thus e=1

Remove the name attribute and you're good to go.

I did a little experiment to confirm since I thought it odd that the server might somehow treat a browser GET differently.

Upvotes: 2

Related Questions