Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Django Rest Framework Simple JWT getting anonymous user #30

Open
devhusnain opened this issue Mar 26, 2022 · 1 comment
Open

Django Rest Framework Simple JWT getting anonymous user #30

devhusnain opened this issue Mar 26, 2022 · 1 comment

Comments

@devhusnain
Copy link

devhusnain commented Mar 26, 2022

  • django_private_chat2 version: 1.0.2
  • Django version: 4.0.1
  • Python version: 10.0
  • Operating System: Win 10

Description

I want to use Rest Framework simpleJWT as authentication earlier I was using Django default authentication. Here are views currently I am getting AnonymousUser error, what changes do I need to get a user request from JWT Authenticated user. I want to get a request.user from a jWT Authenticated user. Please help me out.

Here are views

class MessagesModelList(ListView):
http_method_names = ['get', ]
paginate_by = getattr(settings, 'MESSAGES_PAGINATION', 500)

def get_queryset(self):
    if self.kwargs.get('dialog_with'):
        qs = MessageModel.objects \
            .filter(Q(recipient=self.request.user, sender=self.kwargs['dialog_with']) |
                    Q(sender=self.request.user, recipient=self.kwargs['dialog_with'])) \
            .select_related('sender', 'recipient')
    else:
        qs = MessageModel.objects.filter(Q(recipient=self.request.user) |
                                         Q(sender=self.request.user)).prefetch_related('sender', 'recipient', 'file')

    return qs.order_by('-created')

def render_to_response(self, context, **response_kwargs):
    user_pk = self.request.user.pk
    data = [serialize_message_model(i, user_pk)
            for i in context['object_list']]
    page: Page = context.pop('page_obj')
    paginator: Paginator = context.pop('paginator')
    return_data = {
        'page': page.number,
        'pages': paginator.num_pages,
        'data': data
    }
    return JsonResponse(return_data, **response_kwargs)

class DialogsModelList(ListView):

http_method_names = ['get', ]
paginate_by = getattr(settings, 'DIALOGS_PAGINATION', 20)

def get_queryset(self):
    qs = DialogsModel.objects.filter(Q(user1_id=self.request.user.pk) | Q(user2_id=self.request.user.pk)) \
        .select_related('user1', 'user2')
    return qs.order_by('-created')

def render_to_response(self, context, **response_kwargs):
    # TODO: add online status
    user_pk = self.request.user.pk
    data = [serialize_dialog_model(i, user_pk)
            for i in context['object_list']]
    page: Page = context.pop('page_obj')
    paginator: Paginator = context.pop('paginator')
    return_data = {
        'page': page.number,
        'pages': paginator.num_pages,
        'data': data
    }
    return JsonResponse(return_data, **response_kwargs)


class SelfInfoView(DetailView):

def get_object(self, queryset=None):
    return self.request.user

def render_to_response(self, context, **response_kwargs):
    user: AbstractBaseUser = context['object']
    data = {
        "username": user.get_username(),
        "pk": str(user.pk)
    }
    return JsonResponse(data, **response_kwargs)

class UploadView(CreateView):
http_method_names = ['post', ]
model = UploadedFile
form_class = UploadForm

def form_valid(self, form: UploadForm):
    self.object = UploadedFile.objects.create(
        uploaded_by=self.request.user, file=form.cleaned_data['file'])
    return JsonResponse(serialize_file_model(self.object))

def form_invalid(self, form: UploadForm):
    context = self.get_context_data(form=form)
    errors_json: str = context['form'].errors.get_json_data()
    return HttpResponseBadRequest(content=json.dumps({'errors': errors_json}))
@acfuns
Copy link

acfuns commented Apr 27, 2022

I meet this problem, My solution is (:
add APIView and inherit it

from rest_framework.views import APIView
...

class DialogsModelList(ListView, APIView):
    http_method_names = ['get', ]
    paginate_by = getattr(settings, 'DIALOGS_PAGINATION', 20)

    def get_queryset(self):
        qs = DialogsModel.objects.filter(Q(user1_id=self.request.user.pk) | Q(user2_id=self.request.user.pk)) \
            .select_related('user1', 'user2')
        return qs.order_by('-created')

    def render_to_response(self, context, **response_kwargs):
        # TODO: add online status
        user_pk = self.request.user.pk
        print(self.request.user)
        data = [serialize_dialog_model(i, user_pk) for i in context['object_list']]
        page: Page = context.pop('page_obj')
        paginator: Paginator = context.pop('paginator')
        return_data = {
            'page': page.number,
            'pages': paginator.num_pages,
            'data': data
        }
        return JsonResponse(return_data, **response_kwargs)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants