Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin: pass variable by URL

i want to pass a variable by URL to another page in django admin. it seems it is not working, i want to pass the variable "/?name=hello", and catch it by request.GET.get["name",""].but the url becomes "/?e=1" after it passed. if i use the default parameter'q', it works, but it will have a conflict. it seems this problem is django-admin only. and i need pass it by url not post... does any one knows how to solve this problem

thanks

like image 201
Grey Avatar asked Aug 16 '10 20:08

Grey


2 Answers

The problem is that the lookup name does not exist when the get_query_set tries to resolve it as a model field. Thus an IncorrectLookupParameters() exception is raised which in turn redirects to the not very helpful "e=1" url. This problem is solved in Django 1.4 with the introduction of custom filterspecs. Until then one possible solution is to dynamically overwrite the ChangeList class returned by your ModelAdmins get_changelist() method.

This solution works on Django 1.3:

class MyModelAdmin(ModelAdmin):

    def get_changelist(self, request, **kwargs):
        changelist_class = super(MyModelAdmin, self).get_changelist(request, 
                                                                 **kwargs)

        class CustomChangeList(changelist_class):
            def __init__(self, request, *args, **kwargs):
                self._name = request.GET.get('name')
                super(CustomChangeList, self).__init__(request, *args, **kwargs)

            def get_query_set(self, *args, **kwargs):
                if self._name:
                    del self.params['name']

                qs = super(CustomChangeList, self).get_query_set(*args, **kwargs)

                if self._name:
                    return qs.filter([FILTER WHAT YOU WANT HERE...])

                return qs


        return CustomChangeList
like image 200
Rune Kaagaard Avatar answered Nov 16 '22 03:11

Rune Kaagaard


Can you explain your problem a bit more....why do you want to pass a variable to django admin... also you cant catch GET variable like this... Either use:

request.GET['name'] 

or

request.GET.get('name','')

.get is a instancemethod not a dictionary.

like image 40
crodjer Avatar answered Nov 16 '22 04:11

crodjer