# Path: festi/survey/forms.py
# class SurveyForm(forms.ModelForm):
#     class Meta:
#         model = Survey
#         fields = ('props',)
#         widgets = {
#             'props': SplitJSONWidget,
#         }
# 
#     def clean_props(self):
#         props = self.cleaned_data['props']
#         for prop in props:
#             if not prop.get('answer', '').strip():
#                 raise forms.ValidationError(u'모든 답변을 채워주세요.')
#         return props
# 
# Path: festi/survey/models.py
# class Event(Base):
#     slug = models.SlugField(unique=True)
#     name = models.CharField(max_length=100, db_index=True)
#     props = JSONField(verbose_name='Questions', blank=True)
#     begin = models.DateTimeField()
#     end = models.DateTimeField()
#     is_public = models.BooleanField(default=False, db_index=True)
#     is_closed = models.BooleanField(default=True, db_index=True)
#     approve_email_content = models.TextField(blank=True, null=True, help_text=u'첫 줄은 제목')
# 
#     def __unicode__(self):
#         return self.name
# 
#     def as_dict(self):
#         return {
#             'id': self.id,
#             'name': self.name,
#             'props': self.props,
#             'begin': self.begin,
#             'end': self.end,
#         }
# 
#     def export_csv(self, f):
#         header = ['email', 'name', 'gender', 'is_approved', 'is_notified', 'is_attended']
# 
# 
#         f.write(BOM_UTF8)
#         writer = csv.writer(f)
#         writer.writerow([(col or '').encode('utf8') for col in header])
# 
#         for survey in self.survey_set.select_related('user').all():
#             try:
#                 social = survey.user.socialaccount_set.first()
#                 name = social.extra_data['name']
#                 gender = social.extra_data['gender']
#             except (AttributeError, KeyError):
#                 name = ''
#                 gender = ''
# 
#             row = [survey.user.email, name, gender, survey.is_approved, survey.is_notified, survey.is_attended]
#             row.extend([prop['answer'] for prop in survey.props])
#             writer.writerow([(col or '').encode('utf8') for col in row])
# 
#         return f
# 
# class Speaker(models.Model):
#     event = models.ForeignKey(Event)
#     idx = models.IntegerField(default=0)
#     name = models.CharField(max_length=100)
#     profile = models.CharField(max_length=100, blank=True)
#     profile_image = models.ImageField(upload_to=random_name)
#     keyword = models.CharField(max_length=20, blank=True)
#     topic = models.CharField(max_length=100, blank=True)
#     detail = models.TextField(blank=True)
# 
#     class Meta:
#         ordering = ('idx', 'id')
# 
# class Survey(Base):
#     event = models.ForeignKey(Event)
#     user = models.ForeignKey(settings.AUTH_USER_MODEL)
#     props = JSONField()
#     is_approved = models.BooleanField(default=False, db_index=True, verbose_name=u'승인여부')
#     is_notified = models.BooleanField(default=False, db_index=True, verbose_name=u'알림여부')
#     is_attended = models.BooleanField(default=False, db_index=True, verbose_name=u'참석여부')
# 
#     class Meta:
#         unique_together = (('event', 'user'),)
# 
#     def as_dict(self):
#         return {
#             'props': self.props,
#             'is_approved': self.is_approved,
#             'is_notified': self.is_notified,
#             'is_attended': self.is_attended,
#         }


from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from .forms import SurveyForm
from .models import Event, Speaker, Survey
        else:
            for error in form.errors['props']:
                messages.error(request, error)
    else:
        props = []
        if survey:
            props = survey.props

        for event_prop in (event.props or []):
            for prop in props:
                if int(prop['id']) == int(event_prop['id']):
                    if event_prop.get('answer_type', None):
                        prop['answer_type'] = event_prop['answer_type']
                    break
            else:
                prop = {
                    'id': event_prop['id'],
                    'question': event_prop['question'],
                    'answer': '',
                }
                if event_prop.get('answer_type', None):
                    prop['answer_type'] = event_prop['answer_type']
                props.append(prop)

        if not props:
            messages.info(request, u'참가신청 입력폼을 준비 중입니다.')
            return redirect('conference:index')

        props = sorted(props, key=lambda _p: int(_p['id']))


