I'm following a tutorial on Django in Python, I'm trying to add a bio to my user profile page, however I get this error:
OperationalError at /admin/users/profile/
no such column: users_profile.bio
Here is my models.py file:
from django.contrib.auth.models import User
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
bio = models.TextField(User)
def __str__(self):
return f'{self.user.username} Profile'
Here is my admin.py file:
from django.contrib import admin
from .models import Profile
# Register your models here.
admin.site.register(Profile)
Just change def __str(self):
def __str__(self):
return str(self.user.user)
OR
def __str__(self):
return 'Check if it is the problem'
Related
I created a Django API to create a new user. However, when I try to create a user I get the error message:
IntegrityError at /api/v1/users/register/ NOT NULL constraint failed: accounts_user.user_id
This is what I have in models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class User(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=100, blank=True)
location = models.CharField(max_length=100, blank=True)
password = models.CharField(max_length=32)
email = models.EmailField(max_length=150)
signup_confirmation = models.BooleanField(default=False)
def __str__(self):
return self.user.username
#receiver(post_save, sender=User)
def update_profile_signal(sender, instance, created, **kwargs):
if created:
User.objects.create(user=instance)
instance.profile.save()
In serializers.py
from rest_framework import serializers
from .models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('user_id', 'name', 'location', 'password', 'email', 'signup_confirmation')
and my views.py
from rest_framework import viewsets
from .serializers import UserSerializer
from .models import User
from rest_framework.decorators import action
from .forms import SignUpForm
from .tokens import account_activation_token
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all().order_by('name')
serializer_class = UserSerializer
#action (detail=True, methods=['post'])
def register(self, request):
print(request)
Any ideas on what I can do to resolve this error
As John wrote in a comment:
Here you have a problem: fields = ('user_id',...).
I also advise you to change your User model. If you don't need separating (I suppose you don't), it is way better to create your User with inheritance directly from AbstractUser instead of creating in fact doubled User models.
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
...
In this way you will already have username, password and email, but you can add anything else in same model, instead of using user.user etc.
I'm building a blog on Django and know i have to make a personal page for see all the posts published by the user we're logged in now.
I'm using some querysets so.
Her my code
my models.py
from django.db import models
from django.conf import settings
from django.utils import timezone
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
Here my forms.py
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
from .models import Post
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username','email','password1','password2','user_permissions','is_staff','date_joined']
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'text', 'author']
And that's the view which is gonna filter the posts in base of the logged user
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from .forms import CreateUserForm
from .models import Post
from .forms import PostForm
def user_data(request, pk):
user_data = User.objects.get(pk=pk)
posts = user_data.post_set.filter(author=user_data)
context = {'user_data':user_data, 'posts':posts}
return render(request, 'account/user_data.html', context)
#So it returns me just the user data like name, email or date_joined but not his posts
This should give you posts of logged in users from your view
def user_data(request, pk):
posts=Post.objects.filter(author=request.user)
context = {'posts':posts}
return render(request, 'account/user_data.html', context)
Using the Stripe API to create a credit card checkout form on my website.
I am trying to test the following line in my view.py of the app checkout.
print (request.user.userStripe.stripe_id)
It could be the way my Users is set up.. I tried importing the models from the user app. I just don't understand why it can't see it.
I have two apps: users and checkout
I am the following error in the debug page
AttributeError at /checkout/
'User' object has no attribute 'userStripe'
Request Method: GET
Request URL: http://127.0.0.1:8000/checkout/
Django Version: 1.11
Exception Type: AttributeError
Exception Value:
'User' object has no attribute 'userStripe'
Exception Location: /home/dominic/Desktop/Projects/decentraland/website/manaland/manaland/env/lib/python3.4/site-packages/django/utils/functional.py in inner, line 239
Python Executable: /home/dominic/Desktop/Projects/decentraland/website/manaland/manaland/env/bin/python
Python Version: 3.4.3
Python Path:
['/home/dominic/Desktop/Projects/decentraland/website/manaland/manaland',
'/home/dominic/Desktop/Projects/decentraland/website/manaland/manaland/env/lib/python3.4',
'/home/dominic/Desktop/Projects/decentraland/website/manaland/manaland/env/lib/python3.4/plat-x86_64-linux-gnu',
'/home/dominic/Desktop/Projects/decentraland/website/manaland/manaland/env/lib/python3.4/lib-dynload',
'/usr/lib/python3.4',
'/usr/lib/python3.4/plat-x86_64-linux-gnu',
'/home/dominic/Desktop/Projects/decentraland/website/manaland/manaland/env/lib/python3.4/site-packages']
Server time: Mon, 2 Jul 2018 22:38:35 +0000
checkout.views.py
from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from users.models import User, profile, userStripe
from django.views import generic
from django.views.generic import CreateView
#TODO UPDATE WITH LIVE VERISON FOR STRIPE API KEYS
import stripe
stripe.api_key = settings.STRIPE_SECRET_KEY
# Create your views here.
#login_required
def checkout(request):
publishKey = settings.STRIPE_PUBLISHABLE_KEY
print (request.user.userStripe.stripe_id)
if request.method == 'POST':
token = request.POST['stripeToken']
# Token is created using Checkout or Elements!
# Get the payment token ID submitted by the form:
try:
charge = stripe.Charge.create(
amount=999,
currency='usd',
description='Example charge',
source=token,
)
except stripe.error.CardError as e:
pass
context = {'publishKey': publishKey}
template = 'checkout/checkout.html'
return render(request, template, context)
users.models.py
from django.contrib.auth.models import AbstractUser
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from allauth.account.signals import user_logged_in, user_signed_up
import stripe
stripe.api_key = settings.STRIPE_SECRET_KEY
#python_2_unicode_compatible
class User(AbstractUser):
# First Name and Last Name do not cover name patterns
# around the globe.
name = models.CharField(_('Name of User'), blank=True, max_length=255)
bio = models.CharField( blank=True, max_length=255)
image = models.ImageField(null=True, blank=True)
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse('users:detail', kwargs={'username': self.username})
class profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
description = models.CharField( blank=True, max_length=255)
image = models.ImageField(null=True, blank=True)
def __str__(self):
return self.user.username
class userStripe(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL)
stripe_id = models.CharField(max_length=200, null=True, blank=True)
def __unicode__(self):
if self.stripe_id:
return str(self.stripe_id)
else:
return self.user.username
def stripeCallback(sender, request, user, **kwargs):
user_stripe_account, created = userStripe.objects.get_or_create(user=user)
if created:
print ('created for %s'%(user.username))
if user_stripe_account.stripe_id is None or user_stripe_account.stripe_id == '':
new_stripe_id = stripe.Customer.create(email=user.email)
user_stripe_account.stripe_id = new_stripe_id['id']
user_stripe_account.save()
def profileCallback(sender, request, user, **kwargs):
userProfile, is_created = profile.objects.get_or_create(user=user)
if is_created:
userProfile.name = user.username
userProfile.save()
user_logged_in.connect(stripeCallback)
user_signed_up.connect(profileCallback)
user_signed_up.connect(stripeCallback)
You should use lowercase model name, print(request.user.userstripe.stripe_id).
Better set related_name in your OneToOneField so you will know exactly how to access userStripe from user.
class userStripe(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='user_stripe')
...
print(request.user.user_stripe.stripe_id)
Use request.user.userStripe.stripe_id.
You are using request.User. Instead you have to use: request.user.
you miss typing userStripe in print (request.user.userStripe.stripe_id)
try write userstripe :
print (request.user.userstripe.stripe_id)
it worked for me very nice
I'm trying to add additional field for user's profile which can be edited only by administrator.
When I try to save a new value of city in an administration module I'm getting an error:
global name 'created' is not defined
This error comes from:
signals.py in create_profile, line 7
I described what I have done till now :)
I started a new app profil
In models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils.encoding import smart_str
class UserProfile(models.Model):
"""Model przechowujący dodatkowe informacje o użytkowniku"""
user = models.ForeignKey(User, unique=True)
city = models.CharField(max_length=255, verbose_name=u'Miasto', blank=True, null=True)
class Meta:
verbose_name = 'Profil użytkownika'
verbose_name_plural = 'Profile użytkowników'
def __unicode__(self):
return u'%s' self.user.username
def __str__(self):
return smart_str('%s' % self.user.username)
import profil.signals
In file: signals.py
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from profil.models import UserProfile
def create_profile(sender, instance, **kwargs):
if created == True:
UserProfile.objects.get_or_create(user=instance)
post_save.connect(create_profile, sender=User)
forms.py
from django import forms
from profil.models import UserProfile
class UserProfileForm(forms.ModelForm):
'''Formularz modelu UserProfile'''
class Meta:
model = UserProfile
admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from profil.forms import UserProfileForm
from profil.models import UserProfile
class UserProfileInline(admin.StackedInline):
model = UserProfile
fk_name = 'user'
max_num = 1
form = UserProfileForm
class UserProfileAdmin(UserAdmin):
inlines = [UserProfileInline, ]
admin.site.unregister(User)
admin.site.register(User, UserProfileAdmin)
In your signals.py you are using created but is not defined yet.
So, you can get it from kwargs using this kwargs.get('created')
Fianlly, you create_profile function should looks like this.
def create_profile(sender, instance, **kwargs):
if kwargs.get('created',None):
UserProfile.objects.get_or_create(user=instance)
You can use:
def create_profile(sender, instance, **kwargs):
if kwargs.get('created', False) ...
or
def create_profile(sender, instance, created, **kwargs):
if created == True:
I am programming in Django 1.5 with Python 2.7 on Windows Vista. I am trying to create user profiles. However, when
I visit localhost:8000/admin/home/userprofile, I got the 1146, "Table 'demo.home_userprofile' doesn't exist error.
Now I have in settings.py:
AUTH_PROFILE_MODULE = 'home.userProfile'
and in models.py, where I have the defining values
from django.db import models
from django.contrib.auth.models import User
class userProfile(models.Model):
user = models.OneToOneField(User)
photo = models.ImageField(upload_to = url)
telefono = models.CharField(max_length = 30)
def url(self, filename):
ruta = "MultimediaData/Users/$s/%s"%(self.user.username, filename)
return ruta
def __unicode__(self):
return self.user.username
and in admin.py:
from django.contrib import admin
from demo.apps.home.models import userProfile
admin.site.register(userProfile)
I have been mulling this over for a while now. What seems to be wrong?