如何使用自定义表单(与任何模型无关)将自定义页面添加到django admin?

Мих*_*лов 7 django django-admin

我想bulk_create通过TextArea或FileField通过django admin导入csv数据进行建模。我学习了如何覆盖模板块,如何向django admin添加新的URL。但是我不知道如何解决我的问题。我想用我的表格创建自定义管理页面。传递数据,解析它和bulk_create我的模型对象。你们能建议我该怎么做吗?

Мих*_*лов 5

我找到了这种情况的片段

from django.contrib import admin, messages
from django.http import HttpResponseRedirect
from django.shortcuts import render

from my_app.forms import CustomForm


class FakeModel(object):
    class _meta:
        app_label = 'my_app'  # This is the app that the form will exist under
        model_name = 'custom-form'  # This is what will be used in the link url
        verbose_name_plural = 'Custom AdminForm'  # This is the name used in the link text
        object_name = 'ObjectName'

        swapped = False
        abstract = False


class MyCustomAdminForm(admin.ModelAdmin):
    """
    This is a funky way to register a regular view with the Django Admin.
    """

    def has_add_permission(*args, **kwargs):
        return False

    def has_change_permission(*args, **kwargs):
        return True

    def has_delete_permission(*args, **kwargs):
        return False

    def changelist_view(self, request):
        context = {'title': 'My Custom AdminForm'}
        if request.method == 'POST':
            form = CustomForm(request.POST)
            if form.is_valid():
                # Do your magic with the completed form data.

                # Let the user know that form was submitted.
                messages.success(request, 'Congrats, form submitted!')
                return HttpResponseRedirect('')
            else:
                messages.error(
                    request, 'Please correct the error below'
                )

        else:
            form = CustomForm()

        context['form'] = form
        return render(request, 'admin/change_form.html', context)


admin.site.register([FakeModel], MyCustomAdminForm)

from django import forms


class CustomForm(forms.Form):

# Your run-of-the-mill form here
Run Code Online (Sandbox Code Playgroud)


mrt*_*rts 5

使用代理模型可以节省一些输入:

class ImportCSVData(SomeModel):
    class Meta:
        proxy = True

@admin.register(ImportCSVData)
class MyCustomAdminForm(admin.ModelAdmin):
    ... as in accepted answer ...
Run Code Online (Sandbox Code Playgroud)