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
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
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
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!
Related
I'm new to Django, and I'm trying to create a "game" model with two attributes:
A many-to-one field where multiple instances of the game model are associated with an instance of a custom user model.
A many-to-many field where instances of the game model are connected with multiple instances of words, and instances of the word model are connected with multiple instances of the game model
Top of my models.py model:
from django.db import models
from users.models import CustomUser
from django.contrib.postgres.fields import ArrayField
Game model:
class SortingGame(models.Model):
user_current_player = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, blank=True)
field_words = models.ManyToManyField(Word, related_name="field_sorting_games")
Word model:
class Word(models.Model):
str_word = models.CharField(max_length=50,null=True)
int_grade_level = models.IntegerField()
arrint_phonemes = ArrayField(models.CharField(max_length=50),null=True)
arrstr_graphemes = ArrayField(models.CharField(max_length=50),null=True)
int_num_syllables = models.IntegerField()
arrstr_syllables = ArrayField(models.CharField(max_length=50),null=True)
User model:
class CustomUser(AbstractBaseUser):
# must have the following fields for django
email = models.EmailField(verbose_name="email",max_length = 100,unique=True)
username = models.CharField(max_length = 30, unique = True)
date_joined = models.DateTimeField(verbose_name = "date_joined",auto_now_add=True)
last_login = models.DateTimeField(verbose_name = "last_login",auto_now = True)
is_admin = models.BooleanField(default=False)
is_superuser = models.BooleanField(default = False)
is_staff = models.BooleanField(default = False)
is_active = models.BooleanField(default = True)
first_name = models.CharField(max_length=15, blank=True)
last_name = models.CharField(max_length=30, blank=True)
spelling_level = models.IntegerField(default=1, unique=False)
time_played = models.IntegerField(default=0, unique=False)
percent_correct = models.IntegerField(default=0, unique=False)
admin.py:
from django.contrib import admin
from .models import Word, SortingGame
admin.site.register(SortingGame)
When I run python3 manage.py makemigrations and python3 manage.py migrate, it doesn't complain, but when I go to the admin page of my django site it says psycopg2.errors.UndefinedColumn: column "user_current_player_id" of relation "game_sortinggame" does not exist.
This makes me think the issue is with user_current_player in SortingGame (it worked fine before I added that attribute), but I've looked around on different forums to see what might be going wrong and I can't seem to figure it out. I tried starting from scratch with a new database, and it's still throwing the same exception. Any ideas would be appreciated—thanks!
Nathan!
First thing would be make sure that you have the app where CustomUser model is created in your settings.py file, at INSTALLED_APPS.
If so, please have a look at this folder (app) where you have CustomUser defined to verify if there is in deed a migrations folder there.
I suspect that Django in not aware of this app (not under INSTALLED_APPS) and therefore did not migrated it. So, your database is not finding the User Model connection.
That said, I would suggested you to keep your account model as defined by Django User and create another model with a direct relationship to it to deal with profile/game fields such as spelling level, percentage_correct and so on.
This would keep your Model "concerns" more organized later on.
if you did make a migrations before try to use (python manage.py makemigrations -appname)
Also after That you need to Add the module in your admin.py
from django.contrib import admin
from .models import *
admin.site.register(SortingGame)
... all other modules
I was trying to show the list of the User's to-do lists using view.html. The error says:
no such column:testapp_todolist.user_id".
But I don't understand where this column is and how it is related to the red line in my view.html:
{% for td in user.todolist.all %}
Can you please explain in details how do I add this column?
Here's my models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class ToDoList(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="todolist", default=0)
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Item(models.Model):
todolist = models.ForeignKey(ToDoList, on_delete=models.CASCADE)
text = models.CharField(max_length=200)
complete = models.BooleanField()
def __str__(self):
return self.text
Try solving this by writing this on your console:
python manage.py makemigrations
python manage.py migrate
Those commands are going to create tables for the TodoList model in the database.
user does not have the object todolist, todolist is a foreign key in Item. You should do:
list = ToDoList.objects.filter(user=YOUR_USER_HERE)
or
# if you want to get the todolist of the currently logged in user
list = ToDoList.objects.filter(user=request.user)
but i see Groups and Users model by default if i try to register my model in app/admin.py using admin.site.register(model_name) if i try to registered the default Groups and User it will also not working for me.
CODE
Directory 'app/admin.py'
from django.contrib import admin
from app.models import Contact
admin.site.register(Contact)
Directory 'app/models.py'
from django.db import models
class Contact(models.Model):
name = models.CharField(max_length=100)
gender = models.CharField(max_length=50,choices=('female','Female')
('male','Male')))
email = models.EmailField(max_length=100)
info = models.CharField(max_length=100)
phone = models.IntegerField()
image = models.ImageField(blank=true,upload_to='images/')
date_added = models.DateField(auto_now_add=True)
def __str__(self):
return self.name
Change the import from "app.models" to just ".models" because they are in the same directory and see
i have created a model Post
class Post(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='blog_image', default='default.jpg')
smallContent = models.TextField()
content = models.TextField()
data_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
but id field is not showing in admin panel. i did makemigrations and migrate and both are done successfully.
AutoField is generated after the model is saved. It is not provided in Admin Panel as it should not be editable.
If want to make id editable (not recommended) override it as a CharField instead of AutoField with primary_key=True.
Else if just want to show it in the panel (while editing a saved model), add it to the read_only list of your model admin.
Read about AutoField here.
Since it is a readonly field I think you probably need to explicitly tell admin to show it.
I don't know if this will work but try in admin.py
from django.contrib import admin
from .models import Post
class PostAdmin(admin.ModelAdmin):
readonly_fields = ['display_id']
def display_id(self, obj):
return obj.id
admin.site.register(Post, PostAdmin)
....
from django.contrib.auth.models import User
class Person(models.Model):
user = models.OneToOneField(User)
avatar = models.ImageField(upload_to="photos/")
level = models.IntegerField(default=0)
def __unicode__(self):
return u"%s" % self.user
I'd like to add an edit-person page where the user can modify his profile if he wants to. So I created not only a form for the model Person but also another one for the django model User so that the user can modify information such as username, last_name, first_name, email etc
I'm not proud of the way I did it although it works well.
So my question is:
Is there a way that I can "explode" the django User field which is in my Person model instead of having a select list in my client side?