[Django]-Why are my django model fields not working?

6πŸ‘

βœ…

The problem is your * imports.

django.db.models.CharField is being replaced by django.forms.CharField:

>>> from django.db.models import *
>>> CharField 
<class 'django.db.models.fields.CharField'>
>>> from django.forms import *
>>> CharField 
<class 'django.forms.fields.CharField'>

So, actually name = CharField(max_length=60) defines a form field instead of a model one – it breaks everything and makes this bug subtle.


Solution: remove unnecessary forms import and be explicit in your imports:

from django.db import models
from django.contrib import admin


class Stock(models.Model):
    name = models.CharField(max_length=60)

    class Meta:
        ordering = ["name"]

    def __unicode__(self):
        return self.name

admin.site.register(Stock)
πŸ‘€alecxe

Leave a comment