#ascount=request.user in Serializer

50 messages · Page 1 of 1 (latest)

chilly vortex
#

This would be done in the view or ViewSet by filtering the queryset.
Also it's best practice to list the fields on the Serializer explicitly.

chilly pine
chilly vortex
#

Ok let's reframe this. A serializer defines how some data should get serialised or deserialized. Wherever the Serializer is then used is where the filtering for a specific user should occur. Typically this is in views for the common use case of DRF.

chilly pine
#

I did this

class HubriseOrderViewSet(viewsets.ModelViewSet):

    def test(request):
        serializers_class = HubriseOrderSerializer
        queryset = HubriseOrder.objects.all().filter(ascount=request.user)
chilly vortex
#

Well the logic is correct but it's not in the right method.

If you look at the ModelViewSet at cdrf.co the method to override is get_queryset

#

If you are using class based views or ViewSets then you need to override the right methods otherwise your code will just be ignored.

chilly pine
#

I found this example

def get_queryset(self):
        """
        Get the list of items for this view.
        This must be an iterable, and may be a queryset.
        Defaults to using `self.queryset`.

        This method should always be used rather than accessing `self.queryset`
        directly, as `self.queryset` gets evaluated only once, and those results
        are cached for all subsequent requests.

        You may want to override this if you need to provide different
        querysets depending on the incoming request.

        (Eg. return a list of items that is specific to the user)
        """
        assert self.queryset is not None, (
            "'%s' should either include a `queryset` attribute, "
            "or override the `get_queryset()` method."
            % self.__class__.__name__
        )

        queryset = self.queryset
        if isinstance(queryset, QuerySet):
            # Ensure queryset is re-evaluated on each request.
            queryset = queryset.all()
        return queryset

#

this is the example you are telling me about

chilly vortex
#

Correct so you can override this method with something like:

def get_queryset(self):
    return HibriseOrder.objects.filter(account=self.request.user)
chilly pine
#

I tried this, but it doesn't work on my template, there is data for each user displayed

chilly vortex
#

What is your full viewset right now?

chilly pine
#

I'm not sure that the views plays a role, because when I remove my class from the views the data remains

chilly vortex
#

They definitely do.

chilly pine
#
class HubriseOrderConsumer(ListModelMixin, GenericAsyncAPIConsumer):

    queryset = HubriseOrder.objects.all()
    serializer_class = HubriseOrderSerializer
    permissions = (permissions.AllowAny,)

    async def connect(self, **kwargs):
        await self.model_change.subscribe()
        await super().connect()

    @model_observer(HubriseOrder)
    async def model_change(self, message, observer=None, **kwargs):
        await self.send_json(message)

    @model_change.serializer
    def model_serialize(self, instance, action, **kwargs):
        return dict(data=HubriseOrderSerializer(instance=instance).data, action=action.value)
#

queryset = HubriseOrder.objects.all() here

chilly vortex
#

As I said it depends on where you want to filter the data, if it's in your consumer then fine it would be there. But I doubt you have access to the current user at that point?

chilly pine
#

the endpoint is on my html no?

chilly vortex
#

I am not very familiar with websockets ... But yes you will likely have a request object

chilly pine
#

I made this

class HubriseOrderConsumer(ListModelMixin, GenericAsyncAPIConsumer):

    def get_queryset(request, **kwargs):
        return HubriseOrder.objects.filter(ascount=request.user)

but it tells me, AttributeError: 'HubriseOrderConsumer' object has no attribute 'user'

#

there is no way to recover the user login?

chilly vortex
#

def get_queryset(request, **kwargs): doesn't pass request in as an argument

#
class HubriseOrderConsumer(ListModelMixin, GenericAsyncAPIConsumer):

    def get_queryset(self, **kwargs):
        return HubriseOrder.objects.filter(ascount=self.request.user)
chilly pine
#

AttributeError: 'HubriseOrderConsumer' object has no attribute 'request'

#

😅

#

I replaced

chilly vortex
#

Well it looks like you are using Django Channels as a basis here. So how in Channels do you access the request object?

chilly pine
#

thanks to the serializer

class HubriseOrderConsumer(ListModelMixin, GenericAsyncAPIConsumer):

    queryset = HubriseOrder.objects.all()
    serializer_class = HubriseOrderSerializer
    permissions = (permissions.AllowAny,)

    async def connect(self, **kwargs):
        await self.model_change.subscribe()
        await super().connect()

    @model_observer(HubriseOrder)
    async def model_change(self, message, observer=None, **kwargs):
        await self.send_json(message)

    @model_change.serializer
    def model_serialize(self, instance, action, **kwargs):
        return dict(data=HubriseOrderSerializer(instance=instance).data, action=action.value)
chilly vortex
#

?

chilly pine
#

no ?

chilly vortex
#

What is the question?

chilly pine
#

I recover the objects using the Serializer

chilly vortex
#

Ok... but to go back to your original query of filtering by the user the following line:

queryset = HubriseOrder.objects.all()

means you are considering every object. This needs to be filtered with something like this:

class HubriseOrderConsumer(ListModelMixin, GenericAsyncAPIConsumer):

    def get_queryset(self, **kwargs):
        return HubriseOrder.objects.filter(ascount=self.request.user)

This would work with a normal view(set), but since your using websockets, specifically Django channels your next challenge/question is to work out how to get the current user on the request that has come through the websocket (this assumes that the websocket is authenticated and has a user attached to it)

chilly pine
#

I see, it's going to be quite complicated I don't know enough about websockets

chilly vortex
#

Well django channels probably provides a good abstraction to all this, but I haven't used it myself so don't know the answer. I would be looking that documentation and if that doesn't help jumping into the source code if needed.

#

I have also provided a clear goal for you to aim for.

chilly pine
#

I changed the solution I went to Htmx to load my data

#

thank you for everything

chilly pine
#

I will try it but I don't see how to apply it to my consumers

chilly vortex
#

This is how software development works. not everything you come across is going to be nice and easy, it requires thought, trial and error, reading and understanding.

#

Have you also looked at the documentation for GenericAsyncAPIConsumer?

chilly vortex
#

That would also be a place to start...

chilly pine
#

I understood how to do it, but when I print self.user = self.scope["user"] it returns an AnonymousUser

chilly vortex
#

Well done! Now you need to ensure your consumer is authenticated

chilly pine