We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[Feedback] - Display to the users what questions the company will see.
Illustrate in someway the questions that will be visible to the company.


--- 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/feedback/views.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 import json
3 
4 from collections import namedtuple, defaultdict
5 
6 from django.http import Http404, HttpResponse
7 from django.shortcuts import render, redirect, get_object_or_404
8 from django.contrib.contenttypes.models import ContentType
9 from django.contrib import messages
10 from django.contrib.auth.decorators import login_required
11 from django.core.exceptions import ObjectDoesNotExist
12 from django.utils.translation import ugettext_lazy as _
13 
14 from apps.feedback.models import (
15     FeedbackRelation,
16     FieldOfStudyAnswer,
17     RATING_CHOICES,
18     TextQuestion,
19     TextAnswer,
20     RegisterToken
21 )
22 from apps.feedback.forms import create_answer_forms
23 from apps.feedback.utils import has_permission, can_delete, get_group_restricted_feedback_relations
24 
25 
26 @login_required
27 def feedback(request, applabel, appmodel, object_id, feedback_id):
28     feedback_relation = _get_fbr_or_404(applabel, appmodel, object_id, feedback_id)
29 
30     if not feedback_relation.can_answer(request.user):
31         messages.error(request, feedback_relation.answer_error_message(request.user))
32         return redirect("home")
33 
34     if request.method == "POST":
35         answers = create_answer_forms(feedback_relation, post_data=request.POST)
36         if all([a.is_valid() for a in answers]):
37             for a in answers:
38                 a.save()
39 
40             # mark that the user has answered
41             feedback_relation.answered.add(request.user)
42             feedback_relation.save()
43 
44             # Set field of study automaticly
45             fosa = FieldOfStudyAnswer(feedback_relation=feedback_relation, answer=request.user.field_of_study)
46             fosa.save()
47 
48             messages.success(request, _(u"Takk for at du svarte."))
49             return redirect("home")
50         else:
51             messages.error(request, _(u"Du må svare på alle påkrevde felt."))
52     else:
53         answers = create_answer_forms(feedback_relation)
54 
55     description = feedback_relation.description
56 
57     return render(
58         request,
59         'feedback/answer.html',
60         {'answers': answers, 'description': description}
61     )
62 
63 
64 @login_required
65 def result(request, applabel, appmodel, object_id, feedback_id):
66     feedback_relation = _get_fbr_or_404(applabel, appmodel, object_id, feedback_id)
67 
68     if not has_permission(feedback_relation, request.user):
69         messages.error(request, _(u"Du har ikke tilgang til dette skjemaet."))
70         return redirect("home")
71 
72     return feedback_results(request, feedback_relation)
73 
74 
75 def results_token(request, applabel, appmodel, object_id, feedback_id,  token):
76     feedback_relation = _get_fbr_or_404(applabel, appmodel, object_id, feedback_id)
77     register_token = get_object_or_404(RegisterToken, token=token)
78 
79     if register_token.is_valid(feedback_relation):
80         return feedback_results(request, feedback_relation, True)
81     else:
82         return HttpResponse('Unauthorized', status=401)
83 
84 
85 def feedback_results(request, feedback_relation, token=False):
86     qa = namedtuple("Qa", "question, answers")
87     question_and_answers = []
88 
89     for question in feedback_relation.questions:
90         if (question.display or not token) and isinstance(question, TextQuestion):
91             question_and_answers.append(qa(question, feedback_relation.answers_to_question(question)))
92 
93     info = None
94 
95     if feedback_relation.feedback.display_info or not token:
96         info = feedback_relation.content_info()
97         info[_(u'Besvarelser')] = feedback_relation.answered.count()
98 
99     register_token = get_object_or_404(RegisterToken, fbr=feedback_relation)
100 
101     token_url = u"%s%sresults/%s" % (
102         request.META['HTTP_HOST'],
103         feedback_relation.get_absolute_url(),
104         register_token.token
105     )
106 
107     return render(
108         request,
109         'feedback/results.html',
110         {
111             'question_and_answers': question_and_answers,
112             'description': feedback_relation.description,
113             'token_url': token_url,
114             'token': token,
115             'info': info
116         }
117     )
118 
119 
120 @login_required
121 def chart_data(request, applabel, appmodel, object_id, feedback_id):
122     feedback_relation = _get_fbr_or_404(applabel, appmodel, object_id, feedback_id)
123 
124     if not has_permission(feedback_relation, request.user):
125         messages.error(request, _(u"Du har ikke tilgang til denne dataen."))
126         return redirect("home")
127 
128     return get_chart_data(request, feedback_relation)
129 
130 
131 def chart_data_token(request, applabel, appmodel, object_id, feedback_id, token):
132     feedback_relation = _get_fbr_or_404(applabel, appmodel, object_id, feedback_id)
133     register_token = get_object_or_404(RegisterToken, token=token)
134 
135     if register_token.is_valid(feedback_relation):
136         return get_chart_data(request, feedback_relation, True)
137     else:
138         return HttpResponse('Unauthorized', status=401)
139 
140 
141 def get_chart_data(request, feedback_relation, token=False):
142     rating_answers = []
143     rating_titles = []
144     answer_collection = dict()
145     answer_collection['replies'] = dict()
146     answer_length = int(len(RATING_CHOICES))
147     for question in feedback_relation.ratingquestion:
148         if question.display or not token:
149             rating_titles.append(str(question))
150             answers = feedback_relation.answers_to_question(question)
151             answer_count = [0] * answer_length
152             for answer in answers:
153                 answer_count[int(answer.answer)] += 1
154             rating_answers.append(answer_count[1:])
155 
156     fos_answer_count = defaultdict(int)
157 
158     if feedback_relation.feedback.display_field_of_study or not token:
159         fos = feedback_relation.field_of_study_answers.all()
160         for answer in fos:
161             fos_answer_count[str(answer)] += 1
162 
163     mc_questions = []
164     mc_answer_count = []
165 
166     for question in feedback_relation.multiple_choice_question:
167         if question.display or not token:
168             mc_questions.append(unicode(question))
169             answer_count = defaultdict(int)
170             for answer in feedback_relation.answers_to_question(question):
171                 answer_count[str(answer)] += 1
172             mc_answer_count.append(answer_count.items())
173 
174     answer_collection['replies']['ratings'] = rating_answers
175     answer_collection['replies']['titles'] = rating_titles
176     answer_collection['replies']['mc_questions'] = mc_questions
177     answer_collection['replies']['mc_answers'] = mc_answer_count
178     answer_collection['replies']['fos'] = fos_answer_count.items()
179 
180     return HttpResponse(json.dumps(answer_collection), content_type='application/json')
181 
182 
183 @login_required
184 def index(request):
185     feedback_relations = get_group_restricted_feedback_relations(request.user)
186     return render(request, 'feedback/index.html', {'feedbacks': feedback_relations})
187 
188 
189 @login_required
190 def delete_answer(request):
191     if request.method == 'POST':
192         answer_id = request.POST.get('answer_id')
193         answer = get_object_or_404(TextAnswer, pk=answer_id)
194 
195         if can_delete(answer, request.user):
196             answer.delete()
197             return HttpResponse(status=200)
198 
199     return HttpResponse(_(u"Du har ikke tilgang til å slette dette svaret", status=401))
200 
201 
202 def _get_fbr_or_404(app_label, app_model, object_id, feedback_id):
203     """
204     Get FeedbackRelation or raise Http404
205     """
206     try:
207         ct = ContentType.objects.get(app_label=app_label, model=app_model)
208         fbr = FeedbackRelation.objects.get(
209             content_type=ct,
210             object_id=object_id,
211             feedback_id=feedback_id
212         )
213     except ObjectDoesNotExist:
214         raise Http404
215 
216     return fbr
217
```

Path: `apps/feedback/forms.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 from django import forms
3 from apps.feedback.models import RatingAnswer
4 from apps.feedback.models import MultipleChoiceAnswer
5 from apps.feedback.models import Choice
6 from apps.feedback.models import RATING_CHOICES
7 from apps.feedback.models import FieldOfStudyAnswer
8 from apps.feedback.models import TextAnswer
9 from crispy_forms.helper import FormHelper
10 
11 
12 class AnswerForm(forms.ModelForm):
13     """
14     A superclass for answer forms.
15     """
16     def __init__(self, *args, **kwargs):
17         self.helper = FormHelper()
18         self.helper.form_tag = False
19         self.helper.html5_required = False
20         super(AnswerForm, self).__init__(*args, **kwargs)
21         self.fields['answer'].label = self.instance.question.label
22 
23 
24 class RatingAnswerForm(AnswerForm):
25     answer = forms.ChoiceField(widget=forms.Select(attrs={"class": "rating", "name": "rating"}),
26                                choices=RATING_CHOICES)
27 
28     class Meta(object):
29         model = RatingAnswer
30         exclude = ("feedback_relation", "question",)
31 
32 
33 class FieldOfStudyAnswerForm(AnswerForm):
34 
35     def clean_answer(self):
36         data = self.cleaned_data['answer']
37         return data
38 
39     class Meta(object):
40         model = FieldOfStudyAnswer
41         exclude = ("feedback_relation", "question",)
42 
43 
44 class TextAnswerForm(AnswerForm):
45     answer = forms.CharField(
46         widget=forms.Textarea(attrs={'class': 'form-control', 'type': 'text', "rows": "3"}))
47 
48     class Meta(object):
49         model = TextAnswer
50         exclude = ("feedback_relation", "question",)
51 
52 
53 class MultipleChoiceForm(forms.ModelForm):
54     def __init__(self, *args, **kwargs):
55         self.helper = FormHelper()
56         self.helper.form_tag = False
57         self.helper.html5_required = False
58         super(MultipleChoiceForm, self).__init__(*args, **kwargs)
59 
60         self.fields['answer'] = forms.ModelChoiceField(
61             queryset=Choice.objects.filter(question=self.instance.question.multiple_choice_relation),
62             widget=forms.Select(attrs={'class': 'form-control'}))
63         self.fields['answer'].label = self.instance.question.multiple_choice_relation.label
64 
65     class Meta(object):
66         model = MultipleChoiceAnswer
67         exclude = ("feedback_relation", "question", "choice")
68 
69 
70 def create_answer_forms(fbr, post_data=None):
71     """
72     Prefix magic to identify forms from post_data.
73     """
74     answers = []
75     for i, question in enumerate(fbr.questions):
76         answers.append(answer_form_factory(question, fbr, str(i), post_data))
77     return answers
78 
79 
80 def answer_form_factory(question, feedback_relation, prefix, post_data=None):
81     data = {"question": question, "feedback_relation": feedback_relation}
82     instance = question.answer.model(**data)
83     if question.answer.model == FieldOfStudyAnswer:
84         return FieldOfStudyAnswerForm(post_data, instance=instance,
85                                       prefix=prefix)
86 
87     elif question.answer.model == RatingAnswer:
88         return RatingAnswerForm(post_data, instance=instance, prefix=prefix)
89 
90     elif question.answer.model == TextAnswer:
91         return TextAnswerForm(post_data, instance=instance, prefix=prefix)
92 
93     elif question.answer.model == MultipleChoiceAnswer:
94         return MultipleChoiceForm(post_data, instance=instance, prefix=prefix)
95
```
--- 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/feedback/forms.py b/apps/feedback/forms.py
--- a/apps/feedback/forms.py
+++ b/apps/feedback/forms.py
@@ -19,11 +19,14 @@
         self.helper.html5_required = False
         super(AnswerForm, self).__init__(*args, **kwargs)
         self.fields['answer'].label = self.instance.question.label
+        self.display = self.instance.question.display
 
 
 class RatingAnswerForm(AnswerForm):
-    answer = forms.ChoiceField(widget=forms.Select(attrs={"class": "rating", "name": "rating"}),
-                               choices=RATING_CHOICES)
+    answer = forms.ChoiceField(
+        widget=forms.Select(attrs={"class": "rating", "name": "rating"}),
+        choices=RATING_CHOICES
+    )
 
     class Meta(object):
         model = RatingAnswer
@@ -43,7 +46,7 @@
 
 class TextAnswerForm(AnswerForm):
     answer = forms.CharField(
-        widget=forms.Textarea(attrs={'class': 'form-control', 'type': 'text', "rows": "3"}))
+        widget=forms.Textarea(attrs={'class': 'form-control', 'type': 'text'}))
 
     class Meta(object):
         model = TextAnswer
@@ -67,7 +70,7 @@
         exclude = ("feedback_relation", "question", "choice")
 
 
-def create_answer_forms(fbr, post_data=None):
+def create_forms(fbr, post_data=None):
     """
     Prefix magic to identify forms from post_data.
     """
@@ -81,8 +84,7 @@
     data = {"question": question, "feedback_relation": feedback_relation}
     instance = question.answer.model(**data)
     if question.answer.model == FieldOfStudyAnswer:
-        return FieldOfStudyAnswerForm(post_data, instance=instance,
-                                      prefix=prefix)
+        return FieldOfStudyAnswerForm(post_data, instance=instance, prefix=prefix)
 
     elif question.answer.model == RatingAnswer:
         return RatingAnswerForm(post_data, instance=instance, prefix=prefix)
diff --git a/apps/feedback/views.py b/apps/feedback/views.py
--- a/apps/feedback/views.py
+++ b/apps/feedback/views.py
@@ -19,7 +19,7 @@
     TextAnswer,
     RegisterToken
 )
-from apps.feedback.forms import create_answer_forms
+from apps.feedback.forms import create_forms
 from apps.feedback.utils import has_permission, can_delete, get_group_restricted_feedback_relations
 
 
@@ -32,10 +32,10 @@
         return redirect("home")
 
     if request.method == "POST":
-        answers = create_answer_forms(feedback_relation, post_data=request.POST)
-        if all([a.is_valid() for a in answers]):
-            for a in answers:
-                a.save()
+        questions = create_forms(feedback_relation, post_data=request.POST)
+        if all([answer.is_valid() for answer in questions]):
+            for answer in questions:
+                answer.save()
 
             # mark that the user has answered
             feedback_relation.answered.add(request.user)
@@ -50,14 +50,14 @@
         else:
             messages.error(request, _(u"Du må svare på alle påkrevde felt."))
     else:
-        answers = create_answer_forms(feedback_relation)
+        questions = create_forms(feedback_relation)
 
     description = feedback_relation.description
 
     return render(
         request,
         'feedback/answer.html',
-        {'answers': answers, 'description': description}
+        {'questions': questions, 'description': description}
     )

{"golden_diff": "diff --git a/apps/feedback/forms.py b/apps/feedback/forms.py\n--- a/apps/feedback/forms.py\n+++ b/apps/feedback/forms.py\n@@ -19,11 +19,14 @@\n         self.helper.html5_required = False\n         super(AnswerForm, self).__init__(*args, **kwargs)\n         self.fields['answer'].label = self.instance.question.label\n+        self.display = self.instance.question.display\n \n \n class RatingAnswerForm(AnswerForm):\n-    answer = forms.ChoiceField(widget=forms.Select(attrs={\"class\": \"rating\", \"name\": \"rating\"}),\n-                               choices=RATING_CHOICES)\n+    answer = forms.ChoiceField(\n+        widget=forms.Select(attrs={\"class\": \"rating\", \"name\": \"rating\"}),\n+        choices=RATING_CHOICES\n+    )\n \n     class Meta(object):\n         model = RatingAnswer\n@@ -43,7 +46,7 @@\n \n class TextAnswerForm(AnswerForm):\n     answer = forms.CharField(\n-        widget=forms.Textarea(attrs={'class': 'form-control', 'type': 'text', \"rows\": \"3\"}))\n+        widget=forms.Textarea(attrs={'class': 'form-control', 'type': 'text'}))\n \n     class Meta(object):\n         model = TextAnswer\n@@ -67,7 +70,7 @@\n         exclude = (\"feedback_relation\", \"question\", \"choice\")\n \n \n-def create_answer_forms(fbr, post_data=None):\n+def create_forms(fbr, post_data=None):\n     \"\"\"\n     Prefix magic to identify forms from post_data.\n     \"\"\"\n@@ -81,8 +84,7 @@\n     data = {\"question\": question, \"feedback_relation\": feedback_relation}\n     instance = question.answer.model(**data)\n     if question.answer.model == FieldOfStudyAnswer:\n-        return FieldOfStudyAnswerForm(post_data, instance=instance,\n-                                      prefix=prefix)\n+        return FieldOfStudyAnswerForm(post_data, instance=instance, prefix=prefix)\n \n     elif question.answer.model == RatingAnswer:\n         return RatingAnswerForm(post_data, instance=instance, prefix=prefix)\ndiff --git a/apps/feedback/views.py b/apps/feedback/views.py\n--- a/apps/feedback/views.py\n+++ b/apps/feedback/views.py\n@@ -19,7 +19,7 @@\n     TextAnswer,\n     RegisterToken\n )\n-from apps.feedback.forms import create_answer_forms\n+from apps.feedback.forms import create_forms\n from apps.feedback.utils import has_permission, can_delete, get_group_restricted_feedback_relations\n \n \n@@ -32,10 +32,10 @@\n         return redirect(\"home\")\n \n     if request.method == \"POST\":\n-        answers = create_answer_forms(feedback_relation, post_data=request.POST)\n-        if all([a.is_valid() for a in answers]):\n-            for a in answers:\n-                a.save()\n+        questions = create_forms(feedback_relation, post_data=request.POST)\n+        if all([answer.is_valid() for answer in questions]):\n+            for answer in questions:\n+                answer.save()\n \n             # mark that the user has answered\n             feedback_relation.answered.add(request.user)\n@@ -50,14 +50,14 @@\n         else:\n             messages.error(request, _(u\"Du m\u00e5 svare p\u00e5 alle p\u00e5krevde felt.\"))\n     else:\n-        answers = create_answer_forms(feedback_relation)\n+        questions = create_forms(feedback_relation)\n \n     description = feedback_relation.description\n \n     return render(\n         request,\n         'feedback/answer.html',\n-        {'answers': answers, 'description': description}\n+        {'questions': questions, 'description': description}\n     )\n", "issue": "[Feedback] - Display to the users what questions the company will see.\nIllustrate in someway the questions that will be visible to the company.\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\nimport json\n\nfrom collections import namedtuple, defaultdict\n\nfrom django.http import Http404, HttpResponse\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom apps.feedback.models import (\n    FeedbackRelation,\n    FieldOfStudyAnswer,\n    RATING_CHOICES,\n    TextQuestion,\n    TextAnswer,\n    RegisterToken\n)\nfrom apps.feedback.forms import create_answer_forms\nfrom apps.feedback.utils import has_permission, can_delete, get_group_restricted_feedback_relations\n\n\n@login_required\ndef feedback(request, applabel, appmodel, object_id, feedback_id):\n    feedback_relation = _get_fbr_or_404(applabel, appmodel, object_id, feedback_id)\n\n    if not feedback_relation.can_answer(request.user):\n        messages.error(request, feedback_relation.answer_error_message(request.user))\n        return redirect(\"home\")\n\n    if request.method == \"POST\":\n        answers = create_answer_forms(feedback_relation, post_data=request.POST)\n        if all([a.is_valid() for a in answers]):\n            for a in answers:\n                a.save()\n\n            # mark that the user has answered\n            feedback_relation.answered.add(request.user)\n            feedback_relation.save()\n\n            # Set field of study automaticly\n            fosa = FieldOfStudyAnswer(feedback_relation=feedback_relation, answer=request.user.field_of_study)\n            fosa.save()\n\n            messages.success(request, _(u\"Takk for at du svarte.\"))\n            return redirect(\"home\")\n        else:\n            messages.error(request, _(u\"Du m\u00e5 svare p\u00e5 alle p\u00e5krevde felt.\"))\n    else:\n        answers = create_answer_forms(feedback_relation)\n\n    description = feedback_relation.description\n\n    return render(\n        request,\n        'feedback/answer.html',\n        {'answers': answers, 'description': description}\n    )\n\n\n@login_required\ndef result(request, applabel, appmodel, object_id, feedback_id):\n    feedback_relation = _get_fbr_or_404(applabel, appmodel, object_id, feedback_id)\n\n    if not has_permission(feedback_relation, request.user):\n        messages.error(request, _(u\"Du har ikke tilgang til dette skjemaet.\"))\n        return redirect(\"home\")\n\n    return feedback_results(request, feedback_relation)\n\n\ndef results_token(request, applabel, appmodel, object_id, feedback_id,  token):\n    feedback_relation = _get_fbr_or_404(applabel, appmodel, object_id, feedback_id)\n    register_token = get_object_or_404(RegisterToken, token=token)\n\n    if register_token.is_valid(feedback_relation):\n        return feedback_results(request, feedback_relation, True)\n    else:\n        return HttpResponse('Unauthorized', status=401)\n\n\ndef feedback_results(request, feedback_relation, token=False):\n    qa = namedtuple(\"Qa\", \"question, answers\")\n    question_and_answers = []\n\n    for question in feedback_relation.questions:\n        if (question.display or not token) and isinstance(question, TextQuestion):\n            question_and_answers.append(qa(question, feedback_relation.answers_to_question(question)))\n\n    info = None\n\n    if feedback_relation.feedback.display_info or not token:\n        info = feedback_relation.content_info()\n        info[_(u'Besvarelser')] = feedback_relation.answered.count()\n\n    register_token = get_object_or_404(RegisterToken, fbr=feedback_relation)\n\n    token_url = u\"%s%sresults/%s\" % (\n        request.META['HTTP_HOST'],\n        feedback_relation.get_absolute_url(),\n        register_token.token\n    )\n\n    return render(\n        request,\n        'feedback/results.html',\n        {\n            'question_and_answers': question_and_answers,\n            'description': feedback_relation.description,\n            'token_url': token_url,\n            'token': token,\n            'info': info\n        }\n    )\n\n\n@login_required\ndef chart_data(request, applabel, appmodel, object_id, feedback_id):\n    feedback_relation = _get_fbr_or_404(applabel, appmodel, object_id, feedback_id)\n\n    if not has_permission(feedback_relation, request.user):\n        messages.error(request, _(u\"Du har ikke tilgang til denne dataen.\"))\n        return redirect(\"home\")\n\n    return get_chart_data(request, feedback_relation)\n\n\ndef chart_data_token(request, applabel, appmodel, object_id, feedback_id, token):\n    feedback_relation = _get_fbr_or_404(applabel, appmodel, object_id, feedback_id)\n    register_token = get_object_or_404(RegisterToken, token=token)\n\n    if register_token.is_valid(feedback_relation):\n        return get_chart_data(request, feedback_relation, True)\n    else:\n        return HttpResponse('Unauthorized', status=401)\n\n\ndef get_chart_data(request, feedback_relation, token=False):\n    rating_answers = []\n    rating_titles = []\n    answer_collection = dict()\n    answer_collection['replies'] = dict()\n    answer_length = int(len(RATING_CHOICES))\n    for question in feedback_relation.ratingquestion:\n        if question.display or not token:\n            rating_titles.append(str(question))\n            answers = feedback_relation.answers_to_question(question)\n            answer_count = [0] * answer_length\n            for answer in answers:\n                answer_count[int(answer.answer)] += 1\n            rating_answers.append(answer_count[1:])\n\n    fos_answer_count = defaultdict(int)\n\n    if feedback_relation.feedback.display_field_of_study or not token:\n        fos = feedback_relation.field_of_study_answers.all()\n        for answer in fos:\n            fos_answer_count[str(answer)] += 1\n\n    mc_questions = []\n    mc_answer_count = []\n\n    for question in feedback_relation.multiple_choice_question:\n        if question.display or not token:\n            mc_questions.append(unicode(question))\n            answer_count = defaultdict(int)\n            for answer in feedback_relation.answers_to_question(question):\n                answer_count[str(answer)] += 1\n            mc_answer_count.append(answer_count.items())\n\n    answer_collection['replies']['ratings'] = rating_answers\n    answer_collection['replies']['titles'] = rating_titles\n    answer_collection['replies']['mc_questions'] = mc_questions\n    answer_collection['replies']['mc_answers'] = mc_answer_count\n    answer_collection['replies']['fos'] = fos_answer_count.items()\n\n    return HttpResponse(json.dumps(answer_collection), content_type='application/json')\n\n\n@login_required\ndef index(request):\n    feedback_relations = get_group_restricted_feedback_relations(request.user)\n    return render(request, 'feedback/index.html', {'feedbacks': feedback_relations})\n\n\n@login_required\ndef delete_answer(request):\n    if request.method == 'POST':\n        answer_id = request.POST.get('answer_id')\n        answer = get_object_or_404(TextAnswer, pk=answer_id)\n\n        if can_delete(answer, request.user):\n            answer.delete()\n            return HttpResponse(status=200)\n\n    return HttpResponse(_(u\"Du har ikke tilgang til \u00e5 slette dette svaret\", status=401))\n\n\ndef _get_fbr_or_404(app_label, app_model, object_id, feedback_id):\n    \"\"\"\n    Get FeedbackRelation or raise Http404\n    \"\"\"\n    try:\n        ct = ContentType.objects.get(app_label=app_label, model=app_model)\n        fbr = FeedbackRelation.objects.get(\n            content_type=ct,\n            object_id=object_id,\n            feedback_id=feedback_id\n        )\n    except ObjectDoesNotExist:\n        raise Http404\n\n    return fbr\n", "path": "apps/feedback/views.py"}, {"content": "# -*- coding: utf-8 -*-\nfrom django import forms\nfrom apps.feedback.models import RatingAnswer\nfrom apps.feedback.models import MultipleChoiceAnswer\nfrom apps.feedback.models import Choice\nfrom apps.feedback.models import RATING_CHOICES\nfrom apps.feedback.models import FieldOfStudyAnswer\nfrom apps.feedback.models import TextAnswer\nfrom crispy_forms.helper import FormHelper\n\n\nclass AnswerForm(forms.ModelForm):\n    \"\"\"\n    A superclass for answer forms.\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        self.helper = FormHelper()\n        self.helper.form_tag = False\n        self.helper.html5_required = False\n        super(AnswerForm, self).__init__(*args, **kwargs)\n        self.fields['answer'].label = self.instance.question.label\n\n\nclass RatingAnswerForm(AnswerForm):\n    answer = forms.ChoiceField(widget=forms.Select(attrs={\"class\": \"rating\", \"name\": \"rating\"}),\n                               choices=RATING_CHOICES)\n\n    class Meta(object):\n        model = RatingAnswer\n        exclude = (\"feedback_relation\", \"question\",)\n\n\nclass FieldOfStudyAnswerForm(AnswerForm):\n\n    def clean_answer(self):\n        data = self.cleaned_data['answer']\n        return data\n\n    class Meta(object):\n        model = FieldOfStudyAnswer\n        exclude = (\"feedback_relation\", \"question\",)\n\n\nclass TextAnswerForm(AnswerForm):\n    answer = forms.CharField(\n        widget=forms.Textarea(attrs={'class': 'form-control', 'type': 'text', \"rows\": \"3\"}))\n\n    class Meta(object):\n        model = TextAnswer\n        exclude = (\"feedback_relation\", \"question\",)\n\n\nclass MultipleChoiceForm(forms.ModelForm):\n    def __init__(self, *args, **kwargs):\n        self.helper = FormHelper()\n        self.helper.form_tag = False\n        self.helper.html5_required = False\n        super(MultipleChoiceForm, self).__init__(*args, **kwargs)\n\n        self.fields['answer'] = forms.ModelChoiceField(\n            queryset=Choice.objects.filter(question=self.instance.question.multiple_choice_relation),\n            widget=forms.Select(attrs={'class': 'form-control'}))\n        self.fields['answer'].label = self.instance.question.multiple_choice_relation.label\n\n    class Meta(object):\n        model = MultipleChoiceAnswer\n        exclude = (\"feedback_relation\", \"question\", \"choice\")\n\n\ndef create_answer_forms(fbr, post_data=None):\n    \"\"\"\n    Prefix magic to identify forms from post_data.\n    \"\"\"\n    answers = []\n    for i, question in enumerate(fbr.questions):\n        answers.append(answer_form_factory(question, fbr, str(i), post_data))\n    return answers\n\n\ndef answer_form_factory(question, feedback_relation, prefix, post_data=None):\n    data = {\"question\": question, \"feedback_relation\": feedback_relation}\n    instance = question.answer.model(**data)\n    if question.answer.model == FieldOfStudyAnswer:\n        return FieldOfStudyAnswerForm(post_data, instance=instance,\n                                      prefix=prefix)\n\n    elif question.answer.model == RatingAnswer:\n        return RatingAnswerForm(post_data, instance=instance, prefix=prefix)\n\n    elif question.answer.model == TextAnswer:\n        return TextAnswerForm(post_data, instance=instance, prefix=prefix)\n\n    elif question.answer.model == MultipleChoiceAnswer:\n        return MultipleChoiceForm(post_data, instance=instance, prefix=prefix)\n", "path": "apps/feedback/forms.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\nimport json\n\nfrom collections import namedtuple, defaultdict\n\nfrom django.http import Http404, HttpResponse\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom apps.feedback.models import (\n    FeedbackRelation,\n    FieldOfStudyAnswer,\n    RATING_CHOICES,\n    TextQuestion,\n    TextAnswer,\n    RegisterToken\n)\nfrom apps.feedback.forms import create_forms\nfrom apps.feedback.utils import has_permission, can_delete, get_group_restricted_feedback_relations\n\n\n@login_required\ndef feedback(request, applabel, appmodel, object_id, feedback_id):\n    feedback_relation = _get_fbr_or_404(applabel, appmodel, object_id, feedback_id)\n\n    if not feedback_relation.can_answer(request.user):\n        messages.error(request, feedback_relation.answer_error_message(request.user))\n        return redirect(\"home\")\n\n    if request.method == \"POST\":\n        questions = create_forms(feedback_relation, post_data=request.POST)\n        if all([answer.is_valid() for answer in questions]):\n            for answer in questions:\n                answer.save()\n\n            # mark that the user has answered\n            feedback_relation.answered.add(request.user)\n            feedback_relation.save()\n\n            # Set field of study automaticly\n            fosa = FieldOfStudyAnswer(feedback_relation=feedback_relation, answer=request.user.field_of_study)\n            fosa.save()\n\n            messages.success(request, _(u\"Takk for at du svarte.\"))\n            return redirect(\"home\")\n        else:\n            messages.error(request, _(u\"Du m\u00e5 svare p\u00e5 alle p\u00e5krevde felt.\"))\n    else:\n        questions = create_forms(feedback_relation)\n\n    description = feedback_relation.description\n\n    return render(\n        request,\n        'feedback/answer.html',\n        {'questions': questions, 'description': description}\n    )\n\n\n@login_required\ndef result(request, applabel, appmodel, object_id, feedback_id):\n    feedback_relation = _get_fbr_or_404(applabel, appmodel, object_id, feedback_id)\n\n    if not has_permission(feedback_relation, request.user):\n        messages.error(request, _(u\"Du har ikke tilgang til dette skjemaet.\"))\n        return redirect(\"home\")\n\n    return feedback_results(request, feedback_relation)\n\n\ndef results_token(request, applabel, appmodel, object_id, feedback_id,  token):\n    feedback_relation = _get_fbr_or_404(applabel, appmodel, object_id, feedback_id)\n    register_token = get_object_or_404(RegisterToken, token=token)\n\n    if register_token.is_valid(feedback_relation):\n        return feedback_results(request, feedback_relation, True)\n    else:\n        return HttpResponse('Unauthorized', status=401)\n\n\ndef feedback_results(request, feedback_relation, token=False):\n    qa = namedtuple(\"Qa\", \"question, answers\")\n    question_and_answers = []\n\n    for question in feedback_relation.questions:\n        if (question.display or not token) and isinstance(question, TextQuestion):\n            question_and_answers.append(qa(question, feedback_relation.answers_to_question(question)))\n\n    info = None\n\n    if feedback_relation.feedback.display_info or not token:\n        info = feedback_relation.content_info()\n        info[_(u'Besvarelser')] = feedback_relation.answered.count()\n\n    register_token = get_object_or_404(RegisterToken, fbr=feedback_relation)\n\n    token_url = u\"%s%sresults/%s\" % (\n        request.META['HTTP_HOST'],\n        feedback_relation.get_absolute_url(),\n        register_token.token\n    )\n\n    return render(\n        request,\n        'feedback/results.html',\n        {\n            'question_and_answers': question_and_answers,\n            'description': feedback_relation.description,\n            'token_url': token_url,\n            'token': token,\n            'info': info\n        }\n    )\n\n\n@login_required\ndef chart_data(request, applabel, appmodel, object_id, feedback_id):\n    feedback_relation = _get_fbr_or_404(applabel, appmodel, object_id, feedback_id)\n\n    if not has_permission(feedback_relation, request.user):\n        messages.error(request, _(u\"Du har ikke tilgang til denne dataen.\"))\n        return redirect(\"home\")\n\n    return get_chart_data(request, feedback_relation)\n\n\ndef chart_data_token(request, applabel, appmodel, object_id, feedback_id, token):\n    feedback_relation = _get_fbr_or_404(applabel, appmodel, object_id, feedback_id)\n    register_token = get_object_or_404(RegisterToken, token=token)\n\n    if register_token.is_valid(feedback_relation):\n        return get_chart_data(request, feedback_relation, True)\n    else:\n        return HttpResponse('Unauthorized', status=401)\n\n\ndef get_chart_data(request, feedback_relation, token=False):\n    rating_answers = []\n    rating_titles = []\n    answer_collection = dict()\n    answer_collection['replies'] = dict()\n    answer_length = int(len(RATING_CHOICES))\n    for question in feedback_relation.ratingquestion:\n        if question.display or not token:\n            rating_titles.append(str(question))\n            answers = feedback_relation.answers_to_question(question)\n            answer_count = [0] * answer_length\n            for answer in answers:\n                answer_count[int(answer.answer)] += 1\n            rating_answers.append(answer_count[1:])\n\n    fos_answer_count = defaultdict(int)\n\n    if feedback_relation.feedback.display_field_of_study or not token:\n        fos = feedback_relation.field_of_study_answers.all()\n        for answer in fos:\n            fos_answer_count[str(answer)] += 1\n\n    mc_questions = []\n    mc_answer_count = []\n\n    for question in feedback_relation.multiple_choice_question:\n        if question.display or not token:\n            mc_questions.append(unicode(question))\n            answer_count = defaultdict(int)\n            for answer in feedback_relation.answers_to_question(question):\n                answer_count[str(answer)] += 1\n            mc_answer_count.append(answer_count.items())\n\n    answer_collection['replies']['ratings'] = rating_answers\n    answer_collection['replies']['titles'] = rating_titles\n    answer_collection['replies']['mc_questions'] = mc_questions\n    answer_collection['replies']['mc_answers'] = mc_answer_count\n    answer_collection['replies']['fos'] = fos_answer_count.items()\n\n    return HttpResponse(json.dumps(answer_collection), content_type='application/json')\n\n\n@login_required\ndef index(request):\n    feedback_relations = get_group_restricted_feedback_relations(request.user)\n    return render(request, 'feedback/index.html', {'feedbacks': feedback_relations})\n\n\n@login_required\ndef delete_answer(request):\n    if request.method == 'POST':\n        answer_id = request.POST.get('answer_id')\n        answer = get_object_or_404(TextAnswer, pk=answer_id)\n\n        if can_delete(answer, request.user):\n            answer.delete()\n            return HttpResponse(status=200)\n\n    return HttpResponse(_(u\"Du har ikke tilgang til \u00e5 slette dette svaret\", status=401))\n\n\ndef _get_fbr_or_404(app_label, app_model, object_id, feedback_id):\n    \"\"\"\n    Get FeedbackRelation or raise Http404\n    \"\"\"\n    try:\n        ct = ContentType.objects.get(app_label=app_label, model=app_model)\n        fbr = FeedbackRelation.objects.get(\n            content_type=ct,\n            object_id=object_id,\n            feedback_id=feedback_id\n        )\n    except ObjectDoesNotExist:\n        raise Http404\n\n    return fbr\n", "path": "apps/feedback/views.py"}, {"content": "# -*- coding: utf-8 -*-\nfrom django import forms\nfrom apps.feedback.models import RatingAnswer\nfrom apps.feedback.models import MultipleChoiceAnswer\nfrom apps.feedback.models import Choice\nfrom apps.feedback.models import RATING_CHOICES\nfrom apps.feedback.models import FieldOfStudyAnswer\nfrom apps.feedback.models import TextAnswer\nfrom crispy_forms.helper import FormHelper\n\n\nclass AnswerForm(forms.ModelForm):\n    \"\"\"\n    A superclass for answer forms.\n    \"\"\"\n    def __init__(self, *args, **kwargs):\n        self.helper = FormHelper()\n        self.helper.form_tag = False\n        self.helper.html5_required = False\n        super(AnswerForm, self).__init__(*args, **kwargs)\n        self.fields['answer'].label = self.instance.question.label\n        self.display = self.instance.question.display\n\n\nclass RatingAnswerForm(AnswerForm):\n    answer = forms.ChoiceField(\n        widget=forms.Select(attrs={\"class\": \"rating\", \"name\": \"rating\"}),\n        choices=RATING_CHOICES\n    )\n\n    class Meta(object):\n        model = RatingAnswer\n        exclude = (\"feedback_relation\", \"question\",)\n\n\nclass FieldOfStudyAnswerForm(AnswerForm):\n\n    def clean_answer(self):\n        data = self.cleaned_data['answer']\n        return data\n\n    class Meta(object):\n        model = FieldOfStudyAnswer\n        exclude = (\"feedback_relation\", \"question\",)\n\n\nclass TextAnswerForm(AnswerForm):\n    answer = forms.CharField(\n        widget=forms.Textarea(attrs={'class': 'form-control', 'type': 'text'}))\n\n    class Meta(object):\n        model = TextAnswer\n        exclude = (\"feedback_relation\", \"question\",)\n\n\nclass MultipleChoiceForm(forms.ModelForm):\n    def __init__(self, *args, **kwargs):\n        self.helper = FormHelper()\n        self.helper.form_tag = False\n        self.helper.html5_required = False\n        super(MultipleChoiceForm, self).__init__(*args, **kwargs)\n\n        self.fields['answer'] = forms.ModelChoiceField(\n            queryset=Choice.objects.filter(question=self.instance.question.multiple_choice_relation),\n            widget=forms.Select(attrs={'class': 'form-control'}))\n        self.fields['answer'].label = self.instance.question.multiple_choice_relation.label\n\n    class Meta(object):\n        model = MultipleChoiceAnswer\n        exclude = (\"feedback_relation\", \"question\", \"choice\")\n\n\ndef create_forms(fbr, post_data=None):\n    \"\"\"\n    Prefix magic to identify forms from post_data.\n    \"\"\"\n    answers = []\n    for i, question in enumerate(fbr.questions):\n        answers.append(answer_form_factory(question, fbr, str(i), post_data))\n    return answers\n\n\ndef answer_form_factory(question, feedback_relation, prefix, post_data=None):\n    data = {\"question\": question, \"feedback_relation\": feedback_relation}\n    instance = question.answer.model(**data)\n    if question.answer.model == FieldOfStudyAnswer:\n        return FieldOfStudyAnswerForm(post_data, instance=instance, prefix=prefix)\n\n    elif question.answer.model == RatingAnswer:\n        return RatingAnswerForm(post_data, instance=instance, prefix=prefix)\n\n    elif question.answer.model == TextAnswer:\n        return TextAnswerForm(post_data, instance=instance, prefix=prefix)\n\n    elif question.answer.model == MultipleChoiceAnswer:\n        return MultipleChoiceForm(post_data, instance=instance, prefix=prefix)\n", "path": "apps/feedback/forms.py"}]}