We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Mandatory phone number in profile
It has been requested from arrkom among others and decided in HS that phone numbers in the user profile should be mandatory for people attending events. So we need to implement functionality similar to the one used for "prikkeregler". 

If users hide this in their profile the info could behave as allergies and only show up when events are exported to pdf. 


--- 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/events/views.py`
Content:
```
1 #-*- coding: utf-8 -*-
2 
3 import datetime
4 
5 from django.utils import timezone
6 
7 from django.conf import settings
8 from django.contrib import messages
9 from django.contrib.auth.decorators import login_required, user_passes_test
10 from django.core.urlresolvers import reverse
11 from django.http import HttpResponseRedirect
12 from django.shortcuts import render, get_object_or_404, redirect
13 from django.utils.translation import ugettext as _
14 
15 import watson
16 
17 from apps.events.forms import CaptchaForm
18 from apps.events.models import Event, AttendanceEvent, Attendee
19 from apps.events.pdf_generator import EventPDF
20 
21 
22 def index(request):
23     return render(request, 'events/index.html', {})
24 
25 def details(request, event_id, event_slug):
26     event = get_object_or_404(Event, pk=event_id)
27 
28     is_attendance_event = False
29     user_anonymous = True
30     user_attending = False
31     place_on_wait_list = 0
32     will_be_on_wait_list = False
33     rules = []
34     user_status = False
35 
36     try:
37         attendance_event = AttendanceEvent.objects.get(pk=event_id)
38         is_attendance_event = True
39         form = CaptchaForm(user=request.user)
40 
41         if attendance_event.rule_bundles:
42             for rule_bundle in attendance_event.rule_bundles.all():
43                 rules.append(rule_bundle.get_rule_strings)
44 
45         if request.user.is_authenticated():
46             user_anonymous = False
47             if attendance_event.is_attendee(request.user):
48                 user_attending = True
49 
50             
51             will_be_on_wait_list = attendance_event.will_i_be_on_wait_list
52 
53             user_status = event.is_eligible_for_signup(request.user)
54 
55             # Check if this user is on the waitlist
56             place_on_wait_list = event.what_place_is_user_on_wait_list(request.user)
57 
58     except AttendanceEvent.DoesNotExist:
59         pass
60 
61     if is_attendance_event:
62         context = {
63                 'now': timezone.now(),
64                 'event': event,
65                 'attendance_event': attendance_event,
66                 'user_anonymous': user_anonymous,
67                 'user_attending': user_attending,
68                 'will_be_on_wait_list': will_be_on_wait_list,
69                 'rules': rules,
70                 'user_status': user_status,
71                 'place_on_wait_list': int(place_on_wait_list),
72                 #'position_in_wait_list': position_in_wait_list,
73                 'captcha_form': form,
74         }
75         
76         return render(request, 'events/details.html', context)
77     else:
78         return render(request, 'events/details.html', {'event': event})
79 
80 
81 def get_attendee(attendee_id):
82     return get_object_or_404(Attendee, pk=attendee_id)
83 
84 @login_required
85 def attendEvent(request, event_id):
86     
87     event = get_object_or_404(Event, pk=event_id)
88 
89     if not request.POST:
90         messages.error(request, _(u'Vennligst fyll ut skjemaet.'))
91         return redirect(event)
92     form = CaptchaForm(request.POST, user=request.user)
93 
94     if not form.is_valid():
95         if not 'mark_rules' in request.POST and not request.user.mark_rules:
96             error_message = u'Du må godta prikkreglene for å melde deg på.'
97         else:
98             error_message = u'Du klarte ikke captcha-en. Er du en bot?'
99         messages.error(request, _(error_message))
100         return redirect(event)
101 
102     # Check if the user is eligible to attend this event.
103     # If not, an error message will be present in the returned dict
104     attendance_event = event.attendance_event
105 
106     response = event.is_eligible_for_signup(request.user);
107 
108     if response['status']:   
109         # First time accepting mark rules
110         if 'mark_rules' in form.cleaned_data:
111             request.user.mark_rules = True
112             request.user.save()
113         Attendee(event=attendance_event, user=request.user).save()
114         messages.success(request, _(u"Du er nå påmeldt på arrangementet!"))
115         return redirect(event)
116     else:
117         messages.error(request, response['message'])
118         return redirect(event)
119 
120 @login_required
121 def unattendEvent(request, event_id):
122 
123     event = get_object_or_404(Event, pk=event_id)
124     attendance_event = event.attendance_event
125 
126     # Check if the deadline for unattending has passed
127     if attendance_event.unattend_deadline < timezone.now():
128         messages.error(request, _(u"Avmeldingsfristen for dette arrangementet har utløpt."))
129         return redirect(event)
130 
131     event.notify_waiting_list(host=request.META['HTTP_HOST'], unattended_user=request.user)
132     Attendee.objects.get(event=attendance_event, user=request.user).delete()
133 
134     messages.success(request, _(u"Du ble meldt av arrangementet."))
135     return redirect(event)
136 
137 def search_events(request):
138     query = request.GET.get('query')
139     filters = {
140         'future' : request.GET.get('future'),
141         'myevents' : request.GET.get('myevents')
142     }
143     events = _search_indexed(request, query, filters)
144 
145     return render(request, 'events/search.html', {'events': events})
146 
147 
148 def _search_indexed(request, query, filters):
149     results = []
150     kwargs = {}
151 
152     if filters['future'] == 'true':
153         kwargs['event_start__gte'] = timezone.now()
154 
155     if filters['myevents'] == 'true':
156         kwargs['attendance_event__attendees'] = request.user
157 
158     events = Event.objects.filter(**kwargs).order_by('event_start').prefetch_related(
159             'attendance_event', 'attendance_event__attendees')
160 
161     if query:
162         for result in watson.search(query, models=(events,)):
163             results.append(result.object)
164         return results[:10]
165 
166     return events
167 
168 
169 @login_required()
170 @user_passes_test(lambda u: u.groups.filter(name='Komiteer').count() == 1)
171 def generate_pdf(request, event_id):
172 
173     event = get_object_or_404(Event, pk=event_id)
174 
175     groups = request.user.groups.all()
176     if not (groups.filter(name='dotKom').count() == 1 or groups.filter(name='Hovedstyret').count() == 1):
177         if event.event_type == 1 and not groups.filter(name='arrKom').count() == 1:
178             messages.error(request, _(u'Du har ikke tilgang til listen for dette arrangementet.'))
179             return redirect(event)
180 
181         if event.event_type == 2 and not groups.filter(name='bedKom').count() == 1:
182             messages.error(request, _(u'Du har ikke tilgang til listen for dette arrangementet.'))
183             return redirect(event)
184 
185         if event.event_type == 3 and not groups.filter(name='fagKom').count() == 1:
186             messages.error(request, _(u'Du har ikke tilgang til listen for dette arrangementet.'))  
187             return redirect(event)
188 
189     return EventPDF(event).render_pdf()
190
```

Path: `apps/events/forms.py`
Content:
```
1 from django import forms
2 from captcha.fields import CaptchaField
3 
4 class CaptchaForm(forms.Form):
5     def __init__(self, *args, **kwargs):
6         user = kwargs.pop('user', None)
7         super(CaptchaForm, self).__init__(*args, **kwargs)
8         # Removing mark rules field if user has already accepted the rules
9         if user and user.is_authenticated() and user.mark_rules:
10             del self.fields['mark_rules']
11     mark_rules = forms.BooleanField(label=u'Jeg godtar <a href="/profile/#marks" target="_blank">prikkreglene</a>')
12     captcha = CaptchaField()
13
```
--- 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/events/forms.py b/apps/events/forms.py
--- a/apps/events/forms.py
+++ b/apps/events/forms.py
@@ -1,12 +1,48 @@
+#-*- coding: utf-8 -*-
+
 from django import forms
 from captcha.fields import CaptchaField
+from django.utils.translation import ugettext as _
 
 class CaptchaForm(forms.Form):
+
+    phone_number = forms.CharField(label=_(u'Telefonnummer er påkrevd for å være påmeldt et arrangement.'),
+                                   error_messages={'required' : _(u'Telefonnummer er påkrevd!')})
+    mark_rules = forms.BooleanField(label=_(u'Jeg godtar <a href="/profile/#marks" target="_blank">prikkreglene</a>'),
+                                    error_messages={'required' : _(u'Du må godta prikkereglene!')})
+    captcha = CaptchaField(error_messages={'required' : _(u'Du klarte ikke captchaen! Er du en bot?')})
+
     def __init__(self, *args, **kwargs):
-        user = kwargs.pop('user', None)
+        self.user = kwargs.pop('user', None)
         super(CaptchaForm, self).__init__(*args, **kwargs)
+
         # Removing mark rules field if user has already accepted the rules
-        if user and user.is_authenticated() and user.mark_rules:
-            del self.fields['mark_rules']
-    mark_rules = forms.BooleanField(label=u'Jeg godtar <a href="/profile/#marks" target="_blank">prikkreglene</a>')
-    captcha = CaptchaField()
+        if self.user and self.user.is_authenticated():
+            if self.user.mark_rules:
+                del self.fields['mark_rules']
+
+            if self.user.phone_number:
+                del self.fields['phone_number']
+
+
+    def clean(self):
+        super(CaptchaForm, self).clean()
+        cleaned_data = self.cleaned_data
+
+        if 'mark_rules' in self.fields:
+            if 'mark_rules' in cleaned_data:
+                mark_rules = cleaned_data['mark_rules']
+
+                if mark_rules:
+                    self.user.mark_rules = True
+                    self.user.save()
+
+        if 'phone_number' in self.fields:
+            if 'phone_number' in cleaned_data:
+                phone_number = cleaned_data['phone_number']
+
+                if phone_number:
+                    self.user.phone_number = phone_number
+                    self.user.save()
+
+        return cleaned_data
\ No newline at end of file
diff --git a/apps/events/views.py b/apps/events/views.py
--- a/apps/events/views.py
+++ b/apps/events/views.py
@@ -89,14 +89,14 @@
     if not request.POST:
         messages.error(request, _(u'Vennligst fyll ut skjemaet.'))
         return redirect(event)
+
     form = CaptchaForm(request.POST, user=request.user)
 
     if not form.is_valid():
-        if not 'mark_rules' in request.POST and not request.user.mark_rules:
-            error_message = u'Du må godta prikkreglene for å melde deg på.'
-        else:
-            error_message = u'Du klarte ikke captcha-en. Er du en bot?'
-        messages.error(request, _(error_message))
+        for field,errors in form.errors.items():
+            for error in errors:
+                messages.error(request, error)
+
         return redirect(event)
 
     # Check if the user is eligible to attend this event.
@@ -106,10 +106,6 @@
     response = event.is_eligible_for_signup(request.user);
 
     if response['status']:   
-        # First time accepting mark rules
-        if 'mark_rules' in form.cleaned_data:
-            request.user.mark_rules = True
-            request.user.save()
         Attendee(event=attendance_event, user=request.user).save()
         messages.success(request, _(u"Du er nå påmeldt på arrangementet!"))
         return redirect(event)

{"golden_diff": "diff --git a/apps/events/forms.py b/apps/events/forms.py\n--- a/apps/events/forms.py\n+++ b/apps/events/forms.py\n@@ -1,12 +1,48 @@\n+#-*- coding: utf-8 -*-\n+\n from django import forms\n from captcha.fields import CaptchaField\n+from django.utils.translation import ugettext as _\n \n class CaptchaForm(forms.Form):\n+\n+    phone_number = forms.CharField(label=_(u'Telefonnummer er p\u00e5krevd for \u00e5 v\u00e6re p\u00e5meldt et arrangement.'),\n+                                   error_messages={'required' : _(u'Telefonnummer er p\u00e5krevd!')})\n+    mark_rules = forms.BooleanField(label=_(u'Jeg godtar <a href=\"/profile/#marks\" target=\"_blank\">prikkreglene</a>'),\n+                                    error_messages={'required' : _(u'Du m\u00e5 godta prikkereglene!')})\n+    captcha = CaptchaField(error_messages={'required' : _(u'Du klarte ikke captchaen! Er du en bot?')})\n+\n     def __init__(self, *args, **kwargs):\n-        user = kwargs.pop('user', None)\n+        self.user = kwargs.pop('user', None)\n         super(CaptchaForm, self).__init__(*args, **kwargs)\n+\n         # Removing mark rules field if user has already accepted the rules\n-        if user and user.is_authenticated() and user.mark_rules:\n-            del self.fields['mark_rules']\n-    mark_rules = forms.BooleanField(label=u'Jeg godtar <a href=\"/profile/#marks\" target=\"_blank\">prikkreglene</a>')\n-    captcha = CaptchaField()\n+        if self.user and self.user.is_authenticated():\n+            if self.user.mark_rules:\n+                del self.fields['mark_rules']\n+\n+            if self.user.phone_number:\n+                del self.fields['phone_number']\n+\n+\n+    def clean(self):\n+        super(CaptchaForm, self).clean()\n+        cleaned_data = self.cleaned_data\n+\n+        if 'mark_rules' in self.fields:\n+            if 'mark_rules' in cleaned_data:\n+                mark_rules = cleaned_data['mark_rules']\n+\n+                if mark_rules:\n+                    self.user.mark_rules = True\n+                    self.user.save()\n+\n+        if 'phone_number' in self.fields:\n+            if 'phone_number' in cleaned_data:\n+                phone_number = cleaned_data['phone_number']\n+\n+                if phone_number:\n+                    self.user.phone_number = phone_number\n+                    self.user.save()\n+\n+        return cleaned_data\n\\ No newline at end of file\ndiff --git a/apps/events/views.py b/apps/events/views.py\n--- a/apps/events/views.py\n+++ b/apps/events/views.py\n@@ -89,14 +89,14 @@\n     if not request.POST:\n         messages.error(request, _(u'Vennligst fyll ut skjemaet.'))\n         return redirect(event)\n+\n     form = CaptchaForm(request.POST, user=request.user)\n \n     if not form.is_valid():\n-        if not 'mark_rules' in request.POST and not request.user.mark_rules:\n-            error_message = u'Du m\u00e5 godta prikkreglene for \u00e5 melde deg p\u00e5.'\n-        else:\n-            error_message = u'Du klarte ikke captcha-en. Er du en bot?'\n-        messages.error(request, _(error_message))\n+        for field,errors in form.errors.items():\n+            for error in errors:\n+                messages.error(request, error)\n+\n         return redirect(event)\n \n     # Check if the user is eligible to attend this event.\n@@ -106,10 +106,6 @@\n     response = event.is_eligible_for_signup(request.user);\n \n     if response['status']:   \n-        # First time accepting mark rules\n-        if 'mark_rules' in form.cleaned_data:\n-            request.user.mark_rules = True\n-            request.user.save()\n         Attendee(event=attendance_event, user=request.user).save()\n         messages.success(request, _(u\"Du er n\u00e5 p\u00e5meldt p\u00e5 arrangementet!\"))\n         return redirect(event)\n", "issue": "Mandatory phone number in profile\nIt has been requested from arrkom among others and decided in HS that phone numbers in the user profile should be mandatory for people attending events. So we need to implement functionality similar to the one used for \"prikkeregler\". \n\nIf users hide this in their profile the info could behave as allergies and only show up when events are exported to pdf. \n\n", "before_files": [{"content": "#-*- coding: utf-8 -*-\n\nimport datetime\n\nfrom django.utils import timezone\n\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required, user_passes_test\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.utils.translation import ugettext as _\n\nimport watson\n\nfrom apps.events.forms import CaptchaForm\nfrom apps.events.models import Event, AttendanceEvent, Attendee\nfrom apps.events.pdf_generator import EventPDF\n\n\ndef index(request):\n    return render(request, 'events/index.html', {})\n\ndef details(request, event_id, event_slug):\n    event = get_object_or_404(Event, pk=event_id)\n\n    is_attendance_event = False\n    user_anonymous = True\n    user_attending = False\n    place_on_wait_list = 0\n    will_be_on_wait_list = False\n    rules = []\n    user_status = False\n\n    try:\n        attendance_event = AttendanceEvent.objects.get(pk=event_id)\n        is_attendance_event = True\n        form = CaptchaForm(user=request.user)\n\n        if attendance_event.rule_bundles:\n            for rule_bundle in attendance_event.rule_bundles.all():\n                rules.append(rule_bundle.get_rule_strings)\n\n        if request.user.is_authenticated():\n            user_anonymous = False\n            if attendance_event.is_attendee(request.user):\n                user_attending = True\n\n            \n            will_be_on_wait_list = attendance_event.will_i_be_on_wait_list\n\n            user_status = event.is_eligible_for_signup(request.user)\n\n            # Check if this user is on the waitlist\n            place_on_wait_list = event.what_place_is_user_on_wait_list(request.user)\n\n    except AttendanceEvent.DoesNotExist:\n        pass\n\n    if is_attendance_event:\n        context = {\n                'now': timezone.now(),\n                'event': event,\n                'attendance_event': attendance_event,\n                'user_anonymous': user_anonymous,\n                'user_attending': user_attending,\n                'will_be_on_wait_list': will_be_on_wait_list,\n                'rules': rules,\n                'user_status': user_status,\n                'place_on_wait_list': int(place_on_wait_list),\n                #'position_in_wait_list': position_in_wait_list,\n                'captcha_form': form,\n        }\n        \n        return render(request, 'events/details.html', context)\n    else:\n        return render(request, 'events/details.html', {'event': event})\n\n\ndef get_attendee(attendee_id):\n    return get_object_or_404(Attendee, pk=attendee_id)\n\n@login_required\ndef attendEvent(request, event_id):\n    \n    event = get_object_or_404(Event, pk=event_id)\n\n    if not request.POST:\n        messages.error(request, _(u'Vennligst fyll ut skjemaet.'))\n        return redirect(event)\n    form = CaptchaForm(request.POST, user=request.user)\n\n    if not form.is_valid():\n        if not 'mark_rules' in request.POST and not request.user.mark_rules:\n            error_message = u'Du m\u00e5 godta prikkreglene for \u00e5 melde deg p\u00e5.'\n        else:\n            error_message = u'Du klarte ikke captcha-en. Er du en bot?'\n        messages.error(request, _(error_message))\n        return redirect(event)\n\n    # Check if the user is eligible to attend this event.\n    # If not, an error message will be present in the returned dict\n    attendance_event = event.attendance_event\n\n    response = event.is_eligible_for_signup(request.user);\n\n    if response['status']:   \n        # First time accepting mark rules\n        if 'mark_rules' in form.cleaned_data:\n            request.user.mark_rules = True\n            request.user.save()\n        Attendee(event=attendance_event, user=request.user).save()\n        messages.success(request, _(u\"Du er n\u00e5 p\u00e5meldt p\u00e5 arrangementet!\"))\n        return redirect(event)\n    else:\n        messages.error(request, response['message'])\n        return redirect(event)\n\n@login_required\ndef unattendEvent(request, event_id):\n\n    event = get_object_or_404(Event, pk=event_id)\n    attendance_event = event.attendance_event\n\n    # Check if the deadline for unattending has passed\n    if attendance_event.unattend_deadline < timezone.now():\n        messages.error(request, _(u\"Avmeldingsfristen for dette arrangementet har utl\u00f8pt.\"))\n        return redirect(event)\n\n    event.notify_waiting_list(host=request.META['HTTP_HOST'], unattended_user=request.user)\n    Attendee.objects.get(event=attendance_event, user=request.user).delete()\n\n    messages.success(request, _(u\"Du ble meldt av arrangementet.\"))\n    return redirect(event)\n\ndef search_events(request):\n    query = request.GET.get('query')\n    filters = {\n        'future' : request.GET.get('future'),\n        'myevents' : request.GET.get('myevents')\n    }\n    events = _search_indexed(request, query, filters)\n\n    return render(request, 'events/search.html', {'events': events})\n\n\ndef _search_indexed(request, query, filters):\n    results = []\n    kwargs = {}\n\n    if filters['future'] == 'true':\n        kwargs['event_start__gte'] = timezone.now()\n\n    if filters['myevents'] == 'true':\n        kwargs['attendance_event__attendees'] = request.user\n\n    events = Event.objects.filter(**kwargs).order_by('event_start').prefetch_related(\n            'attendance_event', 'attendance_event__attendees')\n\n    if query:\n        for result in watson.search(query, models=(events,)):\n            results.append(result.object)\n        return results[:10]\n\n    return events\n\n\n@login_required()\n@user_passes_test(lambda u: u.groups.filter(name='Komiteer').count() == 1)\ndef generate_pdf(request, event_id):\n\n    event = get_object_or_404(Event, pk=event_id)\n\n    groups = request.user.groups.all()\n    if not (groups.filter(name='dotKom').count() == 1 or groups.filter(name='Hovedstyret').count() == 1):\n        if event.event_type == 1 and not groups.filter(name='arrKom').count() == 1:\n            messages.error(request, _(u'Du har ikke tilgang til listen for dette arrangementet.'))\n            return redirect(event)\n\n        if event.event_type == 2 and not groups.filter(name='bedKom').count() == 1:\n            messages.error(request, _(u'Du har ikke tilgang til listen for dette arrangementet.'))\n            return redirect(event)\n\n        if event.event_type == 3 and not groups.filter(name='fagKom').count() == 1:\n            messages.error(request, _(u'Du har ikke tilgang til listen for dette arrangementet.'))  \n            return redirect(event)\n\n    return EventPDF(event).render_pdf()\n", "path": "apps/events/views.py"}, {"content": "from django import forms\nfrom captcha.fields import CaptchaField\n\nclass CaptchaForm(forms.Form):\n    def __init__(self, *args, **kwargs):\n        user = kwargs.pop('user', None)\n        super(CaptchaForm, self).__init__(*args, **kwargs)\n        # Removing mark rules field if user has already accepted the rules\n        if user and user.is_authenticated() and user.mark_rules:\n            del self.fields['mark_rules']\n    mark_rules = forms.BooleanField(label=u'Jeg godtar <a href=\"/profile/#marks\" target=\"_blank\">prikkreglene</a>')\n    captcha = CaptchaField()\n", "path": "apps/events/forms.py"}], "after_files": [{"content": "#-*- coding: utf-8 -*-\n\nimport datetime\n\nfrom django.utils import timezone\n\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required, user_passes_test\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.utils.translation import ugettext as _\n\nimport watson\n\nfrom apps.events.forms import CaptchaForm\nfrom apps.events.models import Event, AttendanceEvent, Attendee\nfrom apps.events.pdf_generator import EventPDF\n\n\ndef index(request):\n    return render(request, 'events/index.html', {})\n\ndef details(request, event_id, event_slug):\n    event = get_object_or_404(Event, pk=event_id)\n\n    is_attendance_event = False\n    user_anonymous = True\n    user_attending = False\n    place_on_wait_list = 0\n    will_be_on_wait_list = False\n    rules = []\n    user_status = False\n\n    try:\n        attendance_event = AttendanceEvent.objects.get(pk=event_id)\n        is_attendance_event = True\n        form = CaptchaForm(user=request.user)\n\n        if attendance_event.rule_bundles:\n            for rule_bundle in attendance_event.rule_bundles.all():\n                rules.append(rule_bundle.get_rule_strings)\n\n        if request.user.is_authenticated():\n            user_anonymous = False\n            if attendance_event.is_attendee(request.user):\n                user_attending = True\n\n            \n            will_be_on_wait_list = attendance_event.will_i_be_on_wait_list\n\n            user_status = event.is_eligible_for_signup(request.user)\n\n            # Check if this user is on the waitlist\n            place_on_wait_list = event.what_place_is_user_on_wait_list(request.user)\n\n    except AttendanceEvent.DoesNotExist:\n        pass\n\n    if is_attendance_event:\n        context = {\n                'now': timezone.now(),\n                'event': event,\n                'attendance_event': attendance_event,\n                'user_anonymous': user_anonymous,\n                'user_attending': user_attending,\n                'will_be_on_wait_list': will_be_on_wait_list,\n                'rules': rules,\n                'user_status': user_status,\n                'place_on_wait_list': int(place_on_wait_list),\n                #'position_in_wait_list': position_in_wait_list,\n                'captcha_form': form,\n        }\n        \n        return render(request, 'events/details.html', context)\n    else:\n        return render(request, 'events/details.html', {'event': event})\n\n\ndef get_attendee(attendee_id):\n    return get_object_or_404(Attendee, pk=attendee_id)\n\n@login_required\ndef attendEvent(request, event_id):\n    \n    event = get_object_or_404(Event, pk=event_id)\n\n    if not request.POST:\n        messages.error(request, _(u'Vennligst fyll ut skjemaet.'))\n        return redirect(event)\n\n    form = CaptchaForm(request.POST, user=request.user)\n\n    if not form.is_valid():\n        for field,errors in form.errors.items():\n            for error in errors:\n                messages.error(request, error)\n\n        return redirect(event)\n\n    # Check if the user is eligible to attend this event.\n    # If not, an error message will be present in the returned dict\n    attendance_event = event.attendance_event\n\n    response = event.is_eligible_for_signup(request.user);\n\n    if response['status']:   \n        Attendee(event=attendance_event, user=request.user).save()\n        messages.success(request, _(u\"Du er n\u00e5 p\u00e5meldt p\u00e5 arrangementet!\"))\n        return redirect(event)\n    else:\n        messages.error(request, response['message'])\n        return redirect(event)\n\n@login_required\ndef unattendEvent(request, event_id):\n\n    event = get_object_or_404(Event, pk=event_id)\n    attendance_event = event.attendance_event\n\n    # Check if the deadline for unattending has passed\n    if attendance_event.unattend_deadline < timezone.now():\n        messages.error(request, _(u\"Avmeldingsfristen for dette arrangementet har utl\u00f8pt.\"))\n        return redirect(event)\n    \n    Attendee.objects.get(event=attendance_event, user=request.user).delete()\n\n    messages.success(request, _(u\"Du ble meldt av arrangementet.\"))\n    return redirect(event)\n\ndef search_events(request):\n    query = request.GET.get('query')\n    filters = {\n        'future' : request.GET.get('future'),\n        'myevents' : request.GET.get('myevents')\n    }\n    events = _search_indexed(request, query, filters)\n\n    return render(request, 'events/search.html', {'events': events})\n\n\ndef _search_indexed(request, query, filters):\n    results = []\n    kwargs = {}\n\n    if filters['future'] == 'true':\n        kwargs['event_start__gte'] = timezone.now()\n\n    if filters['myevents'] == 'true':\n        kwargs['attendance_event__attendees'] = request.user\n\n    events = Event.objects.filter(**kwargs).order_by('event_start').prefetch_related(\n            'attendance_event', 'attendance_event__attendees')\n\n    if query:\n        for result in watson.search(query, models=(events,)):\n            results.append(result.object)\n        return results[:10]\n\n    return events\n\n\n@login_required()\n@user_passes_test(lambda u: u.groups.filter(name='Komiteer').count() == 1)\ndef generate_pdf(request, event_id):\n\n    event = get_object_or_404(Event, pk=event_id)\n\n    groups = request.user.groups.all()\n    if not (groups.filter(name='dotKom').count() == 1 or groups.filter(name='Hovedstyret').count() == 1):\n        if event.event_type == 1 and not groups.filter(name='arrKom').count() == 1:\n            messages.error(request, _(u'Du har ikke tilgang til listen for dette arrangementet.'))\n            return redirect(event)\n\n        if event.event_type == 2 and not groups.filter(name='bedKom').count() == 1:\n            messages.error(request, _(u'Du har ikke tilgang til listen for dette arrangementet.'))\n            return redirect(event)\n\n        if event.event_type == 3 and not groups.filter(name='fagKom').count() == 1:\n            messages.error(request, _(u'Du har ikke tilgang til listen for dette arrangementet.'))  \n            return redirect(event)\n\n    return EventPDF(event).render_pdf()\n", "path": "apps/events/views.py"}, {"content": "#-*- coding: utf-8 -*-\n\nfrom django import forms\nfrom captcha.fields import CaptchaField\nfrom django.utils.translation import ugettext as _\n\nclass CaptchaForm(forms.Form):\n\n    phone_number = forms.CharField(label=_(u'Telefonnummer er p\u00e5krevd for \u00e5 v\u00e6re p\u00e5meldt et arrangement.'),\n                                   error_messages={'required' : _(u'Telefonnummer er p\u00e5krevd!')})\n    mark_rules = forms.BooleanField(label=_(u'Jeg godtar <a href=\"/profile/#marks\" target=\"_blank\">prikkreglene</a>'),\n                                    error_messages={'required' : _(u'Du m\u00e5 godta prikkereglene!')})\n    captcha = CaptchaField(error_messages={'required' : _(u'Du klarte ikke captchaen! Er du en bot?')})\n\n    def __init__(self, *args, **kwargs):\n        self.user = kwargs.pop('user', None)\n        super(CaptchaForm, self).__init__(*args, **kwargs)\n\n        # Removing mark rules field if user has already accepted the rules\n        if self.user and self.user.is_authenticated():\n            if self.user.mark_rules:\n                del self.fields['mark_rules']\n\n            if self.user.phone_number:\n                del self.fields['phone_number']\n\n\n    def clean(self):\n        super(CaptchaForm, self).clean()\n        cleaned_data = self.cleaned_data\n\n        if 'mark_rules' in self.fields:\n            if 'mark_rules' in cleaned_data:\n                mark_rules = cleaned_data['mark_rules']\n\n                if mark_rules:\n                    self.user.mark_rules = True\n                    self.user.save()\n\n        if 'phone_number' in self.fields:\n            if 'phone_number' in cleaned_data:\n                phone_number = cleaned_data['phone_number']\n\n                if phone_number:\n                    self.user.phone_number = phone_number\n                    self.user.save()\n\n        return cleaned_data", "path": "apps/events/forms.py"}]}