django admin “add page” initial datetime from GET parameters

后端 未结 2 807
时光取名叫无心
时光取名叫无心 2021-01-12 21:35

I want to create a link which opens the django admin add page of a model with some fields pre filled.

I checked that it is possible to add parameters to the GET dict

2条回答
  •  臣服心动
    2021-01-12 22:24

    It appears the problem is your passing a string when it expects a date. You need to convert your string into a date first.

    You can use the built in python library datetime:

     import datetime
     value = datetime.datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
     def decompress(self, value):
         ...
    

    Edit: alecxe correctly pointed out that I was not properly answering your question. With a bit of a searching I found something that might be more relevant.

    According to this answer, Django allows you to replace the GET dictionary before it is processed. Borrowing from this example, it seems feasible that we could intercept your get parameters and replace the string dates with datetime objects in the GET dictionary

        def add_view(self, request, form_url='', extra_context=None):
            // any extra processing can go here...
            g = request.GET.copy()
            g.update({
                'date':datetime.datetime.strptime(request.GET.get('date'), "%Y-%m-%d %H:%M:%S"),
            })
    
            request.GET = g
            return super(MyModelAdmin, self).add_view(request, form_url, extra_context)
    

提交回复
热议问题