将自定义字段添加到Django admin [英] Adding custom fields to Django admin

查看:296
本文介绍了将自定义字段添加到Django admin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用各种领域定义了我的模型。
其中一些是自定义字段,我使用我的应用程序的fields.py文件来验证信用卡数据。来源是此处

I have defined my model with various fields. Some of these are custom fields, which I am using to validate credit card data, using the fields.py file of my app. Source is here.

class Transaction(models.Model):
    card_name = models.CharField()
    card_number = CreditCardField(required=True)
    security_code = VerificationValueField(required=True)
    expiry_date = ExpiryDateField(required=True)

我在我的模型中定义了一个ModelForm

I have defined a ModelForm in my forms.py file.

class TransactionForm(forms.ModelForm):
    class Meta:
        model = Transaction
        fields = "__all__"

我已经将表单添加到了管理员中。 py文件。

And I've added the form to my admin.py file.

class TransactionAdmin(admin.ModelAdmin):
    form = TransactionForm

    def get_fieldsets(self, *args, **kwargs):
        return (
            (None, {
                'fields': ('card_name', 'card_number'),
            }),
        )
admin.site.register(Transaction, TransactionAdmin)

但是,自定义字段似乎没有显示在管理小组。经过大量研究,我发现作为解决方案,除非它不起作用。我尝试了各种尝试,包括添加带有缺少字段的元组以使其正常工作,但没有骰子。是的,我已经做了很多搜索。

However, the custom fields don't seem to be showing in the administration panel. Having done a ton of research, I found this, which would seem to be the solution, except it doesn't work. I've tried all sorts of over things including adding a fields tuple with the missing fields to get it to work, but no dice. And yes I've done plenty of searching.

在上一个链接中遵循解决方案时出现的错误是:

The error I get when following the solution in the last link is this:

为交易指定的未知字段(卡号)。检查字段TransactionAdmin的字段/字段集/排除属性。

运行Django 1.7.4,Python 3。

Running Django 1.7.4, Python 3.

推荐答案

像这样更改模型/管理员/表单

Change your model / admin / form like this

class Transaction(models.Model):
    card_name = models.CharField()
    card_number = models.CharField(max_length=40)
    expire_date = models.DateTimeField()
    card_code = models.CharField(max_length=10)

 

class TransactionForm(forms.ModelForm):
    card_number = CreditCardField(required=True)
    expiry_date = ExpiryDateField(required=True)
    card_code = VerificationValueField(required=True)
    class Meta:
        model = Transaction
        fields = "__all__"

 

class TransactionAdmin(admin.ModelAdmin):
    form = TransactionForm

admin.site.register(Transaction, TransactionAdmin)

更新:

CreditCardField 是一个Form字段,而不是model字段。在您发布的链接中查看其用法。

CreditCardField is a Form field, not a model field. See its usage in the same link that you have posted.

这些字段将以表格形式出现。

Those fields will come in the form.

这篇关于将自定义字段添加到Django admin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