We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Posters issues
- [ ] Does not send mail [src](https://github.com/dotKom/onlineweb4/blob/f4c45b9d07bd2c20533dec840a3bdcb3b8d50dd3/apps/posters/dashboard/views.py#L106)
- [x] Group is set to "Komiteer" [src](https://github.com/dotKom/onlineweb4/blob/f4c45b9d07bd2c20533dec840a3bdcb3b8d50dd3/apps/posters/dashboard/views.py#L93)


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `apps/posters/dashboard/views.py`
Content:
```
1 # -*- encoding: utf-8 -*-
2 
3 import json
4 
5 from django.conf import settings
6 from django.contrib import messages
7 from django.contrib.auth.decorators import login_required
8 from django.contrib.auth.models import Group
9 from django.core.mail import EmailMessage
10 from django.core.exceptions import PermissionDenied, ObjectDoesNotExist
11 from django.core.urlresolvers import reverse
12 from django.forms.models import model_to_dict
13 from django.shortcuts import render, redirect, get_object_or_404, HttpResponseRedirect, HttpResponse
14 from django.utils import timezone
15 from django.utils.translation import ugettext as _
16 from django.views.decorators.csrf import ensure_csrf_cookie
17 
18 from guardian.decorators import permission_required
19 from guardian.models import UserObjectPermission, GroupObjectPermission
20 # from guardian.core import ObjectPermissionChecker
21 import guardian
22 
23 from datetime import datetime, timedelta
24 
25 from apps.authentication.models import OnlineUser as User
26 from apps.dashboard.tools import has_access, get_base_context
27 from apps.posters.models import Poster
28 from apps.posters.forms import AddForm, AddPosterForm, AddBongForm, AddOtherForm, EditPosterForm
29 # from apps.dashboard.posters.models import PosterForm
30 from apps.companyprofile.models import Company
31 from apps.posters.models import Poster, OrderMixin
32 from apps.posters.permissions import has_view_perms, has_view_all_perms
33 
34 
35 @ensure_csrf_cookie
36 @login_required
37 @permission_required('posters.overview_poster_order', return_403=True)
38 def index(request):
39     if request.is_ajax():
40         do_ajax_shit = True
41 
42     # The group with members who should populate the dropdownlist
43     group = Group.objects.get(name='proKom')
44     users_to_populate = group.user_set.all()
45 
46     context = get_base_context(request)
47 
48     # View to show if user not in committee, but wanting to see own orders
49     if not has_view_all_perms(request.user):
50         context['your_orders'] = [x for x in Poster.objects.filter(ordered_by=request.user) if request.user.has_perm('view_poster_order', x)]
51         return render(request, 'posters/dashboard/index.html', context)
52 
53     orders = Poster.objects.all()
54 
55     context['new_orders'] = orders.filter(assigned_to=None)
56     context['active_orders'] = orders.filter(finished=False).exclude(assigned_to=None)
57     context['hanging_orders'] = orders.filter(finished=True,
58                                               display_to__lte=datetime.now()+timedelta(days=3))
59 
60     context['workers'] = User.objects.filter(groups=Group.objects.get(name='proKom'))
61 
62     return render(request, 'posters/dashboard/index.html', context)
63 
64 
65 @ensure_csrf_cookie
66 @login_required
67 @permission_required('posters.add_poster_order', return_403=True)
68 def add(request, order_type=0):
69     order_type = int(order_type)
70     context = get_base_context(request)
71     type_names = ("Plakat", "Bong", "Generell ")
72     type_name = type_names[order_type-1]
73 
74     poster = Poster()
75     form = None
76 
77     if request.method == 'POST':
78         if order_type == 1:
79             form = AddPosterForm(data=request.POST, instance=poster)
80         elif order_type == 2:
81             form = AddBongForm(data=request.POST, instance=poster)
82         elif order_type == 3:
83             # poster = GeneralOrder()
84             form = AddOtherForm(data=request.POST, instance=poster)
85 
86         if form.is_valid():
87             poster = form.save(commit=False)
88             if request.POST.get('company'):
89                 poster.company = Company.objects.get(pk=request.POST.get('company'))
90             poster.ordered_by = request.user
91             # Should look for a more kosher solution
92             poster.ordered_committee = request.user.groups.exclude(name='Komiteer').filter(name__contains="Kom")[0]
93             poster.order_type = order_type
94 
95             poster.save()
96 
97             # for b in poster.__class__.__bases__:
98             # poster_mixin = OrderMixin.objects.get(id=poster.id)
99             # Let this user have permissions to show this order
100             UserObjectPermission.objects.assign_perm('view_poster_order', obj=poster, user=request.user)
101             GroupObjectPermission.objects.assign_perm('view_poster_order', obj=poster, group=Group.objects.get(name='proKom'))
102 
103             title = unicode(poster)
104 
105             # The great sending of emails
106             subject = '[ProKom] Ny bestilling for %s' % title
107             email_message = '%(message)s%(signature)s' % {
108                     'message': _('''
109                     Det har blitt registrert en ny %(order_type)sbestilling pa Online sine nettsider. Dette er bestilling nummer %(id)s.
110                     \n
111                     Antall og type: %(num)s * %(order_type)s\n
112                     Arrangement: %(event_name)s\n
113                     Bestilt av: %(ordered_by)s i %(ordered_by_committee)s\n
114                     Bestilt dato: %(ordered_date)s\n
115                     \n
116                     For mer informasjon, sjekk ut bestillingen her: %(absolute_url)s
117                     '''
118                     % {
119                         'site': '',
120                         'order_type': type_name.lower(),
121                         'num': poster.amount,
122                         'ordered_by': poster.ordered_by,
123                         'ordered_by_committee': poster.ordered_committee,
124                         'id': poster.id,
125                         'event_name': title,
126                         'ordered_date': poster.ordered_date,
127                         'absolute_url': request.build_absolute_uri(poster.get_dashboard_url())
128                         }
129                     ),
130                     'signature': _('\n\nVennlig hilsen Linjeforeningen Online')
131             }
132             from_email = settings.EMAIL_PROKOM
133             to_emails = [settings.EMAIL_PROKOM, request.user.get_email()]
134 
135             try:
136                 email_sent = EmailMessage(unicode(subject), unicode(message), from_email, to_emails, []).send()
137             except:
138                 email_sent = False
139 
140             if email_sent:
141                 messages.success(request, 'Opprettet bestilling')
142             else:
143                 messages.error(request, 'Klarte ikke å sende epost, men bestillingen din ble fortsatt opprettet')
144 
145             return redirect(poster.get_absolute_url())
146         else:
147             context['form'] = form
148             return render(request, 'posters/dashboard/add.html', context)
149 
150     context["order_type_name"] = type_name
151     context['order_type'] = order_type
152     context['can_edit'] = True  # request.user.has_perm('posters.view_poster')
153 
154     if order_type == 1:
155         form = AddPosterForm()
156     elif order_type == 2:
157         form = AddBongForm()
158     elif order_type == 3:
159         form = AddOtherForm()
160 
161     forms = (AddPosterForm(), AddBongForm(), AddOtherForm())
162 
163     context['form'] = forms[order_type-1]
164 
165     return render(request, 'posters/dashboard/add.html', context)
166 
167 
168 @ensure_csrf_cookie
169 @login_required
170 def edit(request, order_id=None):
171     context = get_base_context(request)
172     context['add_poster_form'] = EditPosterForm()
173 
174     if order_id:
175         poster = get_object_or_404(Poster, pk=order_id)
176 
177     if request.user != poster.ordered_by and 'proKom' not in request.user.groups:
178         raise PermissionDenied
179 
180     if request.POST:
181         form = AddForm(request.POST, instance=poster)
182         if form.is_valid():
183             form.save()
184             # redirect_url = redirect(poster.get_absolute_url())
185             return HttpResponseRedirect("../detail/"+str(poster.id))
186 
187     else:
188         context["form"] = AddForm(instance=poster)
189 
190     return render(request, 'posters/dashboard/add.html', context)
191 
192 
193 @ensure_csrf_cookie
194 @login_required
195 @permission_required('view_poster_order', (Poster, 'pk', 'order_id'), return_403=True)
196 def detail(request, order_id=None):
197     if request.is_ajax():
198         do_ajax_shit = True
199 
200     if not order_id:
201         return HttpResponse(status=400)
202 
203     context = get_base_context(request)
204     poster = get_object_or_404(Poster, pk=order_id)
205     context['poster'] = poster
206 
207     if not has_view_perms(request.user, poster):
208         raise PermissionDenied
209 
210     order_type = poster.order_type
211     type_names = ("Plakat", "Bong", "Generell ")
212     type_name = type_names[order_type-1]
213     context["order_type_name"] = type_name
214 
215     if request.method == 'POST':
216         poster_status = request.POST.get('completed')
217         if poster_status == 'true' or poster_status == 'false':
218             poster.toggle_finished()
219 
220     return render(request, 'posters/dashboard/details.html', context)
221 
222 
223 # Ajax
224 
225 
226 # @ensure_csrf_cookie
227 @login_required
228 def assign_person(request):
229     if request.is_ajax():
230         if request.method == 'POST':
231             order_id = request.POST.get('order_id')
232             orders = Poster.objects.filter(pk=order_id)
233             assign_to_id = request.POST.get('assign_to_id')
234             assign_to = User.objects.get(pk=assign_to_id)
235 
236             if orders.count() == 0:
237                 response_text = json.dumps({'message': _(
238                     u"""Kan ikke finne en ordre med denne IDen (%s).
239 Om feilen vedvarer etter en refresh, kontakt dotkom@online.ntnu.no.""") % order_id})
240                 return HttpResponse(status=412, content=response_text)
241 
242             order = orders[0]
243 
244             if order.finished or order.assigned_to is not None:
245                 response_text = json.dumps({'message': _(u"Denne ordren er allerede behandlet.")})
246                 return HttpResponse(status=412, content=response_text)
247 
248             order.assigned_to = assign_to
249             order.save()
250 
251             return HttpResponse(status=200)
252
```
--- 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/apps/posters/dashboard/views.py b/apps/posters/dashboard/views.py
--- a/apps/posters/dashboard/views.py
+++ b/apps/posters/dashboard/views.py
@@ -106,14 +106,14 @@
             subject = '[ProKom] Ny bestilling for %s' % title
             email_message = '%(message)s%(signature)s' % {
                     'message': _('''
-                    Det har blitt registrert en ny %(order_type)sbestilling pa Online sine nettsider. Dette er bestilling nummer %(id)s.
-                    \n
-                    Antall og type: %(num)s * %(order_type)s\n
-                    Arrangement: %(event_name)s\n
-                    Bestilt av: %(ordered_by)s i %(ordered_by_committee)s\n
-                    Bestilt dato: %(ordered_date)s\n
-                    \n
-                    For mer informasjon, sjekk ut bestillingen her: %(absolute_url)s
+Det har blitt registrert en ny %(order_type)sbestilling pa Online sine nettsider. Dette er bestilling nummer %(id)s.
+\n
+Antall og type: %(num)s * %(order_type)s\n
+Arrangement: %(event_name)s\n
+Bestilt av: %(ordered_by)s i %(ordered_by_committee)s\n
+Bestilt dato: %(ordered_date)s\n
+\n
+For mer informasjon, sjekk ut bestillingen her: %(absolute_url)s
                     '''
                     % {
                         'site': '',
@@ -130,13 +130,9 @@
                     'signature': _('\n\nVennlig hilsen Linjeforeningen Online')
             }
             from_email = settings.EMAIL_PROKOM
-            to_emails = [settings.EMAIL_PROKOM, request.user.get_email()]
-
-            try:
-                email_sent = EmailMessage(unicode(subject), unicode(message), from_email, to_emails, []).send()
-            except:
-                email_sent = False
+            to_emails = [settings.EMAIL_PROKOM, request.user.get_email().email]
 
+            email_sent = EmailMessage(unicode(subject), unicode(email_message), from_email, to_emails, []).send()
             if email_sent:
                 messages.success(request, 'Opprettet bestilling')
             else:

{"golden_diff": "diff --git a/apps/posters/dashboard/views.py b/apps/posters/dashboard/views.py\n--- a/apps/posters/dashboard/views.py\n+++ b/apps/posters/dashboard/views.py\n@@ -106,14 +106,14 @@\n             subject = '[ProKom] Ny bestilling for %s' % title\n             email_message = '%(message)s%(signature)s' % {\n                     'message': _('''\n-                    Det har blitt registrert en ny %(order_type)sbestilling pa Online sine nettsider. Dette er bestilling nummer %(id)s.\n-                    \\n\n-                    Antall og type: %(num)s * %(order_type)s\\n\n-                    Arrangement: %(event_name)s\\n\n-                    Bestilt av: %(ordered_by)s i %(ordered_by_committee)s\\n\n-                    Bestilt dato: %(ordered_date)s\\n\n-                    \\n\n-                    For mer informasjon, sjekk ut bestillingen her: %(absolute_url)s\n+Det har blitt registrert en ny %(order_type)sbestilling pa Online sine nettsider. Dette er bestilling nummer %(id)s.\n+\\n\n+Antall og type: %(num)s * %(order_type)s\\n\n+Arrangement: %(event_name)s\\n\n+Bestilt av: %(ordered_by)s i %(ordered_by_committee)s\\n\n+Bestilt dato: %(ordered_date)s\\n\n+\\n\n+For mer informasjon, sjekk ut bestillingen her: %(absolute_url)s\n                     '''\n                     % {\n                         'site': '',\n@@ -130,13 +130,9 @@\n                     'signature': _('\\n\\nVennlig hilsen Linjeforeningen Online')\n             }\n             from_email = settings.EMAIL_PROKOM\n-            to_emails = [settings.EMAIL_PROKOM, request.user.get_email()]\n-\n-            try:\n-                email_sent = EmailMessage(unicode(subject), unicode(message), from_email, to_emails, []).send()\n-            except:\n-                email_sent = False\n+            to_emails = [settings.EMAIL_PROKOM, request.user.get_email().email]\n \n+            email_sent = EmailMessage(unicode(subject), unicode(email_message), from_email, to_emails, []).send()\n             if email_sent:\n                 messages.success(request, 'Opprettet bestilling')\n             else:\n", "issue": "Posters issues\n- [ ] Does not send mail [src](https://github.com/dotKom/onlineweb4/blob/f4c45b9d07bd2c20533dec840a3bdcb3b8d50dd3/apps/posters/dashboard/views.py#L106)\n- [x] Group is set to \"Komiteer\" [src](https://github.com/dotKom/onlineweb4/blob/f4c45b9d07bd2c20533dec840a3bdcb3b8d50dd3/apps/posters/dashboard/views.py#L93)\n\n", "before_files": [{"content": "# -*- encoding: utf-8 -*-\n\nimport json\n\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import Group\nfrom django.core.mail import EmailMessage\nfrom django.core.exceptions import PermissionDenied, ObjectDoesNotExist\nfrom django.core.urlresolvers import reverse\nfrom django.forms.models import model_to_dict\nfrom django.shortcuts import render, redirect, get_object_or_404, HttpResponseRedirect, HttpResponse\nfrom django.utils import timezone\nfrom django.utils.translation import ugettext as _\nfrom django.views.decorators.csrf import ensure_csrf_cookie\n\nfrom guardian.decorators import permission_required\nfrom guardian.models import UserObjectPermission, GroupObjectPermission\n# from guardian.core import ObjectPermissionChecker\nimport guardian\n\nfrom datetime import datetime, timedelta\n\nfrom apps.authentication.models import OnlineUser as User\nfrom apps.dashboard.tools import has_access, get_base_context\nfrom apps.posters.models import Poster\nfrom apps.posters.forms import AddForm, AddPosterForm, AddBongForm, AddOtherForm, EditPosterForm\n# from apps.dashboard.posters.models import PosterForm\nfrom apps.companyprofile.models import Company\nfrom apps.posters.models import Poster, OrderMixin\nfrom apps.posters.permissions import has_view_perms, has_view_all_perms\n\n\n@ensure_csrf_cookie\n@login_required\n@permission_required('posters.overview_poster_order', return_403=True)\ndef index(request):\n    if request.is_ajax():\n        do_ajax_shit = True\n\n    # The group with members who should populate the dropdownlist\n    group = Group.objects.get(name='proKom')\n    users_to_populate = group.user_set.all()\n\n    context = get_base_context(request)\n\n    # View to show if user not in committee, but wanting to see own orders\n    if not has_view_all_perms(request.user):\n        context['your_orders'] = [x for x in Poster.objects.filter(ordered_by=request.user) if request.user.has_perm('view_poster_order', x)]\n        return render(request, 'posters/dashboard/index.html', context)\n\n    orders = Poster.objects.all()\n\n    context['new_orders'] = orders.filter(assigned_to=None)\n    context['active_orders'] = orders.filter(finished=False).exclude(assigned_to=None)\n    context['hanging_orders'] = orders.filter(finished=True,\n                                              display_to__lte=datetime.now()+timedelta(days=3))\n\n    context['workers'] = User.objects.filter(groups=Group.objects.get(name='proKom'))\n\n    return render(request, 'posters/dashboard/index.html', context)\n\n\n@ensure_csrf_cookie\n@login_required\n@permission_required('posters.add_poster_order', return_403=True)\ndef add(request, order_type=0):\n    order_type = int(order_type)\n    context = get_base_context(request)\n    type_names = (\"Plakat\", \"Bong\", \"Generell \")\n    type_name = type_names[order_type-1]\n\n    poster = Poster()\n    form = None\n\n    if request.method == 'POST':\n        if order_type == 1:\n            form = AddPosterForm(data=request.POST, instance=poster)\n        elif order_type == 2:\n            form = AddBongForm(data=request.POST, instance=poster)\n        elif order_type == 3:\n            # poster = GeneralOrder()\n            form = AddOtherForm(data=request.POST, instance=poster)\n\n        if form.is_valid():\n            poster = form.save(commit=False)\n            if request.POST.get('company'):\n                poster.company = Company.objects.get(pk=request.POST.get('company'))\n            poster.ordered_by = request.user\n            # Should look for a more kosher solution\n            poster.ordered_committee = request.user.groups.exclude(name='Komiteer').filter(name__contains=\"Kom\")[0]\n            poster.order_type = order_type\n\n            poster.save()\n\n            # for b in poster.__class__.__bases__:\n            # poster_mixin = OrderMixin.objects.get(id=poster.id)\n            # Let this user have permissions to show this order\n            UserObjectPermission.objects.assign_perm('view_poster_order', obj=poster, user=request.user)\n            GroupObjectPermission.objects.assign_perm('view_poster_order', obj=poster, group=Group.objects.get(name='proKom'))\n\n            title = unicode(poster)\n\n            # The great sending of emails\n            subject = '[ProKom] Ny bestilling for %s' % title\n            email_message = '%(message)s%(signature)s' % {\n                    'message': _('''\n                    Det har blitt registrert en ny %(order_type)sbestilling pa Online sine nettsider. Dette er bestilling nummer %(id)s.\n                    \\n\n                    Antall og type: %(num)s * %(order_type)s\\n\n                    Arrangement: %(event_name)s\\n\n                    Bestilt av: %(ordered_by)s i %(ordered_by_committee)s\\n\n                    Bestilt dato: %(ordered_date)s\\n\n                    \\n\n                    For mer informasjon, sjekk ut bestillingen her: %(absolute_url)s\n                    '''\n                    % {\n                        'site': '',\n                        'order_type': type_name.lower(),\n                        'num': poster.amount,\n                        'ordered_by': poster.ordered_by,\n                        'ordered_by_committee': poster.ordered_committee,\n                        'id': poster.id,\n                        'event_name': title,\n                        'ordered_date': poster.ordered_date,\n                        'absolute_url': request.build_absolute_uri(poster.get_dashboard_url())\n                        }\n                    ),\n                    'signature': _('\\n\\nVennlig hilsen Linjeforeningen Online')\n            }\n            from_email = settings.EMAIL_PROKOM\n            to_emails = [settings.EMAIL_PROKOM, request.user.get_email()]\n\n            try:\n                email_sent = EmailMessage(unicode(subject), unicode(message), from_email, to_emails, []).send()\n            except:\n                email_sent = False\n\n            if email_sent:\n                messages.success(request, 'Opprettet bestilling')\n            else:\n                messages.error(request, 'Klarte ikke \u00e5 sende epost, men bestillingen din ble fortsatt opprettet')\n\n            return redirect(poster.get_absolute_url())\n        else:\n            context['form'] = form\n            return render(request, 'posters/dashboard/add.html', context)\n\n    context[\"order_type_name\"] = type_name\n    context['order_type'] = order_type\n    context['can_edit'] = True  # request.user.has_perm('posters.view_poster')\n\n    if order_type == 1:\n        form = AddPosterForm()\n    elif order_type == 2:\n        form = AddBongForm()\n    elif order_type == 3:\n        form = AddOtherForm()\n\n    forms = (AddPosterForm(), AddBongForm(), AddOtherForm())\n\n    context['form'] = forms[order_type-1]\n\n    return render(request, 'posters/dashboard/add.html', context)\n\n\n@ensure_csrf_cookie\n@login_required\ndef edit(request, order_id=None):\n    context = get_base_context(request)\n    context['add_poster_form'] = EditPosterForm()\n\n    if order_id:\n        poster = get_object_or_404(Poster, pk=order_id)\n\n    if request.user != poster.ordered_by and 'proKom' not in request.user.groups:\n        raise PermissionDenied\n\n    if request.POST:\n        form = AddForm(request.POST, instance=poster)\n        if form.is_valid():\n            form.save()\n            # redirect_url = redirect(poster.get_absolute_url())\n            return HttpResponseRedirect(\"../detail/\"+str(poster.id))\n\n    else:\n        context[\"form\"] = AddForm(instance=poster)\n\n    return render(request, 'posters/dashboard/add.html', context)\n\n\n@ensure_csrf_cookie\n@login_required\n@permission_required('view_poster_order', (Poster, 'pk', 'order_id'), return_403=True)\ndef detail(request, order_id=None):\n    if request.is_ajax():\n        do_ajax_shit = True\n\n    if not order_id:\n        return HttpResponse(status=400)\n\n    context = get_base_context(request)\n    poster = get_object_or_404(Poster, pk=order_id)\n    context['poster'] = poster\n\n    if not has_view_perms(request.user, poster):\n        raise PermissionDenied\n\n    order_type = poster.order_type\n    type_names = (\"Plakat\", \"Bong\", \"Generell \")\n    type_name = type_names[order_type-1]\n    context[\"order_type_name\"] = type_name\n\n    if request.method == 'POST':\n        poster_status = request.POST.get('completed')\n        if poster_status == 'true' or poster_status == 'false':\n            poster.toggle_finished()\n\n    return render(request, 'posters/dashboard/details.html', context)\n\n\n# Ajax\n\n\n# @ensure_csrf_cookie\n@login_required\ndef assign_person(request):\n    if request.is_ajax():\n        if request.method == 'POST':\n            order_id = request.POST.get('order_id')\n            orders = Poster.objects.filter(pk=order_id)\n            assign_to_id = request.POST.get('assign_to_id')\n            assign_to = User.objects.get(pk=assign_to_id)\n\n            if orders.count() == 0:\n                response_text = json.dumps({'message': _(\n                    u\"\"\"Kan ikke finne en ordre med denne IDen (%s).\nOm feilen vedvarer etter en refresh, kontakt dotkom@online.ntnu.no.\"\"\") % order_id})\n                return HttpResponse(status=412, content=response_text)\n\n            order = orders[0]\n\n            if order.finished or order.assigned_to is not None:\n                response_text = json.dumps({'message': _(u\"Denne ordren er allerede behandlet.\")})\n                return HttpResponse(status=412, content=response_text)\n\n            order.assigned_to = assign_to\n            order.save()\n\n            return HttpResponse(status=200)\n", "path": "apps/posters/dashboard/views.py"}], "after_files": [{"content": "# -*- encoding: utf-8 -*-\n\nimport json\n\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import Group\nfrom django.core.mail import EmailMessage\nfrom django.core.exceptions import PermissionDenied, ObjectDoesNotExist\nfrom django.core.urlresolvers import reverse\nfrom django.forms.models import model_to_dict\nfrom django.shortcuts import render, redirect, get_object_or_404, HttpResponseRedirect, HttpResponse\nfrom django.utils import timezone\nfrom django.utils.translation import ugettext as _\nfrom django.views.decorators.csrf import ensure_csrf_cookie\n\nfrom guardian.decorators import permission_required\nfrom guardian.models import UserObjectPermission, GroupObjectPermission\n# from guardian.core import ObjectPermissionChecker\nimport guardian\n\nfrom datetime import datetime, timedelta\n\nfrom apps.authentication.models import OnlineUser as User\nfrom apps.dashboard.tools import has_access, get_base_context\nfrom apps.posters.models import Poster\nfrom apps.posters.forms import AddForm, AddPosterForm, AddBongForm, AddOtherForm, EditPosterForm\n# from apps.dashboard.posters.models import PosterForm\nfrom apps.companyprofile.models import Company\nfrom apps.posters.models import Poster, OrderMixin\nfrom apps.posters.permissions import has_view_perms, has_view_all_perms\n\n\n@ensure_csrf_cookie\n@login_required\n@permission_required('posters.overview_poster_order', return_403=True)\ndef index(request):\n    if request.is_ajax():\n        do_ajax_shit = True\n\n    # The group with members who should populate the dropdownlist\n    group = Group.objects.get(name='proKom')\n    users_to_populate = group.user_set.all()\n\n    context = get_base_context(request)\n\n    # View to show if user not in committee, but wanting to see own orders\n    if not has_view_all_perms(request.user):\n        context['your_orders'] = [x for x in Poster.objects.filter(ordered_by=request.user) if request.user.has_perm('view_poster_order', x)]\n        return render(request, 'posters/dashboard/index.html', context)\n\n    orders = Poster.objects.all()\n\n    context['new_orders'] = orders.filter(assigned_to=None)\n    context['active_orders'] = orders.filter(finished=False).exclude(assigned_to=None)\n    context['hanging_orders'] = orders.filter(finished=True,\n                                              display_to__lte=datetime.now()+timedelta(days=3))\n\n    context['workers'] = User.objects.filter(groups=Group.objects.get(name='proKom'))\n\n    return render(request, 'posters/dashboard/index.html', context)\n\n\n@ensure_csrf_cookie\n@login_required\n@permission_required('posters.add_poster_order', return_403=True)\ndef add(request, order_type=0):\n    order_type = int(order_type)\n    context = get_base_context(request)\n    type_names = (\"Plakat\", \"Bong\", \"Generell \")\n    type_name = type_names[order_type-1]\n\n    poster = Poster()\n    form = None\n\n    if request.method == 'POST':\n        if order_type == 1:\n            form = AddPosterForm(data=request.POST, instance=poster)\n        elif order_type == 2:\n            form = AddBongForm(data=request.POST, instance=poster)\n        elif order_type == 3:\n            # poster = GeneralOrder()\n            form = AddOtherForm(data=request.POST, instance=poster)\n\n        if form.is_valid():\n            poster = form.save(commit=False)\n            if request.POST.get('company'):\n                poster.company = Company.objects.get(pk=request.POST.get('company'))\n            poster.ordered_by = request.user\n            # Should look for a more kosher solution\n            poster.ordered_committee = request.user.groups.exclude(name='Komiteer').filter(name__contains=\"Kom\")[0]\n            poster.order_type = order_type\n\n            poster.save()\n\n            # for b in poster.__class__.__bases__:\n            # poster_mixin = OrderMixin.objects.get(id=poster.id)\n            # Let this user have permissions to show this order\n            UserObjectPermission.objects.assign_perm('view_poster_order', obj=poster, user=request.user)\n            GroupObjectPermission.objects.assign_perm('view_poster_order', obj=poster, group=Group.objects.get(name='proKom'))\n\n            title = unicode(poster)\n\n            # The great sending of emails\n            subject = '[ProKom] Ny bestilling for %s' % title\n            email_message = '%(message)s%(signature)s' % {\n                    'message': _('''\nDet har blitt registrert en ny %(order_type)sbestilling pa Online sine nettsider. Dette er bestilling nummer %(id)s.\n\\n\nAntall og type: %(num)s * %(order_type)s\\n\nArrangement: %(event_name)s\\n\nBestilt av: %(ordered_by)s i %(ordered_by_committee)s\\n\nBestilt dato: %(ordered_date)s\\n\n\\n\nFor mer informasjon, sjekk ut bestillingen her: %(absolute_url)s\n                    '''\n                    % {\n                        'site': '',\n                        'order_type': type_name.lower(),\n                        'num': poster.amount,\n                        'ordered_by': poster.ordered_by,\n                        'ordered_by_committee': poster.ordered_committee,\n                        'id': poster.id,\n                        'event_name': title,\n                        'ordered_date': poster.ordered_date,\n                        'absolute_url': request.build_absolute_uri(poster.get_dashboard_url())\n                        }\n                    ),\n                    'signature': _('\\n\\nVennlig hilsen Linjeforeningen Online')\n            }\n            from_email = settings.EMAIL_PROKOM\n            to_emails = [settings.EMAIL_PROKOM, request.user.get_email().email]\n\n            email_sent = EmailMessage(unicode(subject), unicode(email_message), from_email, to_emails, []).send()\n            if email_sent:\n                messages.success(request, 'Opprettet bestilling')\n            else:\n                messages.error(request, 'Klarte ikke \u00e5 sende epost, men bestillingen din ble fortsatt opprettet')\n\n            return redirect(poster.get_absolute_url())\n        else:\n            context['form'] = form\n            return render(request, 'posters/dashboard/add.html', context)\n\n    context[\"order_type_name\"] = type_name\n    context['order_type'] = order_type\n    context['can_edit'] = True  # request.user.has_perm('posters.view_poster')\n\n    if order_type == 1:\n        form = AddPosterForm()\n    elif order_type == 2:\n        form = AddBongForm()\n    elif order_type == 3:\n        form = AddOtherForm()\n\n    forms = (AddPosterForm(), AddBongForm(), AddOtherForm())\n\n    context['form'] = forms[order_type-1]\n\n    return render(request, 'posters/dashboard/add.html', context)\n\n\n@ensure_csrf_cookie\n@login_required\ndef edit(request, order_id=None):\n    context = get_base_context(request)\n    context['add_poster_form'] = EditPosterForm()\n\n    if order_id:\n        poster = get_object_or_404(Poster, pk=order_id)\n\n    if request.user != poster.ordered_by and 'proKom' not in request.user.groups:\n        raise PermissionDenied\n\n    if request.POST:\n        form = AddForm(request.POST, instance=poster)\n        if form.is_valid():\n            form.save()\n            # redirect_url = redirect(poster.get_absolute_url())\n            return HttpResponseRedirect(\"../detail/\"+str(poster.id))\n\n    else:\n        context[\"form\"] = AddForm(instance=poster)\n\n    return render(request, 'posters/dashboard/add.html', context)\n\n\n@ensure_csrf_cookie\n@login_required\n@permission_required('view_poster_order', (Poster, 'pk', 'order_id'), return_403=True)\ndef detail(request, order_id=None):\n    if request.is_ajax():\n        do_ajax_shit = True\n\n    if not order_id:\n        return HttpResponse(status=400)\n\n    context = get_base_context(request)\n    poster = get_object_or_404(Poster, pk=order_id)\n    context['poster'] = poster\n\n    if not has_view_perms(request.user, poster):\n        raise PermissionDenied\n\n    order_type = poster.order_type\n    type_names = (\"Plakat\", \"Bong\", \"Generell \")\n    type_name = type_names[order_type-1]\n    context[\"order_type_name\"] = type_name\n\n    if request.method == 'POST':\n        poster_status = request.POST.get('completed')\n        if poster_status == 'true' or poster_status == 'false':\n            poster.toggle_finished()\n\n    return render(request, 'posters/dashboard/details.html', context)\n\n\n# Ajax\n\n\n# @ensure_csrf_cookie\n@login_required\ndef assign_person(request):\n    if request.is_ajax():\n        if request.method == 'POST':\n            order_id = request.POST.get('order_id')\n            orders = Poster.objects.filter(pk=order_id)\n            assign_to_id = request.POST.get('assign_to_id')\n            assign_to = User.objects.get(pk=assign_to_id)\n\n            if orders.count() == 0:\n                response_text = json.dumps({'message': _(\n                    u\"\"\"Kan ikke finne en ordre med denne IDen (%s).\nOm feilen vedvarer etter en refresh, kontakt dotkom@online.ntnu.no.\"\"\") % order_id})\n                return HttpResponse(status=412, content=response_text)\n\n            order = orders[0]\n\n            if order.finished or order.assigned_to is not None:\n                response_text = json.dumps({'message': _(u\"Denne ordren er allerede behandlet.\")})\n                return HttpResponse(status=412, content=response_text)\n\n            order.assigned_to = assign_to\n            order.save()\n\n            return HttpResponse(status=200)\n", "path": "apps/posters/dashboard/views.py"}]}