Home > Enterprise >  accessing self.request.user.profile in django generic views
accessing self.request.user.profile in django generic views

Time:10-03

I'm working on an API in Django rest framework and I am using generics.RetrieveUpdateAPIView here is my class:

class updateProfile(generics.RetrieveUpdateAPIView):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer

and here is my model:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=200, blank=True, null=True)
    email = models.EmailField(max_length=500, blank=True, null=True)
    username = models.CharField(max_length=200, blank=True, null=True)
    location = models.CharField(max_length=200, blank=True, null=True)
    short_intro = models.CharField(max_length=200, blank=True, null=True)
    bio = models.TextField(blank=True, null=True)
    profile_image = models.ImageField(
        null=True,
        blank=True,
        upload_to="profiles/",
        default="profiles/user-default.png",
    )
    social_github = models.URLField(
        max_length=200, blank=True, null=True, validators=[validate_url_github]
    )
    social_twitter = models.URLField(
        max_length=200, blank=True, null=True, validators=[validate_url_twitter]
    )
    social_linkedin = models.URLField(
        max_length=200, blank=True, null=True, validators=[validate_url_linkedin]
    )
    social_youtube = models.URLField(
        max_length=200, blank=True, null=True, validators=[validate_url_yt]
    )
    social_website = models.URLField(max_length=200, blank=True, null=True)
    created = models.DateTimeField(auto_now_add=True)
    id = models.UUIDField(
        default=uuid.uuid4, unique=True, primary_key=True, editable=False
    )

I want to access the request.user.profile I have tried the view as :

class updateProfile(generics.RetrieveUpdateAPIView):
    queryset = request.user.proifle //and also self.request.user.proile
    serializer_class = ProfileSerializer

how can I access the profile of the user in this class-based view

CodePudding user response:

You can override the get_object method:

class updateProfile(generics.RetrieveUpdateAPIView):
    serializer_class = ProfileSerializer

    def get_object(self):
        return self.request.user.profile
  • Related