class ToggleContactEnabledView(UpdateView):
    http_method_names = ['post', ]
    model = Contact
    fields = ['enabled']

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        self.queryset = Contact.objects.filter(writeitinstance__owner=self.request.user)
        return super(ToggleContactEnabledView, self).dispatch(*args, **kwargs)

    def get_object(self, queryset=None):
        id_ = self.request.POST['id']
        try:
            contact = self.queryset.get(id=id_)
            self.original_enabled = contact.enabled
        except Contact.DoesNotExist:
            raise Http404
        return contact

    def form_valid(self, form):
        self.object.enabled = not self.original_enabled
        self.object.save()
        data = json.dumps({
            'contact': {
                'id': self.object.id,
                'enabled': self.object.enabled
            }
            })
        return HttpResponse(data, content_type='application/json') class MailitTemplateUpdateView(UpdateView):
    model = MailItTemplate
    form_class = MailitTemplateForm

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(MailitTemplateUpdateView, self).dispatch(*args, **kwargs)

    def get_object(self):
        self.writeitinstance = get_object_or_404(WriteItInstance, slug=self.request.subdomain)
        if not self.writeitinstance.owner.__eq__(self.request.user):
            raise Http404
        self.object = self.writeitinstance.mailit_template
        return self.object

    def get_form_kwargs(self):
        kwargs = super(MailitTemplateUpdateView, self).get_form_kwargs()
        self.object = self.get_object()
        kwargs['writeitinstance'] = self.object.writeitinstance
        return kwargs

    def get_success_url(self):
        return reverse('writeitinstance_template_update', subdomain=self.writeitinstance.slug) class AnswerAttachment(models.Model):
    answer = models.ForeignKey(Answer, related_name="attachments")
    content = models.FileField(upload_to="attachments/%Y/%m/%d")
    name = models.CharField(max_length=512, default="") class AboutView(WriteItInstanceDetailView):
    template_name = 'about.html' class ConfirmView(RedirectView):
    permanent = False

    def get_redirect_url(self, *args, **kwargs):
        confirmation = get_object_or_404(Confirmation, key=kwargs['slug'])
        # Now proceed with the confirmation
        if confirmation.confirmated_at is None:
            confirmation.confirmated_at = datetime.now()
            confirmation.save()
            confirmation.message.recently_confirmated()
            self.request.session['user_came_via_confirmation_link'] = True
        return reverse('thread_read',
            subdomain=confirmation.message.writeitinstance.slug,
            kwargs={'slug': confirmation.message.slug}) class HelpView(TemplateView):
    def get_template_names(self):
        if 'section_name' in self.kwargs:
            return ["help/{}.html".format(self.kwargs['section_name'])]
        else:
            return ["help/index.html"] class MessageThreadView(MessageDetailView):
    model = Message
    template_name = 'thread/read.html'

    def get_context_data(self, **kwargs):
        context = super(MessageThreadView, self).get_context_data(**kwargs)
        if self.request.session.get('user_came_via_confirmation_link', False):
            context['user_came_via_confirmation_link'] = True
            del self.request.session['user_came_via_confirmation_link']

        context['writeitinstance'] = self.object.writeitinstance
        return context class MessageThreadsView(ListView):
    model = Message
    template_name = 'thread/all.html'

    def get_queryset(self):
        queryset = super(MessageThreadsView, self).get_queryset()
        return queryset.filter(writeitinstance__slug=self.request.subdomain,
            public=True, confirmated=True)

    def get_context_data(self, **kwargs):
        context = super(MessageThreadsView, self).get_context_data(**kwargs)
        context['writeitinstance'] = get_object_or_404(WriteItInstance, slug=self.request.subdomain)
        return context class MessagesFromPersonView(ListView):
    model = Message
    template_name = 'nuntium/message/from_person.html'

    def dispatch(self, *args, **kwargs):
        self.writeitinstance = get_object_or_404(WriteItInstance, slug=self.request.subdomain)
        self.message = get_object_or_404(Message, slug=self.kwargs['message_slug'])
        return super(MessagesFromPersonView, self).dispatch(*args, **kwargs)

    def get_queryset(self):
        qs = super(MessagesFromPersonView, self).get_queryset()
        qs = qs.filter(writeitinstance=self.writeitinstance).\
            filter(public=True).filter(confirmated=True).\
            filter(author_email=self.message.author_email)
        return qs

    def get_context_data(self, **kwargs):
        context = super(MessagesFromPersonView, self).get_context_data(**kwargs)
        context['author_name'] = self.message.author_name
        context['writeitinstance'] = self.writeitinstance
        return context class MessagesPerPersonView(ListView):
    model = Message
    template_name = "thread/to.html"

    def dispatch(self, request, *args, **kwargs):
        if 'pk' in self.kwargs:
            params = {'pk': self.kwargs['pk']}
        elif 'person_id' in self.kwargs:
            params = {'popit_id': self.kwargs['person_id']}
        self.person = get_object_or_404(Person, **params)
        self.writeitinstance = get_object_or_404(WriteItInstance, slug=request.subdomain)
        return super(MessagesPerPersonView, self).dispatch(request, *args, **kwargs)

    def get_queryset(self):
        qs = Message.public_objects.filter(
            person=self.person,
            writeitinstance=self.writeitinstance,
            )
        return qs

    def get_context_data(self, **kwargs):
        context = super(MessagesPerPersonView, self).get_context_data(**kwargs)
        context['person'] = self.person
        context['writeitinstance'] = self.writeitinstance
        return context class PerInstanceSearchView(SearchView):
    def __init__(self, *args, **kwargs):
        super(PerInstanceSearchView, self).__init__(*args, **kwargs)
        self.form_class = PerInstanceSearchForm
        self.template = 'nuntium/instance_search.html'

    def __call__(self, *args, **kwargs):
        request = args[0]
        self.slug = request.subdomain
        return super(PerInstanceSearchView, self).__call__(*args, **kwargs)

    def build_form(self, form_kwargs=None):
        self.writeitinstance = WriteItInstance.objects.get(slug=self.slug)
        if form_kwargs is None:
            form_kwargs = {}
        form_kwargs['writeitinstance'] = self.writeitinstance

        return super(PerInstanceSearchView, self).build_form(form_kwargs) class WriteMessageView(NamedUrlSessionWizardView):
    form_list = FORMS

    def dispatch(self, request, *args, **kwargs):
        self.writeitinstance = get_object_or_404(WriteItInstance, slug=request.subdomain)
        return super(WriteMessageView, self).dispatch(request=request, *args, **kwargs)

    def get(self, *args, **kwargs):
        the_person = None

        # If we have an ID in the URL and it matches someone, go straight to
        # /draft
        if kwargs.get('step') == 'who' and 'person_id' in self.request.GET:
            person_id = self.request.GET['person_id']
            try:
                the_person = self.writeitinstance.persons.get(popit_id=person_id)
            except Person.DoesNotExist:
                pass

        # If we've come to /who but there is only one person possible to
        # contact, go straight to /draft
        if self.steps.current == 'who' and self.writeitinstance.persons_with_contacts.count() == 1:
            the_person = self.writeitinstance.persons_with_contacts.first()

        if the_person is not None:
            self.storage.set_step_data('who', {self.get_form_prefix() + '-persons': [the_person.id]})
            self.storage.current_step = 'draft'
            return redirect(self.get_step_url('draft'))

        # Check that the form contains valid data
        if self.steps.current == 'preview' or self.steps.current == 'draft':
            message = self.get_form_values()
            if not message.get('persons'):
                # Form is missing persons, restart process
                self.storage.reset()
                self.storage.current_step = self.steps.first
                return redirect(self.get_step_url(self.steps.first))
        return super(WriteMessageView, self).get(*args, **kwargs)

    def get_template_names(self):
        return [TEMPLATES[self.steps.current]]

    def get_form_kwargs(self, step):
        if step == 'who':
            return {'persons_queryset': self.writeitinstance.persons_with_contacts.order_by('name')}
        else:
            return {}

    def get_form_values(self):
        """
        This code is taken from the django form wizards views.py
        Returns a dictionary of all form values
        """
        final_form_list = []
        # walk through the form list and try to validate the data again.
        for form_key in ['who', 'draft']:
            form_obj = self.get_form(step=form_key,
                data=self.storage.get_step_data(form_key),
                files=self.storage.get_step_files(form_key))
            if form_obj.is_bound:
                form_obj.is_valid()
                final_form_list.append(form_obj)
        data = {}
        [data.update(form.cleaned_data) for form in final_form_list]
        return data

    def done(self, form_list, **kwargs):
        data = {}
        [data.update(form.cleaned_data) for form in form_list]
        # Save a message object here
        message = Message(writeitinstance=self.writeitinstance, **data)
        message.save()
        Confirmation.objects.create(message=message)
        # Doing anything with the moderations?
        Moderation.objects.filter(message=message)

        return HttpResponseRedirect(reverse('write_message_sign', subdomain=self.writeitinstance.slug))

    def get_context_data(self, form, **kwargs):
        context = super(WriteMessageView, self).get_context_data(form=form, **kwargs)
        context['writeitinstance'] = self.writeitinstance
        if self.steps.current == 'who':
            context['persons'] = self.writeitinstance.persons.all()
        if self.steps.current == 'preview' or self.steps.current == 'draft':
            context['message'] = self.get_form_values()
            context['message']['people'] = context['message'].get('persons')
        return context

    def get_form_prefix(self, *args, **kwargs):
        prefix = super(WriteMessageView, self).get_form_prefix(*args, **kwargs)
        prefix += u"_" + self.writeitinstance.slug
        return prefix class WriteSignView(TemplateView):
    template_name = 'write/sign.html'

    def get_context_data(self, **kwargs):
        context = super(WriteSignView, self).get_context_data(**kwargs)
        context['writeitinstance'] = WriteItInstance.objects.get(slug=self.request.subdomain)
        return context class WriteItInstanceDetailView(DetailView):
    model = WriteItInstance
    template_name = 'nuntium/instance_detail.html'

    def dispatch(self, request, *args, **kwargs):
        self.kwargs['slug'] = request.subdomain
        return super(WriteItInstanceDetailView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(WriteItInstanceDetailView, self).get_context_data(**kwargs)
        recent_messages = Message.public_objects.filter(writeitinstance=self.object).order_by('-created')[:5]
        context['recent_messages'] = recent_messages
        return context class AcceptMessageView(RedirectView):
    permanent = False

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(AcceptMessageView, self).dispatch(*args, **kwargs)

    def get_redirect_url(self, *args, **kwargs):
        message = get_object_or_404(Message,
            pk=kwargs['pk'],
            writeitinstance__slug=self.request.subdomain,
            writeitinstance__owner=self.request.user
            )
        message.moderate()
        view_messages.info(self.request, _('The message "%(message)s" has been accepted') % {'message': message})
        return reverse(
            'messages_per_writeitinstance',
            subdomain=message.writeitinstance.slug,
            ) class AcceptModerationView(ModerationView):
    template_name = "nuntium/moderation_accepted.html"

    def get(self, *args, **kwargs):
        moderation = self.get_object()
        moderation.message.moderate()
        return super(AcceptModerationView, self).get(*args, **kwargs) class AnswerCreateView(AnswerEditMixin, CreateView):
    model = Answer
    template_name = "nuntium/profiles/create_answer.html"
    form_class = AnswerForm

    def get_message(self):
        message = Message.objects.get(id=self.kwargs['pk'])
        return message

    def get_form_kwargs(self):
        kwargs = super(AnswerCreateView, self).get_form_kwargs()
        kwargs['message'] = self.message
        return kwargs class AnswerUpdateView(AnswerEditMixin, UpdateView):
    model = Answer
    template_name = "nuntium/profiles/update_answer.html"
    fields = ['content']

    def get_message(self):
        return self.model.objects.get(id=self.kwargs['pk']).message class ConfirmationTemplateUpdateView(UpdateTemplateWithWriteitBase):
    form_class = ConfirmationTemplateForm
    model = ConfirmationTemplate class MessageDetail(WriteItInstanceOwnerMixin, DetailView):
    model = Message
    template_name = "nuntium/profiles/message_detail.html" class MessagesPerWriteItInstance(LoginRequiredMixin, ListView):
    model = Message
    template_name = 'nuntium/profiles/messages_per_instance.html'

    def get_queryset(self):
        self.writeitinstance = get_object_or_404(WriteItInstance, slug=self.request.subdomain, owner=self.request.user)
        return super(MessagesPerWriteItInstance, self).get_queryset().filter(writeitinstance=self.writeitinstance)

    def get_context_data(self, **kwargs):
        context = super(MessagesPerWriteItInstance, self).get_context_data(**kwargs)
        context['writeitinstance'] = self.writeitinstance
        return context class NewAnswerNotificationTemplateUpdateView(UpdateTemplateWithWriteitBase):
    form_class = NewAnswerNotificationTemplateForm
    model = NewAnswerNotificationTemplate class WriteItDeleteView(DeleteView):
    model = WriteItInstance

    # @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        self.kwargs['slug'] = request.subdomain
        return super(WriteItDeleteView, self).dispatch(request, *args, **kwargs)

    def get_object(self, queryset=None):
        obj = super(WriteItDeleteView, self).get_object(queryset=queryset)
        if not obj.owner == self.request.user:
            raise Http404
        return obj

    def get_success_url(self):
        url = reverse('your-instances')
        return url class WriteItInstanceAnswerNotificationView(WriteItInstanceAdvancedUpdateView):
    form_class = WriteItInstanceAnswerNotificationForm
    template_name = 'nuntium/writeitinstance_answernotification_form.html'

    def get_success_url(self):
        return reverse(
            'writeitinstance_answernotification_update',
            subdomain=self.object.writeitinstance.slug
            ) class WriteItInstanceApiAutoconfirmView(WriteItInstanceAdvancedUpdateView):
    form_class = WriteItInstanceApiAutoconfirmForm
    template_name = 'nuntium/writeitinstance_autoconfirm_form.html'

    def get_success_url(self):
        return reverse(
            'writeitinstance_api_autoconfirm_update',
            subdomain=self.object.writeitinstance.slug
            ) class WriteItInstanceApiDocsView(WriteItInstanceDetailBaseView):
    template_name = 'nuntium/writeitinstance_api_docs.html'

    def get_context_data(self, *args, **kwargs):
        context = super(WriteItInstanceApiDocsView, self).get_context_data(*args, **kwargs)
        current_domain = Site.objects.get_current().domain
        context['api_base_url'] = 'http://' + current_domain + '/api/v1/'
        return context class WriteItInstanceContactDetailView(WriteItInstanceDetailBaseView):
    template_name = 'nuntium/profiles/contacts/contacts-per-writeitinstance.html'

    def dispatch(self, request, *args, **kwargs):
        self.kwargs['slug'] = request.subdomain
        return super(WriteItInstanceContactDetailView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(WriteItInstanceContactDetailView, self).get_context_data(**kwargs)
        context['people'] = self.object.persons.order_by('name')
        return context class WriteItInstanceModerationView(WriteItInstanceAdvancedUpdateView):
    form_class = WriteItInstanceModerationForm
    template_name = 'nuntium/writeitinstance_moderation_form.html'

    def get_success_url(self):
        return reverse(
            'writeitinstance_moderation_update',
            subdomain=self.object.writeitinstance.slug
            ) class WriteItInstanceMaxRecipientsView(WriteItInstanceAdvancedUpdateView):
    form_class = WriteItInstanceMaxRecipientsForm
    template_name = 'nuntium/writeitinstance_max_recipients_form.html'

    def get_success_url(self):
        return reverse(
            'writeitinstance_maxrecipients_update',
            subdomain=self.object.writeitinstance.slug
            ) class WriteItInstanceRateLimiterView(WriteItInstanceAdvancedUpdateView):
    form_class = WriteItInstanceRateLimiterForm
    template_name = 'nuntium/writeitinstance_ratelimiter_form.html'

    def get_success_url(self):
        return reverse(
            'writeitinstance_ratelimiter_update',
            subdomain=self.object.writeitinstance.slug
            ) class WriteItInstanceStatusView(WriteItInstanceDetailBaseView):
    def render_to_response(self, context, **response_kwargs):
        status = self.object.pulling_from_popit_status
        return HttpResponse(
            json.dumps(status),
            content_type='application/json',
            **response_kwargs
        ) class WriteItInstanceTemplateUpdateView(DetailView):
    model = WriteItInstance
    template_name = 'nuntium/profiles/templates.html'

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        self.kwargs['slug'] = request.subdomain
        return super(WriteItInstanceTemplateUpdateView, self).dispatch(request, *args, **kwargs)

    def get_object(self, queryset=None):
        self.object = super(WriteItInstanceTemplateUpdateView, self).get_object(queryset=queryset)
        #OK I don't know if it is better to test by id
        if not self.object.owner.__eq__(self.request.user):
            raise Http404
        return self.object

    def get_context_data(self, **kwargs):
        context = super(WriteItInstanceTemplateUpdateView, self).get_context_data(**kwargs)
        context['new_answer_template_form'] = NewAnswerNotificationTemplateForm(
            writeitinstance=self.object,
            instance=self.object.new_answer_notification_template,
            )

        context['mailit_template_form'] = MailitTemplateForm(
            writeitinstance=self.object,
            instance=self.object.mailit_template,
            )
        context['confirmation_template_form'] = ConfirmationTemplateForm(
            writeitinstance=self.object,
            instance=self.object.confirmationtemplate,
            )
        return context class WriteItInstanceUpdateView(UpdateView):
    form_class = WriteItInstanceBasicForm
    template_name = "nuntium/writeitinstance_update_form.html"
    model = WriteItInstance

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        self.kwargs['slug'] = request.subdomain
        return super(WriteItInstanceUpdateView, self).dispatch(request, *args, **kwargs)

    def get_queryset(self):
        queryset = super(WriteItInstanceUpdateView, self).get_queryset().filter(owner=self.request.user)
        return queryset

    def get_success_url(self):
        return reverse(
            'writeitinstance_basic_update',
            subdomain=self.object.slug,
            ) class WriteItInstanceWebBasedView(WriteItInstanceAdvancedUpdateView):
    form_class = WriteItInstanceWebBasedForm
    template_name = 'nuntium/writeitinstance_web_based_form.html'

    def get_success_url(self):
        return reverse(
            'writeitinstance_webbased_update',
            subdomain=self.object.writeitinstance.slug
            ) class WriteitPopitRelatingView(FormView):
    form_class = RelatePopitInstanceWithWriteItInstance
    template_name = 'nuntium/profiles/writeitinstance_and_popit_relations.html'

    # This method also checks for instance ownership
    def get_writeitinstance(self):
        self.writeitinstance = get_object_or_404(WriteItInstance, slug=self.request.subdomain, owner=self.request.user)

    def dispatch(self, *args, **kwargs):
        self.get_writeitinstance()
        return super(WriteitPopitRelatingView, self).dispatch(*args, **kwargs)

    def get_form_kwargs(self):
        kwargs = super(WriteitPopitRelatingView, self).get_form_kwargs()
        kwargs['writeitinstance'] = self.writeitinstance
        return kwargs

    def get_success_url(self):
        return reverse('relate-writeit-popit', subdomain=self.writeitinstance.slug)

    def form_valid(self, form):
        form.relate()
        # It returns an AsyncResult http://celery.readthedocs.org/en/latest/reference/celery.result.html
        # that we could use for future information about this process
        return super(WriteitPopitRelatingView, self).form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(WriteitPopitRelatingView, self).get_context_data(**kwargs)
        context['writeitinstance'] = self.writeitinstance
        context['relations'] = self.writeitinstance.writeitinstancepopitinstancerecord_set.all()
        return context class MessageTogglePublic(RedirectView):
    permanent = False

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(MessageTogglePublic, self).dispatch(*args, **kwargs)

    def get_redirect_url(self, *args, **kwargs):
        message = get_object_or_404(Message,
            pk=kwargs['pk'],
            writeitinstance__slug=self.request.subdomain,
            writeitinstance__owner=self.request.user,
            )
        message.public = not message.public
        message.save()
        if message.public:
            view_messages.info(self.request, _("This message has been marked as public"))
        else:
            view_messages.info(self.request, _("This message has been marked as private"))
        return reverse('messages_per_writeitinstance', subdomain=self.request.subdomain) class RejectMessageView(RedirectView):
    permanent = False

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(RejectMessageView, self).dispatch(*args, **kwargs)

    def get_redirect_url(self, *args, **kwargs):
        message = get_object_or_404(Message,
            pk=kwargs['pk'],
            writeitinstance__slug=self.request.subdomain,
            writeitinstance__owner=self.request.user
            )
        message.public = False
        message.moderated = True
        message.save()
        view_messages.info(self.request, _('The message "%(message)s" has been rejected') % {'message': message})
        return reverse(
            'messages_per_writeitinstance',
            subdomain=message.writeitinstance.slug,
            ) class RejectModerationView(ModerationView):
    template_name = "nuntium/moderation_rejected.html"

    def get(self, *args, **kwargs):
        get = super(RejectModerationView, self).get(*args, **kwargs)
        self.object.message.public = False
        # It is turned True to avoid users to
        # mistakenly moderate this message
        # in the admin section
        self.object.message.moderated = True
        self.object.message.save()
        return get class ReSyncFromPopit(View):
    def dispatch(self, *args, **kwargs):
        if not self.request.user.is_authenticated():
            raise Http404
        return super(ReSyncFromPopit, self).dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        writeitinstance = get_object_or_404(WriteItInstance,
            slug=self.request.subdomain,
            owner=self.request.user)
        popits_previously_related = PopitApiInstance.objects.filter(
            writeitinstancepopitinstancerecord__writeitinstance=writeitinstance)

        popit_api_instance = get_object_or_404(popits_previously_related, pk=kwargs['popit_api_pk'])
        pull_from_popit.delay(writeitinstance, popit_api_instance)
        return HttpResponse() class WelcomeView(DetailView):
    model = WriteItInstance
    template_name = 'nuntium/profiles/welcome.html'

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        self.kwargs['slug'] = request.subdomain
        return super(WelcomeView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(WelcomeView, self).get_context_data(**kwargs)
        # passing URLs in for easy insertion into the translation tags
        # because we're using an overridden version of the url tag that
        # doesn't allow the use of "as" to pass the url as a variable
        # that can be quoted within a translation block. *sigh*
        context['url_template_update'] = reverse('writeitinstance_template_update', subdomain=self.request.subdomain)
        context['url_basic_update'] = reverse('writeitinstance_basic_update', subdomain=self.request.subdomain)
        context['url_maxrecipients_update'] = reverse('writeitinstance_maxrecipients_update', subdomain=self.request.subdomain)
        context['url_answernotification_update'] = reverse('writeitinstance_answernotification_update', subdomain=self.request.subdomain)
        context['url_recipients'] = reverse('contacts-per-writeitinstance', subdomain=self.request.subdomain)
        context['url_data_sources'] = reverse('relate-writeit-popit', subdomain=self.request.subdomain)
        return context class WriteItPopitUpdateView(UpdateView):
    form_class = WriteItPopitUpdateForm
    model = WriteitInstancePopitInstanceRecord

    def get_writeitinstance(self):
        self.writeitinstance = get_object_or_404(WriteItInstance, slug=self.request.subdomain, owner=self.request.user)

    def dispatch(self, *args, **kwargs):
        self.get_writeitinstance()
        if self.request.method != 'POST':
            return self.http_method_not_allowed(*args, **kwargs)
        return super(WriteItPopitUpdateView, self).dispatch(*args, **kwargs)

    def form_valid(self, form):
        form.save()
        return HttpResponse(
            json.dumps({
                'id': form.instance.id,
                'periodicity': form.instance.periodicity
                }),
            content_type='application/json'
        )

    def form_invalid(self, form):
        super(WriteItPopitUpdateView, self).form_invalid(form)
        return HttpResponse(
            json.dumps({
                'errors': form.errors
                }),
            content_type='application/json'
        ) class WriteItInstanceWebHooksView(WriteItInstanceDetailBaseView):
    template_name = 'nuntium/profiles/webhooks.html'

    def get_context_data(self, *args, **kwargs):
        context = super(WriteItInstanceWebHooksView, self).get_context_data(*args, **kwargs)
        context['form'] = WebhookCreateForm(writeitinstance=self.object)
        return context class WriteItInstanceCreateWebHooksView(CreateView):
    model = AnswerWebHook
    form_class = WebhookCreateForm

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        self.kwargs['slug'] = request.subdomain
        self.writeitinstance = get_object_or_404(WriteItInstance,
            slug=self.kwargs['slug'],
            owner=self.request.user)
        return super(WriteItInstanceCreateWebHooksView, self).dispatch(request, *args, **kwargs)

    def get_form_kwargs(self):
        kwargs = super(WriteItInstanceCreateWebHooksView, self).get_form_kwargs()
        kwargs['writeitinstance'] = self.writeitinstance
        return kwargs

    def get_success_url(self):
        return reverse(
            'writeitinstance_webhooks',
            subdomain=self.writeitinstance.slug,
            )
from django.conf.urls import patterns, url, include
from django.conf.urls.i18n import i18n_patterns
from django_downloadview import ObjectDownloadView
from contactos.views import ToggleContactEnabledView
from mailit.views import MailitTemplateUpdateView
from nuntium.models import AnswerAttachment
from nuntium.views import (
    AboutView,
    ConfirmView,
    HelpView,
    MessageThreadView,
    MessageThreadsView,
    MessagesFromPersonView,
    MessagesPerPersonView,
    PerInstanceSearchView,
    WriteMessageView,
    WriteSignView,
    WriteItInstanceDetailView,
    )
from nuntium.user_section.views import (
    AcceptMessageView,
    AcceptModerationView,
    AnswerCreateView,
    AnswerUpdateView,
    ConfirmationTemplateUpdateView,
    MessageDetail,
    MessagesPerWriteItInstance,
    NewAnswerNotificationTemplateUpdateView,
    WriteItDeleteView,
    WriteItInstanceAnswerNotificationView,
    WriteItInstanceApiAutoconfirmView,
    WriteItInstanceApiDocsView,
    WriteItInstanceContactDetailView,
    WriteItInstanceModerationView,
    WriteItInstanceMaxRecipientsView,
    WriteItInstanceRateLimiterView,
    WriteItInstanceStatusView,
    WriteItInstanceTemplateUpdateView,
    WriteItInstanceUpdateView,
    WriteItInstanceWebBasedView,
    WriteitPopitRelatingView,
    MessageTogglePublic,
    RejectMessageView,
    RejectModerationView,
    ReSyncFromPopit,
    WelcomeView,
    WriteItPopitUpdateView,
    WriteItInstanceWebHooksView,
    WriteItInstanceCreateWebHooksView
)
from nuntium.user_section.stats import StatsView



# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
download_attachment_view = ObjectDownloadView.as_view(model=AnswerAttachment, file_field="content")

managepatterns = patterns('',
    url(r'^$', WriteItInstanceUpdateView.as_view(), name='writeitinstance_basic_update'),
    url(r'^settings/moderation/$', WriteItInstanceModerationView.as_view(), name='writeitinstance_moderation_update'),

    url(r'^recipients/settings/$', WriteItInstanceMaxRecipientsView.as_view(), name='writeitinstance_maxrecipients_update'),