Adding custom fields to Django admin

南楼画角 提交于 2020-08-05 15:23:40

问题


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)

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

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

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:

Unknown field(s) (card_number) specified for Transaction. Check fields/fieldsets/exclude attributes of class TransactionAdmin.

Running Django 1.7.4, Python 3.


回答1:


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)

UPDATE:

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.



来源:https://stackoverflow.com/questions/29056477/adding-custom-fields-to-django-admin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!