Django admin 获取选中行数据 将这个数据传递到视图view
时间: 2024-03-28 08:41:37 浏览: 32
可以通过在Django admin中使用自定义Action来实现将选中行数据传递到视图(view)中。
首先,在你的app中创建一个自定义Action,比如:
```python
from django.contrib import admin
from django.urls import reverse
from django.http import HttpResponseRedirect
class CustomAction(admin.ModelAdmin):
actions = ['custom_action']
def custom_action(self, request, queryset):
ids = ','.join(str(q.id) for q in queryset)
url = reverse('myapp:myview', args=[ids])
return HttpResponseRedirect(url)
custom_action.short_description = "Custom Action"
```
在自定义Action中,我们使用了Django的reverse函数来获取视图的URL,并将选中行的ID作为参数传递给视图。
接下来,在你的app的urls.py中添加视图的URL,比如:
```python
from django.urls import path
from .views import MyView
app_name = 'myapp'
urlpatterns = [
path('myview/<str:ids>/', MyView.as_view(), name='myview'),
]
```
在这个视图中,我们可以通过获取URL参数来获取选中行数据的ID列表,比如:
```python
from django.views.generic import View
from django.shortcuts import render
class MyView(View):
def get(self, request, ids):
id_list = ids.split(',')
queryset = MyModel.objects.filter(id__in=id_list)
context = {'queryset': queryset}
return render(request, 'my_template.html', context)
```
在这个视图中,我们通过使用split函数将ID列表字符串分割成一个ID列表,并使用filter函数从数据库中获取选中行的数据。最后,我们将数据传递给一个自定义的模板(my_template.html)进行处理。
最后,在你的ModelAdmin中注册自定义Action,比如:
```python
from .models import MyModel
@admin.register(MyModel)
class MyModelAdmin(CustomAction):
list_display = ['id', 'name']
```
现在,当你在Django admin中选中行并点击自定义Action时,它将把选中行数据的ID列表作为参数传递给视图,并显示视图处理后的结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)