We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
zmiana sposobu przewijania spraw z mailami z monitoringu
W tej chwili można przeskakiwać tylko o jedną stronę do przodu i do tyłu, a chodziłoby o to, żeby można było przeskoczyć o kilka lub na sam koniec. Jest tak:

![image](https://user-images.githubusercontent.com/36925935/37586415-8c8a566c-2b5c-11e8-9262-bccfc63bea59.png)

A lepiej jakby było tak:

![image](https://user-images.githubusercontent.com/36925935/37586480-c96e5df8-2b5c-11e8-9090-487ecbd94ed6.png)


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `feder/monitorings/views.py`
Content:
```
1 from atom.ext.guardian.forms import TranslatedUserObjectPermissionsForm
2 from atom.views import DeleteMessageMixin, UpdateMessageMixin
3 from braces.views import (FormValidMessageMixin, LoginRequiredMixin,
4                           PermissionRequiredMixin, SelectRelatedMixin,
5                           UserFormKwargsMixin, PrefetchRelatedMixin)
6 from cached_property import cached_property
7 from dal import autocomplete
8 from django.contrib import messages
9 from django.contrib.auth import get_user_model
10 from django.core.exceptions import PermissionDenied
11 from django.urls import reverse, reverse_lazy
12 from django.db.models import Count
13 from django.http import HttpResponseRedirect
14 from django.shortcuts import get_object_or_404
15 from django.utils.translation import ugettext_lazy as _
16 from django.views.generic import (CreateView, DeleteView, DetailView, FormView,
17                                   UpdateView)
18 from django_filters.views import FilterView
19 from formtools.wizard.views import SessionWizardView
20 from guardian.shortcuts import assign_perm
21 
22 from feder.cases.models import Case
23 from feder.institutions.filters import InstitutionFilter
24 from feder.institutions.models import Institution
25 from feder.letters.models import Letter
26 from feder.main.mixins import ExtraListMixin, RaisePermissionRequiredMixin
27 from .filters import MonitoringFilter
28 from .forms import (MonitoringForm, SaveTranslatedUserObjectPermissionsForm,
29                     SelectUserForm)
30 from .models import Monitoring
31 
32 
33 class MonitoringListView(SelectRelatedMixin, FilterView):
34     filterset_class = MonitoringFilter
35     model = Monitoring
36     select_related = ['user', ]
37     paginate_by = 25
38 
39     def get_queryset(self):
40         qs = super(MonitoringListView, self).get_queryset()
41 
42         if not self.request.user.is_staff:
43             qs = qs.only_public()
44 
45         return qs.with_case_count()
46 
47 
48 class MonitoringDetailView(SelectRelatedMixin, PrefetchRelatedMixin,
49                            ExtraListMixin, DetailView):
50     model = Monitoring
51     select_related = ['user', ]
52     prefetch_related = ['questionary_set', ]
53     paginate_by = 25
54 
55     def get_queryset(self):
56         qs = super(MonitoringDetailView, self).get_queryset()
57 
58         if not self.request.user.is_staff:
59             qs = qs.only_public()
60 
61         return qs
62 
63     def get_object_list(self, obj):
64         return (Case.objects.filter(monitoring=obj).
65                 select_related('institution').
66                 prefetch_related('task_set').
67                 with_record_max().
68                 with_letter().
69                 order_by('-record_max').
70                 all())
71 
72 
73 class LetterListMonitoringView(SelectRelatedMixin, PrefetchRelatedMixin, ExtraListMixin, DetailView):
74     model = Monitoring
75     template_name_suffix = '_letter_list'
76     select_related = ['user', ]
77     prefetch_related = ['questionary_set', ]
78     paginate_by = 25
79 
80     def get_object_list(self, obj):
81         return (Letter.objects.filter(record__case__monitoring=obj).
82                 select_related('record__case').
83                 with_author().
84                 attachment_count().
85                 order_by('-created').
86                 all())
87 
88 
89 class DraftListMonitoringView(SelectRelatedMixin, PrefetchRelatedMixin, ExtraListMixin, DetailView):
90     model = Monitoring
91     template_name_suffix = '_draft_list'
92     select_related = ['user', ]
93     prefetch_related = ['questionary_set', ]
94     paginate_by = 25
95 
96     def get_object_list(self, obj):
97         return (Letter.objects.filter(record__case__monitoring=obj).
98                 is_draft().
99                 select_related('record__case').
100                 with_author().
101                 attachment_count().
102                 order_by('-created').
103                 all())
104 
105 
106 class MonitoringCreateView(LoginRequiredMixin, PermissionRequiredMixin,
107                            UserFormKwargsMixin, CreateView):
108     model = Monitoring
109     template_name = 'monitorings/monitoring_form.html'
110     form_class = MonitoringForm
111     permission_required = 'monitorings.add_monitoring'
112     raise_exception = True
113     redirect_unauthenticated_users = True
114 
115     def get_form_valid_message(self):
116         return _("{0} created!").format(self.object)
117 
118     def form_valid(self, form):
119         output = super(MonitoringCreateView, self).form_valid(form)
120         default_perm = ['change_monitoring', 'delete_monitoring', 'add_questionary',
121                         'change_questionary', 'delete_questionary', 'add_case',
122                         'change_case', 'delete_case', 'add_task', 'change_task',
123                         'delete_task', 'reply', 'view_alert', 'change_alert',
124                         'delete_alert', 'manage_perm',
125                         'select_survey', 'add_draft']
126         for perm in default_perm:
127             assign_perm(perm, self.request.user, form.instance)
128         return output
129 
130 
131 class MonitoringUpdateView(RaisePermissionRequiredMixin, UserFormKwargsMixin,
132                            UpdateMessageMixin, FormValidMessageMixin, UpdateView):
133     model = Monitoring
134     form_class = MonitoringForm
135     permission_required = 'monitorings.change_monitoring'
136 
137 
138 class MonitoringDeleteView(RaisePermissionRequiredMixin, DeleteMessageMixin,
139                            DeleteView):
140     model = Monitoring
141     success_url = reverse_lazy('monitorings:list')
142     permission_required = 'monitorings.delete_monitoring'
143 
144 
145 class PermissionWizard(LoginRequiredMixin, SessionWizardView):
146     form_list = [SelectUserForm, TranslatedUserObjectPermissionsForm]
147     template_name = 'monitorings/permission_wizard.html'
148 
149     def perm_check(self):
150         if not self.request.user.has_perm('monitorings.manage_perm',
151                                           self.monitoring):
152             raise PermissionDenied()
153 
154     @cached_property
155     def monitoring(self):
156         return Monitoring.objects.get(slug=self.kwargs['slug'])
157 
158     def get_context_data(self, *args, **kwargs):
159         context = super(PermissionWizard, self).get_context_data(*args, **kwargs)
160         context['object'] = self.monitoring
161         return context
162 
163     def get_form_kwargs(self, step=None):
164         kw = super(PermissionWizard, self).get_form_kwargs(step)
165         self.perm_check()
166         if step == '1':
167             user_pk = self.storage.get_step_data('0').get('0-user')[0]
168             user = get_user_model().objects.get(pk=user_pk)
169             kw['user'] = user
170             kw['obj'] = self.monitoring
171         return kw
172 
173     def get_success_message(self):
174         return _("Permissions to {monitoring} updated!").format(monitoring=self.object)
175 
176     def done(self, form_list, *args, **kwargs):
177         form_list[1].save_obj_perms()
178         self.object = form_list[1].obj
179         messages.success(self.request, self.get_success_message())
180         url = reverse('monitorings:perm', kwargs={'slug': self.object.slug})
181         return HttpResponseRedirect(url)
182 
183 
184 class MonitoringPermissionView(RaisePermissionRequiredMixin, SelectRelatedMixin, DetailView):
185     model = Monitoring
186     template_name_suffix = '_permissions'
187     select_related = ['user', ]
188     permission_required = 'monitorings.manage_perm'
189 
190     def get_context_data(self, **kwargs):
191         context = super(MonitoringPermissionView, self).get_context_data(**kwargs)
192         context['user_list'], context['index'] = self.object.permission_map()
193         return context
194 
195 
196 class MonitoringUpdatePermissionView(RaisePermissionRequiredMixin, SelectRelatedMixin, FormView):
197     form_class = SaveTranslatedUserObjectPermissionsForm
198     template_name = 'monitorings/monitoring_form.html'
199     permission_required = 'monitorings.manage_perm'
200 
201     def get_permission_object(self):
202         return self.get_monitoring()
203 
204     def get_user(self):
205         if not getattr(self, 'user', None):
206             self.user = get_object_or_404(get_user_model(), id=self.kwargs['user_pk'])
207         return self.user
208 
209     def get_monitoring(self):
210         if not getattr(self, 'monitoring', None):
211             self.monitoring = get_object_or_404(Monitoring, slug=self.kwargs['slug'])
212         return self.monitoring
213 
214     def get_context_data(self, **kwargs):
215         context = super(MonitoringUpdatePermissionView, self).get_context_data(**kwargs)
216         context['object'] = self.get_monitoring()
217         return context
218 
219     def get_form_kwargs(self):
220         kw = super(MonitoringUpdatePermissionView, self).get_form_kwargs()
221         kw.update({'user': self.get_user(), 'obj': self.get_monitoring()})
222         return kw
223 
224     def get_success_message(self):
225         return (_("Permissions to {monitoring} of {user} updated!").
226                 format(monitoring=self.monitoring, user=self.user))
227 
228     def form_valid(self, form):
229         form.save_obj_perms()
230         messages.success(self.request, self.get_success_message())
231         url = reverse('monitorings:perm', kwargs={'slug': self.get_monitoring().slug})
232         return HttpResponseRedirect(url)
233 
234 
235 class MonitoringAssignView(RaisePermissionRequiredMixin, FilterView):
236     model = Institution
237     filterset_class = InstitutionFilter
238     permission_required = 'monitorings.change_monitoring'
239     template_name = 'monitorings/institution_assign.html'
240     paginate_by = 50
241     LIMIT = 500
242 
243     def get_limit_simultaneously(self):
244         return self.LIMIT
245 
246     def get_queryset(self):
247         qs = super(MonitoringAssignView, self).get_queryset()
248         return (qs.exclude(case__monitoring=self.monitoring.pk).
249                 with_case_count().
250                 select_related('jst'))
251 
252     def get_permission_object(self):
253         return self.monitoring
254 
255     @cached_property
256     def monitoring(self):
257         return get_object_or_404(Monitoring, slug=self.kwargs['slug'])
258 
259     def get_context_data(self, **kwargs):
260         context = super(MonitoringAssignView, self).get_context_data(**kwargs)
261         context['monitoring'] = self.monitoring
262         return context
263 
264     def get_filterset_kwargs(self, filterset_class):
265         kw = super(MonitoringAssignView, self).get_filterset_kwargs(filterset_class)
266         return kw
267 
268     def post(self, request, *args, **kwargs):
269         if not request.GET:
270             msg = _("You can not send letters without using filtering.")
271             messages.error(self.request, msg)
272             return HttpResponseRedirect(self.request.path)
273 
274         if request.POST.get('all', 'no') == 'yes':
275             qs = self.get_filterset(self.get_filterset_class()).qs
276         else:
277             ids = request.POST.getlist('to_assign')
278             qs = Institution.objects.filter(pk__in=ids)
279         qs = qs.exclude(case__monitoring=self.monitoring.pk)
280 
281         count = Case.objects.filter(monitoring=self.monitoring).count() or 0
282 
283         to_assign_count = qs.count()
284         if to_assign_count > self.get_limit_simultaneously():
285             msg = _("You can not send %(count)d letters at once. "
286                     "The maximum is %(limit)d. Use filtering.") % \
287                   {'count': to_assign_count, 'limit': self.get_limit_simultaneously()}
288             messages.error(self.request, msg)
289             return HttpResponseRedirect(self.request.path)
290 
291         for i, institution in enumerate(qs):
292             postfix = " #%d" % (i + count + 1,)
293             Letter.send_new_case(user=self.request.user,
294                                  monitoring=self.monitoring,
295                                  postfix=postfix,
296                                  institution=institution,
297                                  text=self.monitoring.template)
298         msg = _("%(count)d institutions was assigned " +
299                 "to %(monitoring)s. The requests was sent.") % \
300               {'count': to_assign_count, 'monitoring': self.monitoring}
301         messages.success(self.request, msg)
302         url = reverse('monitorings:assign', kwargs={'slug': self.monitoring.slug})
303         return HttpResponseRedirect(url)
304 
305 
306 class MonitoringAutocomplete(autocomplete.Select2QuerySetView):
307     def get_queryset(self):
308         qs = Monitoring.objects
309         if self.q:
310             qs = qs.filter(name__icontains=self.q)
311 
312         if not self.request.user.is_staff:
313             qs = qs.only_public()
314 
315         return qs.all()
316 
317 
318 class UserMonitoringAutocomplete(autocomplete.Select2QuerySetView):
319     def get_queryset(self):
320         qs = (get_user_model().objects.
321               annotate(case_count=Count('case')).
322               filter(case_count__gt=0).all())
323         if self.q:
324             qs = qs.filter(name__icontains=self.q)
325         return qs.all()
326
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/feder/monitorings/views.py b/feder/monitorings/views.py
--- a/feder/monitorings/views.py
+++ b/feder/monitorings/views.py
@@ -60,6 +60,10 @@
 
         return qs
 
+    def get_context_data(self, **kwargs):
+        kwargs['url_extra_kwargs'] = {'slug': self.object.slug}
+        return super(MonitoringDetailView, self).get_context_data(**kwargs)
+
     def get_object_list(self, obj):
         return (Case.objects.filter(monitoring=obj).
                 select_related('institution').
@@ -77,6 +81,10 @@
     prefetch_related = ['questionary_set', ]
     paginate_by = 25
 
+    def get_context_data(self, **kwargs):
+        kwargs['url_extra_kwargs'] = {'slug': self.object.slug}
+        return super(LetterListMonitoringView, self).get_context_data(**kwargs)
+
     def get_object_list(self, obj):
         return (Letter.objects.filter(record__case__monitoring=obj).
                 select_related('record__case').
@@ -93,6 +101,10 @@
     prefetch_related = ['questionary_set', ]
     paginate_by = 25
 
+    def get_context_data(self, **kwargs):
+        kwargs['url_extra_kwargs'] = {'slug': self.object.slug}
+        return super(DraftListMonitoringView, self).get_context_data(**kwargs)
+
     def get_object_list(self, obj):
         return (Letter.objects.filter(record__case__monitoring=obj).
                 is_draft().

{"golden_diff": "diff --git a/feder/monitorings/views.py b/feder/monitorings/views.py\n--- a/feder/monitorings/views.py\n+++ b/feder/monitorings/views.py\n@@ -60,6 +60,10 @@\n \n         return qs\n \n+    def get_context_data(self, **kwargs):\n+        kwargs['url_extra_kwargs'] = {'slug': self.object.slug}\n+        return super(MonitoringDetailView, self).get_context_data(**kwargs)\n+\n     def get_object_list(self, obj):\n         return (Case.objects.filter(monitoring=obj).\n                 select_related('institution').\n@@ -77,6 +81,10 @@\n     prefetch_related = ['questionary_set', ]\n     paginate_by = 25\n \n+    def get_context_data(self, **kwargs):\n+        kwargs['url_extra_kwargs'] = {'slug': self.object.slug}\n+        return super(LetterListMonitoringView, self).get_context_data(**kwargs)\n+\n     def get_object_list(self, obj):\n         return (Letter.objects.filter(record__case__monitoring=obj).\n                 select_related('record__case').\n@@ -93,6 +101,10 @@\n     prefetch_related = ['questionary_set', ]\n     paginate_by = 25\n \n+    def get_context_data(self, **kwargs):\n+        kwargs['url_extra_kwargs'] = {'slug': self.object.slug}\n+        return super(DraftListMonitoringView, self).get_context_data(**kwargs)\n+\n     def get_object_list(self, obj):\n         return (Letter.objects.filter(record__case__monitoring=obj).\n                 is_draft().\n", "issue": "zmiana sposobu przewijania spraw z mailami z monitoringu\nW tej chwili mo\u017cna przeskakiwa\u0107 tylko o jedn\u0105 stron\u0119 do przodu i do ty\u0142u, a chodzi\u0142oby o to, \u017ceby mo\u017cna by\u0142o przeskoczy\u0107 o kilka lub na sam koniec. Jest tak:\r\n\r\n![image](https://user-images.githubusercontent.com/36925935/37586415-8c8a566c-2b5c-11e8-9262-bccfc63bea59.png)\r\n\r\nA lepiej jakby by\u0142o tak:\r\n\r\n![image](https://user-images.githubusercontent.com/36925935/37586480-c96e5df8-2b5c-11e8-9090-487ecbd94ed6.png)\r\n\n", "before_files": [{"content": "from atom.ext.guardian.forms import TranslatedUserObjectPermissionsForm\nfrom atom.views import DeleteMessageMixin, UpdateMessageMixin\nfrom braces.views import (FormValidMessageMixin, LoginRequiredMixin,\n                          PermissionRequiredMixin, SelectRelatedMixin,\n                          UserFormKwargsMixin, PrefetchRelatedMixin)\nfrom cached_property import cached_property\nfrom dal import autocomplete\nfrom django.contrib import messages\nfrom django.contrib.auth import get_user_model\nfrom django.core.exceptions import PermissionDenied\nfrom django.urls import reverse, reverse_lazy\nfrom django.db.models import Count\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.views.generic import (CreateView, DeleteView, DetailView, FormView,\n                                  UpdateView)\nfrom django_filters.views import FilterView\nfrom formtools.wizard.views import SessionWizardView\nfrom guardian.shortcuts import assign_perm\n\nfrom feder.cases.models import Case\nfrom feder.institutions.filters import InstitutionFilter\nfrom feder.institutions.models import Institution\nfrom feder.letters.models import Letter\nfrom feder.main.mixins import ExtraListMixin, RaisePermissionRequiredMixin\nfrom .filters import MonitoringFilter\nfrom .forms import (MonitoringForm, SaveTranslatedUserObjectPermissionsForm,\n                    SelectUserForm)\nfrom .models import Monitoring\n\n\nclass MonitoringListView(SelectRelatedMixin, FilterView):\n    filterset_class = MonitoringFilter\n    model = Monitoring\n    select_related = ['user', ]\n    paginate_by = 25\n\n    def get_queryset(self):\n        qs = super(MonitoringListView, self).get_queryset()\n\n        if not self.request.user.is_staff:\n            qs = qs.only_public()\n\n        return qs.with_case_count()\n\n\nclass MonitoringDetailView(SelectRelatedMixin, PrefetchRelatedMixin,\n                           ExtraListMixin, DetailView):\n    model = Monitoring\n    select_related = ['user', ]\n    prefetch_related = ['questionary_set', ]\n    paginate_by = 25\n\n    def get_queryset(self):\n        qs = super(MonitoringDetailView, self).get_queryset()\n\n        if not self.request.user.is_staff:\n            qs = qs.only_public()\n\n        return qs\n\n    def get_object_list(self, obj):\n        return (Case.objects.filter(monitoring=obj).\n                select_related('institution').\n                prefetch_related('task_set').\n                with_record_max().\n                with_letter().\n                order_by('-record_max').\n                all())\n\n\nclass LetterListMonitoringView(SelectRelatedMixin, PrefetchRelatedMixin, ExtraListMixin, DetailView):\n    model = Monitoring\n    template_name_suffix = '_letter_list'\n    select_related = ['user', ]\n    prefetch_related = ['questionary_set', ]\n    paginate_by = 25\n\n    def get_object_list(self, obj):\n        return (Letter.objects.filter(record__case__monitoring=obj).\n                select_related('record__case').\n                with_author().\n                attachment_count().\n                order_by('-created').\n                all())\n\n\nclass DraftListMonitoringView(SelectRelatedMixin, PrefetchRelatedMixin, ExtraListMixin, DetailView):\n    model = Monitoring\n    template_name_suffix = '_draft_list'\n    select_related = ['user', ]\n    prefetch_related = ['questionary_set', ]\n    paginate_by = 25\n\n    def get_object_list(self, obj):\n        return (Letter.objects.filter(record__case__monitoring=obj).\n                is_draft().\n                select_related('record__case').\n                with_author().\n                attachment_count().\n                order_by('-created').\n                all())\n\n\nclass MonitoringCreateView(LoginRequiredMixin, PermissionRequiredMixin,\n                           UserFormKwargsMixin, CreateView):\n    model = Monitoring\n    template_name = 'monitorings/monitoring_form.html'\n    form_class = MonitoringForm\n    permission_required = 'monitorings.add_monitoring'\n    raise_exception = True\n    redirect_unauthenticated_users = True\n\n    def get_form_valid_message(self):\n        return _(\"{0} created!\").format(self.object)\n\n    def form_valid(self, form):\n        output = super(MonitoringCreateView, self).form_valid(form)\n        default_perm = ['change_monitoring', 'delete_monitoring', 'add_questionary',\n                        'change_questionary', 'delete_questionary', 'add_case',\n                        'change_case', 'delete_case', 'add_task', 'change_task',\n                        'delete_task', 'reply', 'view_alert', 'change_alert',\n                        'delete_alert', 'manage_perm',\n                        'select_survey', 'add_draft']\n        for perm in default_perm:\n            assign_perm(perm, self.request.user, form.instance)\n        return output\n\n\nclass MonitoringUpdateView(RaisePermissionRequiredMixin, UserFormKwargsMixin,\n                           UpdateMessageMixin, FormValidMessageMixin, UpdateView):\n    model = Monitoring\n    form_class = MonitoringForm\n    permission_required = 'monitorings.change_monitoring'\n\n\nclass MonitoringDeleteView(RaisePermissionRequiredMixin, DeleteMessageMixin,\n                           DeleteView):\n    model = Monitoring\n    success_url = reverse_lazy('monitorings:list')\n    permission_required = 'monitorings.delete_monitoring'\n\n\nclass PermissionWizard(LoginRequiredMixin, SessionWizardView):\n    form_list = [SelectUserForm, TranslatedUserObjectPermissionsForm]\n    template_name = 'monitorings/permission_wizard.html'\n\n    def perm_check(self):\n        if not self.request.user.has_perm('monitorings.manage_perm',\n                                          self.monitoring):\n            raise PermissionDenied()\n\n    @cached_property\n    def monitoring(self):\n        return Monitoring.objects.get(slug=self.kwargs['slug'])\n\n    def get_context_data(self, *args, **kwargs):\n        context = super(PermissionWizard, self).get_context_data(*args, **kwargs)\n        context['object'] = self.monitoring\n        return context\n\n    def get_form_kwargs(self, step=None):\n        kw = super(PermissionWizard, self).get_form_kwargs(step)\n        self.perm_check()\n        if step == '1':\n            user_pk = self.storage.get_step_data('0').get('0-user')[0]\n            user = get_user_model().objects.get(pk=user_pk)\n            kw['user'] = user\n            kw['obj'] = self.monitoring\n        return kw\n\n    def get_success_message(self):\n        return _(\"Permissions to {monitoring} updated!\").format(monitoring=self.object)\n\n    def done(self, form_list, *args, **kwargs):\n        form_list[1].save_obj_perms()\n        self.object = form_list[1].obj\n        messages.success(self.request, self.get_success_message())\n        url = reverse('monitorings:perm', kwargs={'slug': self.object.slug})\n        return HttpResponseRedirect(url)\n\n\nclass MonitoringPermissionView(RaisePermissionRequiredMixin, SelectRelatedMixin, DetailView):\n    model = Monitoring\n    template_name_suffix = '_permissions'\n    select_related = ['user', ]\n    permission_required = 'monitorings.manage_perm'\n\n    def get_context_data(self, **kwargs):\n        context = super(MonitoringPermissionView, self).get_context_data(**kwargs)\n        context['user_list'], context['index'] = self.object.permission_map()\n        return context\n\n\nclass MonitoringUpdatePermissionView(RaisePermissionRequiredMixin, SelectRelatedMixin, FormView):\n    form_class = SaveTranslatedUserObjectPermissionsForm\n    template_name = 'monitorings/monitoring_form.html'\n    permission_required = 'monitorings.manage_perm'\n\n    def get_permission_object(self):\n        return self.get_monitoring()\n\n    def get_user(self):\n        if not getattr(self, 'user', None):\n            self.user = get_object_or_404(get_user_model(), id=self.kwargs['user_pk'])\n        return self.user\n\n    def get_monitoring(self):\n        if not getattr(self, 'monitoring', None):\n            self.monitoring = get_object_or_404(Monitoring, slug=self.kwargs['slug'])\n        return self.monitoring\n\n    def get_context_data(self, **kwargs):\n        context = super(MonitoringUpdatePermissionView, self).get_context_data(**kwargs)\n        context['object'] = self.get_monitoring()\n        return context\n\n    def get_form_kwargs(self):\n        kw = super(MonitoringUpdatePermissionView, self).get_form_kwargs()\n        kw.update({'user': self.get_user(), 'obj': self.get_monitoring()})\n        return kw\n\n    def get_success_message(self):\n        return (_(\"Permissions to {monitoring} of {user} updated!\").\n                format(monitoring=self.monitoring, user=self.user))\n\n    def form_valid(self, form):\n        form.save_obj_perms()\n        messages.success(self.request, self.get_success_message())\n        url = reverse('monitorings:perm', kwargs={'slug': self.get_monitoring().slug})\n        return HttpResponseRedirect(url)\n\n\nclass MonitoringAssignView(RaisePermissionRequiredMixin, FilterView):\n    model = Institution\n    filterset_class = InstitutionFilter\n    permission_required = 'monitorings.change_monitoring'\n    template_name = 'monitorings/institution_assign.html'\n    paginate_by = 50\n    LIMIT = 500\n\n    def get_limit_simultaneously(self):\n        return self.LIMIT\n\n    def get_queryset(self):\n        qs = super(MonitoringAssignView, self).get_queryset()\n        return (qs.exclude(case__monitoring=self.monitoring.pk).\n                with_case_count().\n                select_related('jst'))\n\n    def get_permission_object(self):\n        return self.monitoring\n\n    @cached_property\n    def monitoring(self):\n        return get_object_or_404(Monitoring, slug=self.kwargs['slug'])\n\n    def get_context_data(self, **kwargs):\n        context = super(MonitoringAssignView, self).get_context_data(**kwargs)\n        context['monitoring'] = self.monitoring\n        return context\n\n    def get_filterset_kwargs(self, filterset_class):\n        kw = super(MonitoringAssignView, self).get_filterset_kwargs(filterset_class)\n        return kw\n\n    def post(self, request, *args, **kwargs):\n        if not request.GET:\n            msg = _(\"You can not send letters without using filtering.\")\n            messages.error(self.request, msg)\n            return HttpResponseRedirect(self.request.path)\n\n        if request.POST.get('all', 'no') == 'yes':\n            qs = self.get_filterset(self.get_filterset_class()).qs\n        else:\n            ids = request.POST.getlist('to_assign')\n            qs = Institution.objects.filter(pk__in=ids)\n        qs = qs.exclude(case__monitoring=self.monitoring.pk)\n\n        count = Case.objects.filter(monitoring=self.monitoring).count() or 0\n\n        to_assign_count = qs.count()\n        if to_assign_count > self.get_limit_simultaneously():\n            msg = _(\"You can not send %(count)d letters at once. \"\n                    \"The maximum is %(limit)d. Use filtering.\") % \\\n                  {'count': to_assign_count, 'limit': self.get_limit_simultaneously()}\n            messages.error(self.request, msg)\n            return HttpResponseRedirect(self.request.path)\n\n        for i, institution in enumerate(qs):\n            postfix = \" #%d\" % (i + count + 1,)\n            Letter.send_new_case(user=self.request.user,\n                                 monitoring=self.monitoring,\n                                 postfix=postfix,\n                                 institution=institution,\n                                 text=self.monitoring.template)\n        msg = _(\"%(count)d institutions was assigned \" +\n                \"to %(monitoring)s. The requests was sent.\") % \\\n              {'count': to_assign_count, 'monitoring': self.monitoring}\n        messages.success(self.request, msg)\n        url = reverse('monitorings:assign', kwargs={'slug': self.monitoring.slug})\n        return HttpResponseRedirect(url)\n\n\nclass MonitoringAutocomplete(autocomplete.Select2QuerySetView):\n    def get_queryset(self):\n        qs = Monitoring.objects\n        if self.q:\n            qs = qs.filter(name__icontains=self.q)\n\n        if not self.request.user.is_staff:\n            qs = qs.only_public()\n\n        return qs.all()\n\n\nclass UserMonitoringAutocomplete(autocomplete.Select2QuerySetView):\n    def get_queryset(self):\n        qs = (get_user_model().objects.\n              annotate(case_count=Count('case')).\n              filter(case_count__gt=0).all())\n        if self.q:\n            qs = qs.filter(name__icontains=self.q)\n        return qs.all()\n", "path": "feder/monitorings/views.py"}], "after_files": [{"content": "from atom.ext.guardian.forms import TranslatedUserObjectPermissionsForm\nfrom atom.views import DeleteMessageMixin, UpdateMessageMixin\nfrom braces.views import (FormValidMessageMixin, LoginRequiredMixin,\n                          PermissionRequiredMixin, SelectRelatedMixin,\n                          UserFormKwargsMixin, PrefetchRelatedMixin)\nfrom cached_property import cached_property\nfrom dal import autocomplete\nfrom django.contrib import messages\nfrom django.contrib.auth import get_user_model\nfrom django.core.exceptions import PermissionDenied\nfrom django.urls import reverse, reverse_lazy\nfrom django.db.models import Count\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.views.generic import (CreateView, DeleteView, DetailView, FormView,\n                                  UpdateView)\nfrom django_filters.views import FilterView\nfrom formtools.wizard.views import SessionWizardView\nfrom guardian.shortcuts import assign_perm\n\nfrom feder.cases.models import Case\nfrom feder.institutions.filters import InstitutionFilter\nfrom feder.institutions.models import Institution\nfrom feder.letters.models import Letter\nfrom feder.main.mixins import ExtraListMixin, RaisePermissionRequiredMixin\nfrom .filters import MonitoringFilter\nfrom .forms import (MonitoringForm, SaveTranslatedUserObjectPermissionsForm,\n                    SelectUserForm)\nfrom .models import Monitoring\n\n\nclass MonitoringListView(SelectRelatedMixin, FilterView):\n    filterset_class = MonitoringFilter\n    model = Monitoring\n    select_related = ['user', ]\n    paginate_by = 25\n\n    def get_queryset(self):\n        qs = super(MonitoringListView, self).get_queryset()\n\n        if not self.request.user.is_staff:\n            qs = qs.only_public()\n\n        return qs.with_case_count()\n\n\nclass MonitoringDetailView(SelectRelatedMixin, PrefetchRelatedMixin,\n                           ExtraListMixin, DetailView):\n    model = Monitoring\n    select_related = ['user', ]\n    prefetch_related = ['questionary_set', ]\n    paginate_by = 25\n\n    def get_queryset(self):\n        qs = super(MonitoringDetailView, self).get_queryset()\n\n        if not self.request.user.is_staff:\n            qs = qs.only_public()\n\n        return qs\n\n    def get_context_data(self, **kwargs):\n        kwargs['url_extra_kwargs'] = {'slug': self.object.slug}\n        return super(MonitoringDetailView, self).get_context_data(**kwargs)\n\n    def get_object_list(self, obj):\n        return (Case.objects.filter(monitoring=obj).\n                select_related('institution').\n                prefetch_related('task_set').\n                with_record_max().\n                with_letter().\n                order_by('-record_max').\n                all())\n\n\nclass LetterListMonitoringView(SelectRelatedMixin, PrefetchRelatedMixin, ExtraListMixin, DetailView):\n    model = Monitoring\n    template_name_suffix = '_letter_list'\n    select_related = ['user', ]\n    prefetch_related = ['questionary_set', ]\n    paginate_by = 25\n\n    def get_context_data(self, **kwargs):\n        kwargs['url_extra_kwargs'] = {'slug': self.object.slug}\n        return super(LetterListMonitoringView, self).get_context_data(**kwargs)\n\n    def get_object_list(self, obj):\n        return (Letter.objects.filter(record__case__monitoring=obj).\n                select_related('record__case').\n                with_author().\n                attachment_count().\n                order_by('-created').\n                all())\n\n\nclass DraftListMonitoringView(SelectRelatedMixin, PrefetchRelatedMixin, ExtraListMixin, DetailView):\n    model = Monitoring\n    template_name_suffix = '_draft_list'\n    select_related = ['user', ]\n    prefetch_related = ['questionary_set', ]\n    paginate_by = 25\n\n    def get_context_data(self, **kwargs):\n        kwargs['url_extra_kwargs'] = {'slug': self.object.slug}\n        return super(DraftListMonitoringView, self).get_context_data(**kwargs)\n\n    def get_object_list(self, obj):\n        return (Letter.objects.filter(record__case__monitoring=obj).\n                is_draft().\n                select_related('record__case').\n                with_author().\n                attachment_count().\n                order_by('-created').\n                all())\n\n\nclass MonitoringCreateView(LoginRequiredMixin, PermissionRequiredMixin,\n                           UserFormKwargsMixin, CreateView):\n    model = Monitoring\n    template_name = 'monitorings/monitoring_form.html'\n    form_class = MonitoringForm\n    permission_required = 'monitorings.add_monitoring'\n    raise_exception = True\n    redirect_unauthenticated_users = True\n\n    def get_form_valid_message(self):\n        return _(\"{0} created!\").format(self.object)\n\n    def form_valid(self, form):\n        output = super(MonitoringCreateView, self).form_valid(form)\n        default_perm = ['change_monitoring', 'delete_monitoring', 'add_questionary',\n                        'change_questionary', 'delete_questionary', 'add_case',\n                        'change_case', 'delete_case', 'add_task', 'change_task',\n                        'delete_task', 'reply', 'view_alert', 'change_alert',\n                        'delete_alert', 'manage_perm',\n                        'select_survey', 'add_draft']\n        for perm in default_perm:\n            assign_perm(perm, self.request.user, form.instance)\n        return output\n\n\nclass MonitoringUpdateView(RaisePermissionRequiredMixin, UserFormKwargsMixin,\n                           UpdateMessageMixin, FormValidMessageMixin, UpdateView):\n    model = Monitoring\n    form_class = MonitoringForm\n    permission_required = 'monitorings.change_monitoring'\n\n\nclass MonitoringDeleteView(RaisePermissionRequiredMixin, DeleteMessageMixin,\n                           DeleteView):\n    model = Monitoring\n    success_url = reverse_lazy('monitorings:list')\n    permission_required = 'monitorings.delete_monitoring'\n\n\nclass PermissionWizard(LoginRequiredMixin, SessionWizardView):\n    form_list = [SelectUserForm, TranslatedUserObjectPermissionsForm]\n    template_name = 'monitorings/permission_wizard.html'\n\n    def perm_check(self):\n        if not self.request.user.has_perm('monitorings.manage_perm',\n                                          self.monitoring):\n            raise PermissionDenied()\n\n    @cached_property\n    def monitoring(self):\n        return Monitoring.objects.get(slug=self.kwargs['slug'])\n\n    def get_context_data(self, *args, **kwargs):\n        context = super(PermissionWizard, self).get_context_data(*args, **kwargs)\n        context['object'] = self.monitoring\n        return context\n\n    def get_form_kwargs(self, step=None):\n        kw = super(PermissionWizard, self).get_form_kwargs(step)\n        self.perm_check()\n        if step == '1':\n            user_pk = self.storage.get_step_data('0').get('0-user')[0]\n            user = get_user_model().objects.get(pk=user_pk)\n            kw['user'] = user\n            kw['obj'] = self.monitoring\n        return kw\n\n    def get_success_message(self):\n        return _(\"Permissions to {monitoring} updated!\").format(monitoring=self.object)\n\n    def done(self, form_list, *args, **kwargs):\n        form_list[1].save_obj_perms()\n        self.object = form_list[1].obj\n        messages.success(self.request, self.get_success_message())\n        url = reverse('monitorings:perm', kwargs={'slug': self.object.slug})\n        return HttpResponseRedirect(url)\n\n\nclass MonitoringPermissionView(RaisePermissionRequiredMixin, SelectRelatedMixin, DetailView):\n    model = Monitoring\n    template_name_suffix = '_permissions'\n    select_related = ['user', ]\n    permission_required = 'monitorings.manage_perm'\n\n    def get_context_data(self, **kwargs):\n        context = super(MonitoringPermissionView, self).get_context_data(**kwargs)\n        context['user_list'], context['index'] = self.object.permission_map()\n        return context\n\n\nclass MonitoringUpdatePermissionView(RaisePermissionRequiredMixin, SelectRelatedMixin, FormView):\n    form_class = SaveTranslatedUserObjectPermissionsForm\n    template_name = 'monitorings/monitoring_form.html'\n    permission_required = 'monitorings.manage_perm'\n\n    def get_permission_object(self):\n        return self.get_monitoring()\n\n    def get_user(self):\n        if not getattr(self, 'user', None):\n            self.user = get_object_or_404(get_user_model(), id=self.kwargs['user_pk'])\n        return self.user\n\n    def get_monitoring(self):\n        if not getattr(self, 'monitoring', None):\n            self.monitoring = get_object_or_404(Monitoring, slug=self.kwargs['slug'])\n        return self.monitoring\n\n    def get_context_data(self, **kwargs):\n        context = super(MonitoringUpdatePermissionView, self).get_context_data(**kwargs)\n        context['object'] = self.get_monitoring()\n        return context\n\n    def get_form_kwargs(self):\n        kw = super(MonitoringUpdatePermissionView, self).get_form_kwargs()\n        kw.update({'user': self.get_user(), 'obj': self.get_monitoring()})\n        return kw\n\n    def get_success_message(self):\n        return (_(\"Permissions to {monitoring} of {user} updated!\").\n                format(monitoring=self.monitoring, user=self.user))\n\n    def form_valid(self, form):\n        form.save_obj_perms()\n        messages.success(self.request, self.get_success_message())\n        url = reverse('monitorings:perm', kwargs={'slug': self.get_monitoring().slug})\n        return HttpResponseRedirect(url)\n\n\nclass MonitoringAssignView(RaisePermissionRequiredMixin, FilterView):\n    model = Institution\n    filterset_class = InstitutionFilter\n    permission_required = 'monitorings.change_monitoring'\n    template_name = 'monitorings/institution_assign.html'\n    paginate_by = 50\n    LIMIT = 500\n\n    def get_limit_simultaneously(self):\n        return self.LIMIT\n\n    def get_queryset(self):\n        qs = super(MonitoringAssignView, self).get_queryset()\n        return (qs.exclude(case__monitoring=self.monitoring.pk).\n                with_case_count().\n                select_related('jst'))\n\n    def get_permission_object(self):\n        return self.monitoring\n\n    @cached_property\n    def monitoring(self):\n        return get_object_or_404(Monitoring, slug=self.kwargs['slug'])\n\n    def get_context_data(self, **kwargs):\n        context = super(MonitoringAssignView, self).get_context_data(**kwargs)\n        context['monitoring'] = self.monitoring\n        return context\n\n    def get_filterset_kwargs(self, filterset_class):\n        kw = super(MonitoringAssignView, self).get_filterset_kwargs(filterset_class)\n        return kw\n\n    def post(self, request, *args, **kwargs):\n        if not request.GET:\n            msg = _(\"You can not send letters without using filtering.\")\n            messages.error(self.request, msg)\n            return HttpResponseRedirect(self.request.path)\n\n        if request.POST.get('all', 'no') == 'yes':\n            qs = self.get_filterset(self.get_filterset_class()).qs\n        else:\n            ids = request.POST.getlist('to_assign')\n            qs = Institution.objects.filter(pk__in=ids)\n        qs = qs.exclude(case__monitoring=self.monitoring.pk)\n\n        count = Case.objects.filter(monitoring=self.monitoring).count() or 0\n\n        to_assign_count = qs.count()\n        if to_assign_count > self.get_limit_simultaneously():\n            msg = _(\"You can not send %(count)d letters at once. \"\n                    \"The maximum is %(limit)d. Use filtering.\") % \\\n                  {'count': to_assign_count, 'limit': self.get_limit_simultaneously()}\n            messages.error(self.request, msg)\n            return HttpResponseRedirect(self.request.path)\n\n        for i, institution in enumerate(qs):\n            postfix = \" #%d\" % (i + count + 1,)\n            Letter.send_new_case(user=self.request.user,\n                                 monitoring=self.monitoring,\n                                 postfix=postfix,\n                                 institution=institution,\n                                 text=self.monitoring.template)\n        msg = _(\"%(count)d institutions was assigned \" +\n                \"to %(monitoring)s. The requests was sent.\") % \\\n              {'count': to_assign_count, 'monitoring': self.monitoring}\n        messages.success(self.request, msg)\n        url = reverse('monitorings:assign', kwargs={'slug': self.monitoring.slug})\n        return HttpResponseRedirect(url)\n\n\nclass MonitoringAutocomplete(autocomplete.Select2QuerySetView):\n    def get_queryset(self):\n        qs = Monitoring.objects\n        if self.q:\n            qs = qs.filter(name__icontains=self.q)\n\n        if not self.request.user.is_staff:\n            qs = qs.only_public()\n\n        return qs.all()\n\n\nclass UserMonitoringAutocomplete(autocomplete.Select2QuerySetView):\n    def get_queryset(self):\n        qs = (get_user_model().objects.\n              annotate(case_count=Count('case')).\n              filter(case_count__gt=0).all())\n        if self.q:\n            qs = qs.filter(name__icontains=self.q)\n        return qs.all()\n", "path": "feder/monitorings/views.py"}]}