将kwargs传递给django管理表单

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将kwargs传递给django管理表单相关的知识,希望对你有一定的参考价值。

我有几个型号,例如:

class Product (models.Model):
    title = models.CharField(
        max_length = 255,
    )
    supplier = models.ForeignKey(
        Supplier,
        blank=True,
        null=True
    )
    min_level = models.IntegerField(
        default = 10,
    )
    quantity = models.IntegerField(
        default = 0
    )

class ReOrder (models.Model):
    product = models.ForeignKey(
        Product,
    )
    order_quantity = models.IntegerField(
        default = 0
    )
    order_date = models.DateField(
        default = datetime.datetime.now()
    )
    received = models.BooleanField(
        default = False
    )
    def __unicode__(self):
        return u'%s' % (self.product)

当我在Django Admin中列出我的产品时,我有一个ReOrder按钮。点击后我想直接进入Django Admin ReOrder添加ReOrder.product默认为产品预填充

获得按钮等就可以了,但我无法理解如何通过Product.id。

我正在尝试:reverse('admin:inventory_reorder_add', kwargs={'product_id' : obj.pk })其中obj.pk是产品。这给了我

使用关键字参数'{'product_id':31L}'找不到'inventory_reorder_add'

如何拨打电话并在管理员中预先选择该字段?

谢谢你的帮助。

以下是完整的ProductAdmin类。

class ProductAdmin(admin.ModelAdmin):
    list_display = ['title', 'get_sku', 'get_ebaylink', 'quantity', 'quantity_status','account_actions','weekly_stock','monthly_stock','quarterly_stock']
    ordering = ['title', 'quantity', ]
    inlines = [SkuInline, EbayLinkInline]
    search_fields = ('title', 'sku__sku', 'ebaylink__custom_label', )
    fields = ['title', 'supplier', 'min_level', 'quantity']

    def get_sku(self, obj):
        try :
            instance = Sku.objects.filter(product=obj)
            msg = ''
            for i in instance:
                msg += i.sku + ', '
            return msg
        except : return None
    get_sku.short_description = 'Amazon Sku'
    get_sku.admin_order_field = 'sku__sku'

    def get_ebaylink(self, obj):
        try:
            instance = EbayLink.objects.filter(product=obj)
            msg = ''
            for i in instance:
                msg += i.custom_label + ', '
            return msg
        except: return None
    get_ebaylink.short_description = 'Ebay Custom Label'
    get_ebaylink.admin_order_field = 'ebaylink__custom_label'

    def quantity_status(self, obj):
        if obj.min_level > obj.quantity:
            return '<div style="width:100%%; height:100%%; background-color:red;">%s</div>' % (obj.quantity-obj.min_level)
        return '%s' % (obj.quantity-obj.min_level)
    quantity_status.short_description = 'Variance from min level'
    quantity_status.allow_tags = True
    quantity_status.admin_order_field = 'total'

    def get_queryset(self, request):
        qs = super(ProductAdmin, self).get_queryset(request)
        qs = qs.annotate(total=ExpressionWrapper(F('quantity')-F('min_level'), output_field=DecimalField())).order_by('total')
        return qs

    def get_urls(self):
        urls = super(ProductAdmin, self).get_urls()
        custom_urls = [
            url(r'^(?P<product_id>.+)/add-stock/$', self.admin_site.admin_view(self.add_stock), name='add-stock',),
            url(r'^(?P<product_id>.+)/delete-stock/$', self.admin_site.admin_view(self.delete_stock), name='delete-stock',),
            url(r'^(?P<product_id>.+)/reorder-stock/$', self.admin_site.admin_view(self.delete_stock), name='reorder-stock',),
        ]
        return custom_urls + urls

    def account_actions(self, obj):
        return format_html(
            '<a class="button" href="{}">+</a>&nbsp;'
            '<a class="button" href="{}">-</a>&nbsp;'
            '<a class="button" href="{}">Reorder</a>',
            reverse('admin:add-stock', args=[obj.pk]),
            reverse('admin:delete-stock', args=[obj.pk]),
            reverse('admin:inventory_reorder_add', kwargs={'product_id' : obj.pk }),
        )
    account_actions.short_description = 'Account Actions'
    account_actions.allow_tags = True

    def add_stock(self, request, product_id, *args, **kwargs):
        product = Product.objects.get(pk=product_id)
        product.quantity += 1
        product.save()
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

    def delete_stock(self, request, product_id, *args, **kwargs):
        product = Product.objects.get(pk=product_id)
        product.quantity -= 1
        product.save()
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

admin.site.register(Product, ProductAdmin)
答案

您可以通过查询字符串而不是URL将默认值传递给管理编辑页面。

'<a class="button" href="{}?product_id={}">Reorder</a>',
...
reverse('admin:inventory_reorder_add'), obj.pk

以上是关于将kwargs传递给django管理表单的主要内容,如果未能解决你的问题,请参考以下文章

将 Django 表单传递给模板标签

将实例传递给 Django 表单集

python Django:将表单视图中的变量传递给表单

Django 表单向导 - 将请求传递给视图?

将HTML表单变量传递给Django中的python函数

将 Javascript 计算传递给 Django 后端