How to use User as foreign key in Django 1.7 - python

I have made a model which looks like this:
from django.contrib.auth.models import User
class Commens(models.Model):
publish = models.ForeignKey(User, unique=True)
example = models.CharField(max_length=1000)
But when I run python manage.py syncdb , I get:
ValueError: Lookup failed for model referenced by field
books.Commens.publish: auth.User
Where I'm wrong and how to fix this?

Related

Why is Django giving me a ValueError when I reference a class within the same model?

I'm building a simple recipe app, and so far I have two models: Ingredient and Recipe.
Each recipe should have multiple ingredients, so I laid out my model like this:
class Ingredient(models.Model):
name = models.CharField(max_length=50)
class Recipe(models.Model):
title = models.CharField(max_length=100)
ingredients = models.ForeignKey(Ingredient, on_delete=CASCADE)
instructions = JSONField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=SET_DEFAULT, default='Chef Anon')
When I makemigrations, I get nothing, but when I migrate, I get this ValueError:
ValueError: Cannot alter field cookbook.Recipe.ingredients into cookbook.Recipe.ingredients - they do not properly define db_type (are you using a badly-written custom field?)
Following the example here (Django: Add foreign key in same model but different class), I've tried setting ingredients=models.ForeignKey(Ingredient, on_delete=CASCADE) as well as using lazy syntax ingredients=models.ForeignKey("Ingredient", on_delete=CASCADE), but each time, makemigrations shows no changes, and migrate gives me the same ValueError.
Edit
My imports:
from django.db.models.deletion import CASCADE, SET_DEFAULT, SET_NULL
from django.db.models.fields.json import JSONField
from django.utils import timezone
from django.contrib.auth.models import User```
Try replacing on_delete=CASCADE with on_delete=models.CASCADE
If you have not imported CASCADE separately from models.
All though, in that case you should get a warning that "CASCADE is not defined".
I believe I found the problem: My models.py file was in the root directory, not in the app directory.

Cannot assign "<class 'django.contrib.auth.models.User'>": "Model.user" must be a "User" instance

Creating first entry to model is throwing error
I executed following commands to migrate
manage.py makemigrations
manage.py migrate
All worked fine, after I made those commands to create the first 'data' in the database
manage.py shell
from sms.models import Post
from django.contrib.auth.models import User
post_1 = Post(name="testname", email="testemail", gender="Monsieur", number="23233", author=User)
And it gave me this error:
ValueError: Cannot assign "<class 'django.contrib.auth.models.User'>": "Post.author" must be a "User" instance.
models.py files
from django.db import models
from django.contrib.auth.models import User
THE_GENDER = [
("Monsieur", "Monsieur"),
("Madame", "Madame")
]
class Post(models.Model):
name = models.CharField(max_length=100)
email = models.CharField(max_length=100)
gender = models.CharField(max_length=8, choices=THE_GENDER)
number = models.CharField(max_length=100)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.name
You see this error because you are trying to assing class object to author attribute. But it suppose to be User instance. So you should create user record first and use it, something like this instead:
user = User.objects.create_user(username="name", email="email#mail.com", password="Pass12345")
post_1 = Post(name="testname", email="testemail", gender="Monsieur", number="23233", author=user)
You can think about model class as about database table. While model instance represents record from this table.

Django User model foreign key failed

I am using django 2.0. For users I am using the model django.contrib.auth.models.User. I have stored a user with username john in it. I have a Post model which uses a User model as ForeignKey. This is my models.py:
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
post_content = models.CharField(max_length=140)
post_date = models.DateTimeField('post date')
post_user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.post_content
...In my views.py I am creating a post with:
from django.contrib.models import User
Post.objects.create(post_content=post_text, post_date=timezone.now(),post_user=User.objects.get(username='john'))
...In one part of the code. When I run I get this error:
FOREIGN KEY constraint failed
IntegrityError at /
And it points to the line in which I create the user in views.py.
Is there a proper way to ForeignKey a user model? Any guidance appreciated. Thank you :-).
EDIT:It works after doing a reset to the database because I made an error with migrations. Run you migrations properly friends!

Django migration not working with postgresql?

I have models :
class Keyword(models.Model):
keyword_name = models.CharField(max_length=40)
keyword_category = models.ForeignKey(Category, null=True)
class Category(models.Model):
category_name = models.CharField(max_length=40)
active = models.BooleanField(default=False)
But when I create migrate this model it give error
django.db.utils.ProgrammingError: relation "main_Keyword" does not
exist
I have try many ways but it's not working.Firstly this project i'm create on local using sqlite database but when I migrate database to postgresql then it give this error. what is my mistake?
EDIT :
Request Method: GET Request
URL: http://127.0.0.1:8000/admin/main/keyword/ Django Version: 1.9.6
Exception Type: ProgrammingError Exception Value: column
main_keyword.keyword_category_id does not exist LINE 1:
...ain_keyword"."id", "main_keyword"."keyword_name", "main_keyw...
^
IMO, from the error message, the models seem to be registered in the admin.py.
Delete the code in admin.py and try the migration again.

How to use 'User' as foreign key in Django 1.5

I have made a custom profile model which looks like this:
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.ForeignKey('User', unique=True)
name = models.CharField(max_length=30)
occupation = models.CharField(max_length=50)
city = models.CharField(max_length=30)
province = models.CharField(max_length=50)
sex = models.CharField(max_length=1)
But when I run manage.py syncdb, I get:
myapp.userprofile: 'user' has a relation with model User, which has
either not been installed or is abstract.
I also tried:
from django.contrib.auth.models import BaseUserManager, AbstractUser
But it gives the same error. Where I'm wrong and how to fix this?
Exactly in Django 1.5 the AUTH_USER_MODEL setting was introduced, allowing using a custom user model with auth system.
If you're writing an app that's intended to work with projects on Django 1.5 through 1.10 and later, this is the proper way to reference user model (which can now be different from django.contrib.auth.models.User):
class UserProfile(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
See docs for more details.
In case you're writing a reusable app supporting Django 1.4 as well, then you should probably determine what reference to use by checking Django version, perhaps like this:
import django
from django.conf import settings
from django.db import models
def get_user_model_fk_ref():
if django.VERSION[:2] >= (1, 5):
return settings.AUTH_USER_MODEL
else:
return 'auth.User'
class UserProfile(models.Model):
user = models.ForeignKey(get_user_model_fk_ref())
Change this:
user = models.ForeignKey('User', unique=True)
to this:
user = models.ForeignKey(User, unique=True)

Categories