# Path: festi/survey/forms.py
# class SurveyForm(forms.ModelForm):
#     class Meta:
#         model = Survey
#         fields = ('props',)
#         widgets = {
#             'props': SplitJSONWidget,
#         }
# 
#     def clean_props(self):
#         props = self.cleaned_data['props']
#         for prop in props:
#             if not prop.get('answer', '').strip():
#                 raise forms.ValidationError(u'모든 답변을 채워주세요.')
#         return props
# 
# Path: festi/survey/models.py
# class Event(Base):
#     slug = models.SlugField(unique=True)
#     name = models.CharField(max_length=100, db_index=True)
#     props = JSONField(verbose_name='Questions', blank=True)
#     begin = models.DateTimeField()
#     end = models.DateTimeField()
#     is_public = models.BooleanField(default=False, db_index=True)
#     is_closed = models.BooleanField(default=True, db_index=True)
#     approve_email_content = models.TextField(blank=True, null=True, help_text=u'첫 줄은 제목')
# 
#     def __unicode__(self):
#         return self.name
# 
#     def as_dict(self):
#         return {
#             'id': self.id,
#             'name': self.name,
#             'props': self.props,
#             'begin': self.begin,
#             'end': self.end,
#         }
# 
#     def export_csv(self, f):
#         header = ['email', 'name', 'gender', 'is_approved', 'is_notified', 'is_attended']
# 
# 
#         f.write(BOM_UTF8)
#         writer = csv.writer(f)
#         writer.writerow([(col or '').encode('utf8') for col in header])
# 
#         for survey in self.survey_set.select_related('user').all():
#             try:
#                 social = survey.user.socialaccount_set.first()
#                 name = social.extra_data['name']
#                 gender = social.extra_data['gender']
#             except (AttributeError, KeyError):
#                 name = ''
#                 gender = ''
# 
#             row = [survey.user.email, name, gender, survey.is_approved, survey.is_notified, survey.is_attended]
#             row.extend([prop['answer'] for prop in survey.props])
#             writer.writerow([(col or '').encode('utf8') for col in row])
# 
#         return f
# 
# class Speaker(models.Model):
#     event = models.ForeignKey(Event)
#     idx = models.IntegerField(default=0)
#     name = models.CharField(max_length=100)
#     profile = models.CharField(max_length=100, blank=True)
#     profile_image = models.ImageField(upload_to=random_name)
#     keyword = models.CharField(max_length=20, blank=True)
#     topic = models.CharField(max_length=100, blank=True)
#     detail = models.TextField(blank=True)
# 
#     class Meta:
#         ordering = ('idx', 'id')
# 
# class Survey(Base):
#     event = models.ForeignKey(Event)
#     user = models.ForeignKey(settings.AUTH_USER_MODEL)
#     props = JSONField()
#     is_approved = models.BooleanField(default=False, db_index=True, verbose_name=u'승인여부')
#     is_notified = models.BooleanField(default=False, db_index=True, verbose_name=u'알림여부')
#     is_attended = models.BooleanField(default=False, db_index=True, verbose_name=u'참석여부')
# 
#     class Meta:
#         unique_together = (('event', 'user'),)
# 
#     def as_dict(self):
#         return {
#             'props': self.props,
#             'is_approved': self.is_approved,
#             'is_notified': self.is_notified,
#             'is_attended': self.is_attended,
#         }


# Path: festi/survey/views.py
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from .forms import SurveyForm
from .models import Event, Speaker, Survey

        else:
            for error in form.errors['props']:
                messages.error(request, error)
    else:
        props = []
        if survey:
            props = survey.props

        for event_prop in (event.props or []):
            for prop in props:
                if int(prop['id']) == int(event_prop['id']):
                    if event_prop.get('answer_type', None):
                        prop['answer_type'] = event_prop['answer_type']
                    break
            else:
                prop = {
                    'id': event_prop['id'],
                    'question': event_prop['question'],
                    'answer': '',
                }
                if event_prop.get('answer_type', None):
                    prop['answer_type'] = event_prop['answer_type']
                props.append(prop)

        if not props:
            messages.info(request, u'참가신청 입력폼을 준비 중입니다.')
            return redirect('conference:index')

        props = sorted(props, key=lambda _p: int(_p['id']))


        form = SurveyForm(instance=survey, initial={'props': props})