We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Posters assign person bug
```
Internal Server Error: /dashboard/posters/assign_person/

ValueError at /dashboard/posters/assign_person/
invalid literal for int() with base 10: '------'
```

I think this happens if you click on the "Assign person" on a poster order, in the available poster orders list, and not select a person. 


--- 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 import logging
5 
6 from django.conf import settings
7 from django.contrib import messages
8 from django.contrib.auth.decorators import login_required
9 from django.contrib.auth.models import Group
10 from django.core.exceptions import ImproperlyConfigured, PermissionDenied
11 from django.core.mail import EmailMessage
12 from django.shortcuts import HttpResponse, HttpResponseRedirect, get_object_or_404, redirect, render
13 from django.template.loader import render_to_string
14 from django.utils.translation import ugettext as _
15 from django.views.decorators.csrf import ensure_csrf_cookie
16 from guardian.decorators import permission_required
17 from guardian.models import GroupObjectPermission, UserObjectPermission
18 
19 from apps.authentication.models import OnlineUser as User
20 from apps.companyprofile.models import Company
21 from apps.dashboard.tools import get_base_context
22 from apps.posters.forms import (AddBongForm, AddOtherForm, AddPosterForm, EditOtherForm,
23                                 EditPosterForm)
24 from apps.posters.models import Poster
25 from apps.posters.permissions import has_edit_perms, has_view_all_perms, has_view_perms
26 
27 
28 @login_required
29 @permission_required('posters.overview_poster_order', return_403=True)
30 def index(request):
31 
32     # The group with members who should populate the dropdownlist
33     group = Group.objects.get(name='proKom')
34     users_to_populate = group.user_set.all()
35 
36     context = get_base_context(request)
37 
38     # View to show if user not in committee, but wanting to see own orders
39     if not has_view_all_perms(request.user):
40         context['your_orders'] = [x for x in Poster.objects.filter(ordered_by=request.user)
41                                   if request.user.has_perm('view_poster_order', x)]
42         return render(request, 'posters/dashboard/index.html', context)
43 
44     orders = Poster.objects.all()
45 
46     context['new_orders'] = orders.filter(assigned_to=None)
47     context['active_orders'] = orders.filter(finished=False).exclude(assigned_to=None)
48     context['old_orders'] = orders.filter(finished=True)
49 
50     context['workers'] = users_to_populate
51 
52     return render(request, 'posters/dashboard/index.html', context)
53 
54 
55 @login_required
56 @permission_required('posters.add_poster_order', return_403=True)
57 def add(request, order_type=0):
58     order_type = int(order_type)
59     context = get_base_context(request)
60     type_names = ("Plakat", "Bong", "Generell ")
61     type_name = type_names[order_type-1]
62 
63     poster = Poster()
64     form = None
65 
66     if request.method == 'POST':
67         if order_type == 1:
68             form = AddPosterForm(data=request.POST, instance=poster)
69         elif order_type == 2:
70             form = AddBongForm(data=request.POST, instance=poster)
71         elif order_type == 3:
72             # poster = GeneralOrder()
73             form = AddOtherForm(data=request.POST, instance=poster)
74 
75         if form.is_valid():
76             _handle_poster_add(request, form, order_type)
77             return redirect(poster.get_absolute_url())
78         else:
79             context['form'] = form
80             context['form'].fields['ordered_committee'].queryset = request.user.groups.all()
81             return render(request, 'posters/dashboard/add.html', context)
82 
83     context["order_type_name"] = type_name
84     context['order_type'] = order_type
85     context['can_edit'] = request.user.has_perm('posters.view_poster')
86 
87     if order_type == 1:
88         AddPosterForm()
89     elif order_type == 2:
90         AddBongForm()
91     elif order_type == 3:
92         AddOtherForm()
93 
94     forms = (AddPosterForm(), AddBongForm(), AddOtherForm())
95 
96     context['form'] = forms[order_type-1]
97     context['form'].fields['ordered_committee'].queryset = request.user.groups.all()
98 
99     return render(request, 'posters/dashboard/add.html', context)
100 
101 
102 @ensure_csrf_cookie
103 @login_required
104 def edit(request, order_id=None):
105     context = get_base_context(request)
106     context['add_poster_form'] = AddPosterForm()
107 
108     if order_id:
109         poster = get_object_or_404(Poster, pk=order_id)
110     else:
111         poster = order_id
112 
113     if order_id and request.user != poster.ordered_by and 'proKom' not in request.user.groups.all():
114         raise PermissionDenied
115 
116     selected_form = EditPosterForm
117 
118     if request.POST:
119         if poster.title:
120             selected_form = EditOtherForm
121         form = selected_form(request.POST, instance=poster)
122         if form.is_valid():
123             form.save()
124             return HttpResponseRedirect("../detail/"+str(poster.id))
125         else:
126             context["form"] = form
127             context["poster"] = poster
128 
129     else:
130         selected_form = EditPosterForm
131         if poster.title:
132             selected_form = EditOtherForm
133 
134         context["form"] = selected_form(instance=poster)
135         context["poster"] = poster
136 
137     return render(request, 'posters/dashboard/add.html', context)
138 
139 
140 @ensure_csrf_cookie
141 @login_required
142 @permission_required('view_poster_order', (Poster, 'pk', 'order_id'), return_403=True)
143 def detail(request, order_id=None):
144 
145     if not order_id:
146         return HttpResponse(status=400)
147 
148     context = get_base_context(request)
149     poster = get_object_or_404(Poster, pk=order_id)
150     context['poster'] = poster
151 
152     if not has_view_perms(request.user, poster):
153         raise PermissionDenied
154 
155     order_type = poster.order_type
156     type_names = ("Plakat", "Bong", "Generell ")
157     type_name = type_names[order_type-1]
158     context["order_type_name"] = type_name
159 
160     if request.method == 'POST':
161         if not has_edit_perms(request.user, poster):
162             raise PermissionDenied
163         poster_status = request.POST.get('completed')
164         if poster_status == 'true' or poster_status == 'false':
165             poster.toggle_finished()
166 
167     return render(request, 'posters/dashboard/details.html', context)
168 
169 
170 def _handle_poster_add(request, form, order_type):
171     logger = logging.getLogger(__name__)
172 
173     poster = form.save(commit=False)
174     if request.POST.get('company'):
175         poster.company = Company.objects.get(pk=request.POST.get('company'))
176     poster.ordered_by = request.user
177     poster.order_type = order_type
178 
179     poster.save()
180 
181     # Let this user have permissions to show this order
182     UserObjectPermission.objects.assign_perm('view_poster_order', request.user, poster)
183     GroupObjectPermission.objects.assign_perm(
184         'view_poster_order',
185         Group.objects.get(name='proKom'),
186         poster
187     )
188 
189     title = str(poster)
190 
191     # The great sending of emails
192     subject = '[ProKom] Ny bestilling | %s' % title
193 
194     poster.absolute_url = request.build_absolute_uri(poster.get_dashboard_url())
195     context = {}
196     context['poster'] = poster
197     message = render_to_string('posters/email/new_order_notification.txt', context)
198 
199     from_email = settings.EMAIL_PROKOM
200     to_emails = [settings.EMAIL_PROKOM, request.user.get_email().email]
201 
202     try:
203         email_sent = EmailMessage(subject, message, from_email, to_emails, []).send()
204     except ImproperlyConfigured:
205         email_sent = False
206         logger.warn("Failed to send email for new order")
207     if email_sent:
208         messages.success(request, 'Opprettet bestilling')
209     else:
210         messages.error(request, 'Klarte ikke å sende epost, men bestillingen din ble fortsatt opprettet')
211 
212 
213 # Ajax
214 @login_required
215 def assign_person(request):
216     if request.is_ajax():
217         if request.method == 'POST':
218             order_id = request.POST.get('order_id')
219             orders = Poster.objects.filter(pk=order_id)
220             assign_to_id = request.POST.get('assign_to_id')
221             assign_to = User.objects.get(pk=assign_to_id)
222 
223             if orders.count() == 0:
224                 logging.debug("Trying to assign to non-existing order \"%s\" (user: %s)." % (order_id, request.user))
225                 response_text = json.dumps({'message': _(
226                     """Kan ikke finne en ordre med denne IDen (%s).
227 Om feilen vedvarer etter en refresh, kontakt dotkom@online.ntnu.no.""") % order_id})
228                 return HttpResponse(status=412, content=response_text)
229 
230             order = orders[0]
231 
232             if order.finished or order.assigned_to is not None:
233                 response_text = json.dumps({'message': _("Denne ordren er allerede behandlet.")})
234                 return HttpResponse(status=412, content=response_text)
235 
236             order.assigned_to = assign_to
237             order.save()
238 
239             return HttpResponse(status=200)
240
```
--- 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
@@ -215,23 +215,15 @@
 def assign_person(request):
     if request.is_ajax():
         if request.method == 'POST':
-            order_id = request.POST.get('order_id')
-            orders = Poster.objects.filter(pk=order_id)
-            assign_to_id = request.POST.get('assign_to_id')
-            assign_to = User.objects.get(pk=assign_to_id)
-
-            if orders.count() == 0:
-                logging.debug("Trying to assign to non-existing order \"%s\" (user: %s)." % (order_id, request.user))
-                response_text = json.dumps({'message': _(
-                    """Kan ikke finne en ordre med denne IDen (%s).
-Om feilen vedvarer etter en refresh, kontakt dotkom@online.ntnu.no.""") % order_id})
-                return HttpResponse(status=412, content=response_text)
-
-            order = orders[0]
+            order = get_object_or_404(Poster, pk=request.POST.get('order_id'))
+            if request.POST.get('assign_to_id') and not str(request.POST.get('assign_to_id')).isnumeric():
+                return HttpResponse(status=400, content=json.dumps(
+                    {'message': 'Denne brukerprofilen kunne ikke tilordnes til ordren.'}))
+            assign_to = get_object_or_404(User, pk=request.POST.get('assign_to_id'))
 
             if order.finished or order.assigned_to is not None:
                 response_text = json.dumps({'message': _("Denne ordren er allerede behandlet.")})
-                return HttpResponse(status=412, content=response_text)
+                return HttpResponse(status=400, content=response_text)
 
             order.assigned_to = assign_to
             order.save()

{"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@@ -215,23 +215,15 @@\n def 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-                logging.debug(\"Trying to assign to non-existing order \\\"%s\\\" (user: %s).\" % (order_id, request.user))\n-                response_text = json.dumps({'message': _(\n-                    \"\"\"Kan ikke finne en ordre med denne IDen (%s).\n-Om 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+            order = get_object_or_404(Poster, pk=request.POST.get('order_id'))\n+            if request.POST.get('assign_to_id') and not str(request.POST.get('assign_to_id')).isnumeric():\n+                return HttpResponse(status=400, content=json.dumps(\n+                    {'message': 'Denne brukerprofilen kunne ikke tilordnes til ordren.'}))\n+            assign_to = get_object_or_404(User, pk=request.POST.get('assign_to_id'))\n \n             if order.finished or order.assigned_to is not None:\n                 response_text = json.dumps({'message': _(\"Denne ordren er allerede behandlet.\")})\n-                return HttpResponse(status=412, content=response_text)\n+                return HttpResponse(status=400, content=response_text)\n \n             order.assigned_to = assign_to\n             order.save()\n", "issue": "Posters assign person bug\n```\nInternal Server Error: /dashboard/posters/assign_person/\n\nValueError at /dashboard/posters/assign_person/\ninvalid literal for int() with base 10: '------'\n```\n\nI think this happens if you click on the \"Assign person\" on a poster order, in the available poster orders list, and not select a person. \n\n", "before_files": [{"content": "# -*- encoding: utf-8 -*-\n\nimport json\nimport logging\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.exceptions import ImproperlyConfigured, PermissionDenied\nfrom django.core.mail import EmailMessage\nfrom django.shortcuts import HttpResponse, HttpResponseRedirect, get_object_or_404, redirect, render\nfrom django.template.loader import render_to_string\nfrom django.utils.translation import ugettext as _\nfrom django.views.decorators.csrf import ensure_csrf_cookie\nfrom guardian.decorators import permission_required\nfrom guardian.models import GroupObjectPermission, UserObjectPermission\n\nfrom apps.authentication.models import OnlineUser as User\nfrom apps.companyprofile.models import Company\nfrom apps.dashboard.tools import get_base_context\nfrom apps.posters.forms import (AddBongForm, AddOtherForm, AddPosterForm, EditOtherForm,\n                                EditPosterForm)\nfrom apps.posters.models import Poster\nfrom apps.posters.permissions import has_edit_perms, has_view_all_perms, has_view_perms\n\n\n@login_required\n@permission_required('posters.overview_poster_order', return_403=True)\ndef index(request):\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)\n                                  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['old_orders'] = orders.filter(finished=True)\n\n    context['workers'] = users_to_populate\n\n    return render(request, 'posters/dashboard/index.html', context)\n\n\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            _handle_poster_add(request, form, order_type)\n            return redirect(poster.get_absolute_url())\n        else:\n            context['form'] = form\n            context['form'].fields['ordered_committee'].queryset = request.user.groups.all()\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'] = request.user.has_perm('posters.view_poster')\n\n    if order_type == 1:\n        AddPosterForm()\n    elif order_type == 2:\n        AddBongForm()\n    elif order_type == 3:\n        AddOtherForm()\n\n    forms = (AddPosterForm(), AddBongForm(), AddOtherForm())\n\n    context['form'] = forms[order_type-1]\n    context['form'].fields['ordered_committee'].queryset = request.user.groups.all()\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'] = AddPosterForm()\n\n    if order_id:\n        poster = get_object_or_404(Poster, pk=order_id)\n    else:\n        poster = order_id\n\n    if order_id and request.user != poster.ordered_by and 'proKom' not in request.user.groups.all():\n        raise PermissionDenied\n\n    selected_form = EditPosterForm\n\n    if request.POST:\n        if poster.title:\n            selected_form = EditOtherForm\n        form = selected_form(request.POST, instance=poster)\n        if form.is_valid():\n            form.save()\n            return HttpResponseRedirect(\"../detail/\"+str(poster.id))\n        else:\n            context[\"form\"] = form\n            context[\"poster\"] = poster\n\n    else:\n        selected_form = EditPosterForm\n        if poster.title:\n            selected_form = EditOtherForm\n\n        context[\"form\"] = selected_form(instance=poster)\n        context[\"poster\"] = 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\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        if not has_edit_perms(request.user, poster):\n            raise PermissionDenied\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\ndef _handle_poster_add(request, form, order_type):\n    logger = logging.getLogger(__name__)\n\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    poster.order_type = order_type\n\n    poster.save()\n\n    # Let this user have permissions to show this order\n    UserObjectPermission.objects.assign_perm('view_poster_order', request.user, poster)\n    GroupObjectPermission.objects.assign_perm(\n        'view_poster_order',\n        Group.objects.get(name='proKom'),\n        poster\n    )\n\n    title = str(poster)\n\n    # The great sending of emails\n    subject = '[ProKom] Ny bestilling | %s' % title\n\n    poster.absolute_url = request.build_absolute_uri(poster.get_dashboard_url())\n    context = {}\n    context['poster'] = poster\n    message = render_to_string('posters/email/new_order_notification.txt', context)\n\n    from_email = settings.EMAIL_PROKOM\n    to_emails = [settings.EMAIL_PROKOM, request.user.get_email().email]\n\n    try:\n        email_sent = EmailMessage(subject, message, from_email, to_emails, []).send()\n    except ImproperlyConfigured:\n        email_sent = False\n        logger.warn(\"Failed to send email for new order\")\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\n# Ajax\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                logging.debug(\"Trying to assign to non-existing order \\\"%s\\\" (user: %s).\" % (order_id, request.user))\n                response_text = json.dumps({'message': _(\n                    \"\"\"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': _(\"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\nimport logging\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.exceptions import ImproperlyConfigured, PermissionDenied\nfrom django.core.mail import EmailMessage\nfrom django.shortcuts import HttpResponse, HttpResponseRedirect, get_object_or_404, redirect, render\nfrom django.template.loader import render_to_string\nfrom django.utils.translation import ugettext as _\nfrom django.views.decorators.csrf import ensure_csrf_cookie\nfrom guardian.decorators import permission_required\nfrom guardian.models import GroupObjectPermission, UserObjectPermission\n\nfrom apps.authentication.models import OnlineUser as User\nfrom apps.companyprofile.models import Company\nfrom apps.dashboard.tools import get_base_context\nfrom apps.posters.forms import (AddBongForm, AddOtherForm, AddPosterForm, EditOtherForm,\n                                EditPosterForm)\nfrom apps.posters.models import Poster\nfrom apps.posters.permissions import has_edit_perms, has_view_all_perms, has_view_perms\n\n\n@login_required\n@permission_required('posters.overview_poster_order', return_403=True)\ndef index(request):\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)\n                                  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['old_orders'] = orders.filter(finished=True)\n\n    context['workers'] = users_to_populate\n\n    return render(request, 'posters/dashboard/index.html', context)\n\n\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            _handle_poster_add(request, form, order_type)\n            return redirect(poster.get_absolute_url())\n        else:\n            context['form'] = form\n            context['form'].fields['ordered_committee'].queryset = request.user.groups.all()\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'] = request.user.has_perm('posters.view_poster')\n\n    if order_type == 1:\n        AddPosterForm()\n    elif order_type == 2:\n        AddBongForm()\n    elif order_type == 3:\n        AddOtherForm()\n\n    forms = (AddPosterForm(), AddBongForm(), AddOtherForm())\n\n    context['form'] = forms[order_type-1]\n    context['form'].fields['ordered_committee'].queryset = request.user.groups.all()\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'] = AddPosterForm()\n\n    if order_id:\n        poster = get_object_or_404(Poster, pk=order_id)\n    else:\n        poster = order_id\n\n    if order_id and request.user != poster.ordered_by and 'proKom' not in request.user.groups.all():\n        raise PermissionDenied\n\n    selected_form = EditPosterForm\n\n    if request.POST:\n        if poster.title:\n            selected_form = EditOtherForm\n        form = selected_form(request.POST, instance=poster)\n        if form.is_valid():\n            form.save()\n            return HttpResponseRedirect(\"../detail/\"+str(poster.id))\n        else:\n            context[\"form\"] = form\n            context[\"poster\"] = poster\n\n    else:\n        selected_form = EditPosterForm\n        if poster.title:\n            selected_form = EditOtherForm\n\n        context[\"form\"] = selected_form(instance=poster)\n        context[\"poster\"] = 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\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        if not has_edit_perms(request.user, poster):\n            raise PermissionDenied\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\ndef _handle_poster_add(request, form, order_type):\n    logger = logging.getLogger(__name__)\n\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    poster.order_type = order_type\n\n    poster.save()\n\n    # Let this user have permissions to show this order\n    UserObjectPermission.objects.assign_perm('view_poster_order', request.user, poster)\n    GroupObjectPermission.objects.assign_perm(\n        'view_poster_order',\n        Group.objects.get(name='proKom'),\n        poster\n    )\n\n    title = str(poster)\n\n    # The great sending of emails\n    subject = '[ProKom] Ny bestilling | %s' % title\n\n    poster.absolute_url = request.build_absolute_uri(poster.get_dashboard_url())\n    context = {}\n    context['poster'] = poster\n    message = render_to_string('posters/email/new_order_notification.txt', context)\n\n    from_email = settings.EMAIL_PROKOM\n    to_emails = [settings.EMAIL_PROKOM, request.user.get_email().email]\n\n    try:\n        email_sent = EmailMessage(subject, message, from_email, to_emails, []).send()\n    except ImproperlyConfigured:\n        email_sent = False\n        logger.warn(\"Failed to send email for new order\")\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\n# Ajax\n@login_required\ndef assign_person(request):\n    if request.is_ajax():\n        if request.method == 'POST':\n            order = get_object_or_404(Poster, pk=request.POST.get('order_id'))\n            if request.POST.get('assign_to_id') and not str(request.POST.get('assign_to_id')).isnumeric():\n                return HttpResponse(status=400, content=json.dumps(\n                    {'message': 'Denne brukerprofilen kunne ikke tilordnes til ordren.'}))\n            assign_to = get_object_or_404(User, pk=request.POST.get('assign_to_id'))\n\n            if order.finished or order.assigned_to is not None:\n                response_text = json.dumps({'message': _(\"Denne ordren er allerede behandlet.\")})\n                return HttpResponse(status=400, 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"}]}