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!
Related
I'm getting this error.
ERRORS: subscriptions.StripeCustomer.user: (fields.E301) Field defines
a relation with the model 'auth.User', which has been swapped out.
HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'.
I'm trying to configure Django Stripe Subscriptions following this manual https://testdriven.io/blog/django-stripe-subscriptions/
My models.py
from django.contrib.auth.models import User
from django.db import models
class StripeCustomer(models.Model):
user = models.OneToOneField(to=User, on_delete=models.CASCADE)
stripeCustomerId = models.CharField(max_length=255)
stripeSubscriptionId = models.CharField(max_length=255)
def __str__(self):
return self.user.username
My admin.py
from django.contrib import admin
from subscriptions.models import StripeCustomer
admin.site.register(StripeCustomer)
My settings.py
#used for django-allauth
AUTH_USER_MODEL = 'accounts.CustomUser'
DEFAULT_AUTO_FIELD='django.db.models.AutoField'
SITE_ID = 1
AUTHENTICATION_BACKENDS = (
'allauth.account.auth_backends.AuthenticationBackend',
'django.contrib.auth.backends.ModelBackend',
)
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
ACCOUNT_EMAIL_VERIFICATION = "none"
accounts/models.py
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
class Meta:
verbose_name_plural = 'CustomUser'
After setting above, I executed "python manage.py makemigrations && python manage.py migrate" then the error occurred.
I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you
You have your OneToOneField pointing to the User model from django.contrib.auth when in fact you are using a custom user model CustomUser, hence you get the error. Generally if one wants to have a foreign key or any related field with the user model one should point it to settings.AUTH_USER_MODEL as described in the Referencing the User model [Django docs] so that such issues can be prevented easily. Hence change your StripeCustomer model like so:
from django.conf import settings
from django.db import models
class StripeCustomer(models.Model):
user = models.OneToOneField(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
stripeCustomerId = models.CharField(max_length=255)
stripeSubscriptionId = models.CharField(max_length=255)
def __str__(self):
return self.user.username
How fix this? This after when i create new post and when i press button 'add'
It looks like your post is mostly code; please add some more details. Why stackoverflow ask this?
#models.py
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=255)
author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
content = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now= True)
def __str__(self):
return self.title
#admin.py
from django.contrib import admin
from .models import Post
class PostAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',), }
admin.site.register(Post,PostAdmin)
Maybe you forgot to use management commands, makemigrations and migrate after removing status field from your Post model. As far as I can see you don't have status field in your model but this field is still exists in your database. So make sure that field is properly removed from your database by using these management commands (makemigrations and migrate) or if your data is not important you can do the following procedure:
a- Drop your database and create new one
b- Remove all migration files
c- Run manage.py makemigrations and manage.py migrate
I want to add Mobile filed to be saved to auth_user table when i register.
models.py
from django.db import models
from django.contrib.auth.models import User
class UserRegModel(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
mobile = models.CharField(max_length=100)
forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserRegisterForm(UserCreationForm):
mobile = forms.CharField(max_length=15)
class Meta:
model = User
fields = ['username','email','mobile','password1','password2']
If you want to store all user data together, you should substitute a user model instead of creating a OneToOne relationship. Judging by the current code you will get 2 tables - one for standard Django user and one connected to it with mobile data.
Here you can read more about substituting a user and the difference between these 2 approaches:
Extending the User model with custom fields in Django
Or directly in the documentation:
https://docs.djangoproject.com/en/dev/topics/auth/customizing/#substituting-a-custom-user-model
Click here for the first image
Click here for the second image
Do this and type these codes in terminal
python manage.py makemigrations
python manage.py migrate
I have added one extra custom field phone to Django user authentication. Till then it worked properly. Later I added one more custom field called permissions. After that I am facing an error message when I try to access the admin page. Here is my model.py code
from django.contrib.auth.models import User
from django.db import models
class UserProfile(models.Model):
# This line is required. Links UserProfile to a User model instance.
user = models.OneToOneField(User)
class Meta:
permissions = (
("ssc_1","can access ssc locked questions"),
)
# The additional attributes we wish to include.
phone = models.CharField(max_length =20)
permission = models.IntegerField()
# Override the __unicode__() method to return out something meaningful!
def __unicode__(self):
return self.user.username
I have followed this stackoverflow answer, when I issue python manage.py migrate command, I am getting this error message
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: table "users_userprofile" already exists
Note : My Django versions is 1.6.6
Thanks
Migrations were introduced only in django 1.7. Until then south was being used to handle migrations
I am getting an error when I try to extend user profile using django-allauth
Exception Type: IntegrityError at /accounts/signup/
Exception Value: workerapp_userprofile.user_id may not be NULL
This is my models.py in my workerapp app of my django project where I am asking for two additional fields along with other signup information.
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
# This line is required. Links UserProfile to a User model instance.
user = models.OneToOneField(User, unique=True)
# The additional attributes we wish to include.
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images', blank=True)
# Override the __unicode__() method to return out something meaningful!
def __unicode__(self):
return self.user.username
My user is saving correctly which I can see in the admin, it's just the showing this error during the signup.