简体   繁体   中英

Adding custom fields to Django admin

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM