Saturday, May 30, 2015

django - class based view store post data


I am trying to use class based view to post data.
I have come across a weird issue. It is not saving data in the backend. I get an error:
Expected view AddToUserProfile to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. 

I have searched on google to see explanation on this error but could not understand the explanation. Appreciate if someone can shed some light on this.

Here is my model:

class UserPrefs(models.Model):
Preferences = (
user = models.ForeignKey('auth.User', related_name='Hello')
name = models.ForeignKey(Stock)
value = models.CharField(max_length=20,choices=Preferences)

class Meta:
#managed = False
db_table = 'user_pref'

def save(self, *args, **kwargs):
super(Hello, self).save(*args, **kwargs)

class AddToUserProfile(generics.GenericAPIView):
permission_classes = (permissions.IsAuthenticatedOrReadOnly,IsOwnerOrReadOnly)
queryset = UserPrefs.objects.all()
serializer_class = UserPrefSerializer
lookup_fields = ('id')
def get(self, request, *args, **kwargs):
return HttpResponse('Hello there!')

def post(self, request, *args, **kwargs):
self.object = self.get_object()
context = self.get_context_data(object=self.object)
#eturn self.render_to_response(context)
def create(self, serializer):

Serializer code:

class UserPrefSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = UserPrefs
fields = ( 'owner', 'name', 'value')
depth = 1 entry:
url(r'^Hello/setPrefs', views.AddToUserProfile.as_view()),

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
To post to this group, send email to
Visit this group at
To view this discussion on the web visit
For more options, visit

No comments:

Post a Comment