1

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

4
  • have you migrated after creating second model Commented Dec 16, 2019 at 8:33
  • yes I have migrated Commented Dec 16, 2019 at 8:38
  • Totally unrelated, but I kindly suggest you use django.contrib.auth for all user management stuff... Commented Dec 16, 2019 at 8:42
  • @bruno desthuilliers,Sorry, I have deleted the comment Commented Dec 16, 2019 at 8:46

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

I think the name (NewUser) is misleading. I dont want to create a new user. I just want to create another table and add data to it. The name can be anything other than new user
naming you can change as you wish, it should be relevant to the project, so that in future you or any other developers can trace it.
I have a "class User" in my models.py just like yours. When I tried to make migrations and migrate, there are no tables created. When I renamed it to "class Person" it created a bunch of tables along with the table "projectApp_person"
1

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.