RamezIssac / django-slick-reporting

The Reporting Engine for Django. Create dashboards and standalone Reports and Charts.
https://django-slick-reporting.com/
BSD 3-Clause "New" or "Revised" License
549 stars 44 forks source link

Access self.request.user #103

Open caclement opened 6 months ago

caclement commented 6 months ago

In the documentation it seems you managed to refer to self.request.user when creating customs filters.

https://django-slick-reporting.readthedocs.io/en/latest/topics/filter_form.html

    def get_filters(self):
        # return the filters to be used in the report
        # Note: the use of Q filters and kwargs filters
        filters = {}
        q_filters = []
        if self.cleaned_data["secure"] == "secure":
            filters["is_secure"] = True
        elif self.cleaned_data["secure"] == "non-secure":
            filters["is_secure"] = False
        if self.cleaned_data["method"]:
            filters["method"] = self.cleaned_data["method"]
        if self.cleaned_data["response"]:
            filters["response"] = self.cleaned_data["response"]
        if self.cleaned_data["other_people_only"]:
            q_filters.append(~Q(user=self.request.user))

However when I do it, I get an error :

    def get_filters(self):
        filters = {}
        q_filters = []
        filters["location_id"] = self.cleaned_data["location_id"]
        filters["test"] = self.request.user.email
        return q_filters, filters

The error is : AttributeError: 'ManagerForm' object has no attribute 'request'

RamezIssac commented 6 months ago

Hello, Thank you for this. Yes the documentation is missing that

  1. the form is accepting the request on its init, and attaching it to self
  2. How the view sends the request to the form

class MyReport(ReportView):
    # ....       
    def get_form_kwargs(self):
          kwargs = super().get_form_kwargs()
          kwargs["request"] = self.request # send the request as a form kwarg, as you'd do in any CBV
          return kwargs

class RequestLogForm(BaseReportForm, forms.Form):
    # ... 
    def __init__(self, request, *args, **kwargs):
        # special init signature to accept the request and attach it
        self.request = request 
        # ....
caclement commented 6 months ago

Thanks ! It works perfectly. Awsome application by the way.