Whoa...where'd Stock come from? :-D

First off, the line where you create user_obj isn't needed. The user object
in request.user is already the populated User object. You can either use
request.user directly, or you could do user_obj = request.user.

Secondly, I don't think this is working the way you think it is. Yes, it
successfully saved, but now I believe you have incorrect data.

Your 'address_obj' is actually a Stock object, and not an Address object.
Your UserPref model doesn't show any relation to Stock unless you don't
have the full model shown.

What you're doing is grabbing a Stock object, with a
symbol=request.data['address']. You're then assigning the PK of the Stock
object *as if it were* an Address object. That is almost certain to be a
different PK than the Address object you intended. If you looked back at
that UserPrefs object now, I'm guessing that it will display the wrong
address.

I believe the reason that you aren't seeing the necessary data is because
it isn't validating properly. Data that doesn't validate properly won't
show in validated_data (at least I'm assuming so, since it should work the
same way as ModelForms and cleaned_data). Using request.data instead of
serializer.validated_data means that you are using the raw values that were
POSTed, and haven't been checked (and...well, validated) in any way. This
is a bad idea.


Honestly, there shouldn't be a reason for any of this code. I'm not sure
how Stock fits in to any of this, I get the feeling I've only seen a
portion of the relevant code, so my context here may be a bit skewed.

I actually broke down and made a quick version of your
model/serializer/view using DRF to make sure I was leading you in the
correct direction. Here is a complete copy of the code I wrote (some minor
modifications):


class Address(models.Model):
    # no idea what this model looked like, just made something simple
    name = models.CharField(max_length=250)

class UserPrefs(models.Model):

    Preferences = (
        ('0','Likes'),
        ('1','Dislikes'),
        ('2','Shared'),
        ('3','Rejected'),
    )
    user = models.ForeignKey(User)
    address = models.ForeignKey(Address)
    prefs = models.CharField(max_length=1,choices=Preferences)




class UserPrefSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserPrefs
        fields = ('id', 'address', 'prefs')




class AddToUserProfile(generics.CreateAPIView):
    serializer_class = UserPrefSerializer
    queryset = UserPrefs.objects.all()

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)




urlpatterns = [
    url(r'^addPrefs/', AddToUserProfile.as_view())
]



After spinning all of this up and running the migrations, I created a
couple of Address objects manually in the DB:

>>> from myapp.models import Address
>>> Address.objects.create(name='My Address 1')
>>> Address.objects.create(name='My Address 2')
>>> quit()

I assumed that the two addresses I just created had PK's of 1 and 2
respectively.

And I was able to successfully create UserPrefs objects with this command:

curl -H "Content-Type: application/json" -X POST -d
'{"address":"2","prefs":"0"}'
http://username:password@127.0.0.1:8000/addPrefs/

Easier than I remember from the last time I dealt with DRF a number of
years ago.

Validation works out of the box as well:

curl -H "Content-Type: application/json" -X POST -d
'{"address":"43","prefs":"0"}'
http://username:password@127.0.0.1:8000/addPrefs/
{"address":["Invalid pk \"43\" - object does not exist."]}

curl -H "Content-Type: application/json" -X POST -d
'{"address":"2","prefs":"25"}'
http://username:password@127.0.0.1:8000/addPrefs/
{"prefs":["\"25\" is not a valid choice."]}

HTH,

-James


On Tue, Jun 2, 2015 at 10:58 PM, Shekar Tippur <ctip...@gmail.com> wrote:

> James,
>
> I was able to get thro with the save operation. It was quite a bit of
> learning.
>
> Meta section on the model existed but I was not populating validated_data
> properly. I was under the assumption that
>
> when I did
>
> serializer=UserPrefSerializer(data=request.data)
>
> seriazer object will be populated with post request data.
>
> I had to resort to
>
>              address_obj=Stock.objects.get(symbol=request.data['address'])
>
>              user_obj=User.objects.get(username=request.user)
>
>             serializer.validated_data['stock_id']=address_obj.id
>
>             serializer.validated_data['user_id']=user_obj.id
>
> I am not sure if this is the optimal way to do it but this seem to have
> done the trick.
>
> Heartfelt thanks for handholding me through this.
>
> - Shekar
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users+unsubscr...@googlegroups.com.
> To post to this group, send email to django-users@googlegroups.com.
> Visit this group at http://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/452653a5-6bcc-4e48-9bd8-8d9aea866ecc%40googlegroups.com
> <https://groups.google.com/d/msgid/django-users/452653a5-6bcc-4e48-9bd8-8d9aea866ecc%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CA%2Be%2BciV52FBz9NkhPWYf4NNzWStN2ZwH1g7VkWZx-30daD5uBQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to