django-piston add value foreign key

I'm trying to insert from REST API Django-piston a new value on my database.

I have the follow models

class Mobile_User(models.Model):
id       = models.CharField(primary_key=True, max_length=255, unique=True)
email    = models.EmailField()
name     = models.CharField(max_length=300)

def __unicode__(self):
    return u"%s - %s" % (self.id, self.email)

class Mobile_User_Business(models.Model):
mobile_user_id = models.ForeignKey(Mobile_User)
business_id = models.ForeignKey(Business)

def __unicode__(self):
    return u"%s - %s" % (self.business_id, self.mobile_user_id)

and handlers.py

def create(self, request):
    """
    Creates a new Mobile_User.
    """
    if not hasattr(request, "data"):
        request.data = request.POST
    attrs = self.flatten_dict(request.data)
    if self.exists(**attrs):
        msj = "The user mobile already exist"
        return msj
    else:
        mobile_user_business = Mobile_User_Business(mobile_user_id=attrs['mobile_user_id'], 
                        business_id=attrs['business_id'],)
        mobile_user_business.save()
        return mobile_user_business

for send the information:

curl -u myuser:12345 -X POST -d mobile_user_id="21221212" -d business_id="1" http://mydomain.com/api/newuser/

and that returns:


Traceback (most recent call last):

File "/dir/www/djangotest/apps/api/handlers.py", line 122, in create business_id=attrs['business_id'],)

File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 352, in init setattr(self, field.name, rel_obj)

File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py", line 331, in set self.field.name, self.field.rel.to._meta.object_name))

ValueError: Cannot assign "u'21221212'": "Mobile_User_Business.mobile_user_id" must be a "Mobile_User" instance.


Any idea??

Thanks!

Answers


That's because you are trying to assign a unicode value to mobile_user_id, but django expects a Mobile_User instance instead.

You should change it to something like this:

...
else:
    # First get the instances
    mobile_user = Mobile_User.objects.get(pk=attrs['mobile_user_id'])
    business = Business.objects.get(pk=attrs['business_id'])

    # Then use them in this model
    mobile_user_business = Mobile_User_Business(mobile_user_id=mobile_user, 
                    business_id=business,)
    mobile_user_business.save()
    return mobile_user_business

Need Your Help

Converting Win16 C code to Win32

c windows winapi 16-bit

In general, what needs to be done to convert a 16 bit Windows program to Win32? I'm sure I'm not the only person to inherit a codebase and be stunned to find 16-bit code lurking in the corners.