I have created a profile-model to extend the default django user (using django 1.6) But I can't save the profile-model correctly.
Here is my model:
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User)
mobilephone = models.CharField(max_length=20, blank=True)
Here is my celery-task which updates personrecords from a wdsl file:
@task()
def update_local(user_id):
url = 'http://webservice.domain.com/webservice/Person.cfc?wsdl'
try:
#Make SUDS.Client from WSDL url
client = Client(url)
except socket.error, exc:
raise update_local.retry(exc=exc)
except BadStatusLine, exc:
raise update_local.retry(exc=exc)
#Make dict with parameters for WSDL query
d = dict(CustomerId='xxx', Password='xxx', PersonId=user_id)
try:
#Get result from WSDL query
result = client.service.GetPerson(**d)
except (socket.error, WebFault), exc:
raise update_local.retry(exc=exc)
except BadStatusLine, exc:
raise update_local.retry(exc=exc)
#Soup the result
soup = BeautifulSoup(result)
#Firstname
first_name = soup.personrecord.firstname.string
#Lastname
last_name = soup.personrecord.lastname.string
#Email
email = soup.personrecord.email.string
#Mobilephone
mobilephone = soup.personrecord.mobilephone.string
#Get the user
django_user = User.objects.get(username__exact=user_id)
#Update info to fields
if first_name:
django_user.first_name = first_name.encode("UTF-8")
if last_name:
django_user.last_name = last_name.encode("UTF-8")
if email:
django_user.email = email
django_user.save()
#Get the profile
profile_user = Profile.objects.get_or_create(user=django_user)
if mobilephone:
profile_user.mobilephone = mobilephone
profile_user.save()
The django_user.save()
is working fine, but the profile_user.save()
is not working. Im getting this error: AttributeError: 'tuple' object has no attribute 'mobilephone'
Anyone see what Im doing wrong?
I have found 2 bugs in your code:
get_or_create
method returns tuple (objects, created), so you have to change your code to:
profile_user = Profile.objects.get_or_create(user=django_user)[0]
or, if you need information about state of returned object (just created or not) you should use
profile_user, created = Profile.objects.get_or_create(user=django_user)
and then rest of code will work correctly.
In your profile model the field models.CharField
must have max_length
argument declared.
You don't need to use ()
in @task
decorator. You only have to do this if you pass arguments to the decorator.
Also you can avoid build user profile with one to one database connection using django custom user model.
Hope this helps.