shaswat kumar
shaswat kumar

Reputation: 349

Adding data to created sqlite database in Django

I have created two classes in models.py in my application.

models.py

 from django.db import models

 # Create your models here.
 class User(models.Model):
 first_name = models.CharField(max_length=264, unique=True)
 last_name = models.CharField(max_length=264, unique=True)
 email = models.CharField(max_length=264,unique=True)

 def __str__(self):
    return self.first_name

 class NewUser(models.Model):
 categorie = models.ForeignKey('User',on_delete=models.DO_NOTHING)
 area = models.CharField(max_length=264)

def __str__(self):
    return self.name

enter image description here

as shown in my image my (User and New users)tables are created. data is getting added to my (User) table. But when I try to add data to my (New users) table I get this error enter image description here

Upvotes: 1

Views: 1646

Answers (2)

filiphl
filiphl

Reputation: 991

Most likely you haven't migrated properly. Try:

python manage.py makemigrations
python manage.py migrate

The models show up in the admin because they are present in the apps models.py. This is not related to the database!

Upvotes: 1

bmons
bmons

Reputation: 3392

Since you don't have any custom fields in your User model, you dont need to create a seperate User class, only you have to import the built in User class.

from django.contrib.auth.models import User

class NewUser(models.Model):
   categorie = models.ForeignKey('User',on_delete=models.DO_NOTHING)
   area = models.CharField(max_length=264)

   def __str__(self):
      return self.categorie.user.username

You can still get username, first_name, last_name, email etc from the default user class. Refer: https://docs.djangoproject.com/en/3.0/ref/contrib/auth/#django.contrib.auth.models.User

Upvotes: 2

Related Questions