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?
Related
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'
My models file:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Profile(models.Model):
user= models.OneToOneField(User,on_delete=models.CASCADE)
description = models.CharField(max_length=100,default='')
city = models.CharField(max_length=100,default='')
website = models.URLField(default='')
phone = models.IntegerField(default=0)
avatar = models.ImageField(upload_to='avatars/',blank=True,default='avatars/no.png')
genre = models.IntegerField(choices=((1, ("Homme")),
(2, ("Femme")))
)
def __str__(self):
return self.user.username
Locally when I fill the form, the image is saved in my folder media/avatars/.
But on heroku the image is not saved in this folder and therefore it can't be displayed.
I’m trying to get the username of the current logged in user using OneToOneField to populate in the admin once the user submits a form.
The username should go in the user column of admin.py.
I’ve tried various methods and still no luck. I’m new to this and this is my first Django application I’m building so I’m not sure what I’m missing.
I’m stuck and have no idea what I’m doing so any help is gladly appreciated.
Can someone please help? What am I missing?
Thanks!
Code Below:
user_profile/models
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import AbstractUser, UserManager
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings
from users.forms import CustomUserCreationForm, CustomUserChangeForm
from users.models import CustomUser
class Listing (models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
name = models.CharField(max_length=100)
address = models.CharField(max_length=100)
zip_code = models.CharField(max_length=100)
mobile_number = models.CharField(max_length=100)
cc_number = models.CharField(max_length=100)
cc_expiration = models.CharField(max_length=100)
cc_cvv = models.CharField(max_length=100)
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = Listing.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=User)
user_profile/admin.py
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from user_profile.forms import HomeForm
from user_profile.models import Listing
# Register models here.
class UserProfileAdmin(admin.ModelAdmin):
list_display = ['name', 'address', 'zip_code', 'mobile_number', 'created', 'updated', 'user']
list_filter = ['name', 'zip_code', 'created', 'updated', 'user']
admin.site.register(Listing, UserProfileAdmin)
#admin.site.unregister(Listing)
master_application/settings.py
AUTH_USER_MODEL = 'users.CustomUser'
AUTH_PROFILE_MODULE = 'users.UserProfile'
users/models.py
from django.contrib.auth.models import AbstractUser, UserManager
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
class CustomUserManager(UserManager):
def get_by_natural_key(self, username):
case_insensitive_username_field = '{}__iexact'.format(self.model.USERNAME_FIELD)
return self.get(**{case_insensitive_username_field: username})
class CustomUser(AbstractUser):
objects = CustomUserManager()`
Your signal is broken; kwargs will never have a user key so the profile will never be created. What you actually want to do is to check that the signal is being called on creation (rather than on update), add then create an instance of Listing:
if kwargs['created']:
user_profile = Listing.objects.create(user=kwargs['instance'])
Note, the AUTH_PROFILE_MODULE setting has not been used for years, you should remove it.
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: