예제 #1
0
    def get_data(self):
        context = super(TeamAdminData, self).get_data()
        team = get_object_or_404(Team, code=self.kwargs["team"])
        context["data"]["object"] = dict(name=team.name,
                                         pk=team.pk,
                                         all_projects=team.all_projects,
                                         all_languages=team.all_languages)
        form = TeamEditForm(instance=team)
        member_types = ("members", "contributors", "translators", "reviewers",
                        "admins")
        for k in member_types:
            qs = getattr(team, k)
            count = qs.count()
            # not very optimal
            items = [{
                "username": member.username,
                "pk": member.pk
            } for member in getattr(team, k).all()[:10]]
            context["data"]["object"][k] = dict(items=items, count=count)
        context["data"]["form"] = RemoteForm(form).as_dict()
        context["data"]["form"]["fieldsets"] = OrderedDict(form.Meta.fieldsets)

        members_form = TeamMembersForm(instance=team)
        context["data"]["members_form"] = RemoteForm(members_form).as_dict()
        del context["data"]["members_form"]["data"]
        context["data"]["members_form"]["fieldsets"] = OrderedDict(
            members_form.Meta.fieldsets)
        return context
예제 #2
0
def my_ajax_view(request):
    csrf_middleware = CsrfViewMiddleware()

    response_data = {}
    if request.method == 'GET':
        # Get form definition
        form = ProjectForm()


    elif request.raw_post_data:
        request.POST = json.loads(request.raw_post_data)
        # Process request for CSRF
        csrf_middleware.process_view(request, None, None, None)
        form_data = request.POST.get('data', {})
        form = ProjectForm(form_data)
        if form.is_valid():
            form.save()

    field_configuration = {
        'include': ['title','duration'],
    }

    remote_form = RemoteForm(form, **field_configuration)
    # Errors in response_data['non_field_errors'] and response_data['errors']
    response_data.update(remote_form.as_dict())

    response = HttpResponse(
        json.dumps(response_data, cls=DjangoJSONEncoder),
        mimetype="application/json"
    )

    # Process response for CSRF
    csrf_middleware.process_response(request, response)
    return response
예제 #3
0
def handle_login(request):
    csrf_middleware = CsrfViewMiddleware()

    response_data = {}
    form = None

    if request.raw_post_data:
        request.POST = json.loads(request.raw_post_data)
        csrf_middleware.process_view(request, None, None, None)
        if 'data' in request.POST:
            form = LoginForm(data=request.POST['data'])
            if form.is_valid():
                if not request.POST['meta']['validate']:
                    auth_login(request, form.get_user())
    else:
        form = LoginForm(request)
        response_data['csrfmiddlewaretoken'] = get_token(request)

    if form is not None:
        remote_form = RemoteForm(form)
        response_data.update(remote_form.as_dict())

    response = HttpResponse(json.dumps(response_data, cls=LazyEncoder),
                            mimetype="application/json")
    csrf_middleware.process_response(request, response)
    return response
def api_user_login_via_otp_form_email_django_forms_example(request):
    csrf_middleware = CsrfViewMiddleware()

    response_data = {}
    if request.method == 'GET':
        # Get form definition
        form = UserLoginViaOtpFormEmail(initial={'email': settings.TESTING_EMAIL2})
    elif request.method == 'POST':
        if request.content_type  != 'application/json':
            return HttpResponse(json.dumps({"detail": "Unsupported media type \"'%s'\" in request." % request.content_type}), content_type="application/json",status=401);
        # Process request for CSRF
        csrf_middleware.process_view(request, None, None, None)
        form_data = json.loads(request.body)
        form = UserLoginViaOtpFormEmail(form_data)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            response = HttpResponse(
                {'email': email},
                content_type="application/json"
            )

    remote_form = RemoteForm(form)
    # Errors in response_data['non_field_errors'] and response_data['errors']
    response_data.update(remote_form.as_dict())

    response = HttpResponse(
        json.dumps(response_data, cls=DjangoJSONEncoder),
        content_type="application/json"
    )

    # Process response for CSRF
    csrf_middleware.process_response(request, response)
    return response
예제 #5
0
def my_ajax_view(request):
    csrf_middleware = CsrfViewMiddleware()

    response_data = {}
    if request.method == 'GET':
        # Get form definition
        form = IngredientForm10()
    elif request.method == 'POST':
        #request.POST = json.loads(request.body)
        # Process request for CSRF
        csrf_middleware.process_view(request, None, None, None)
        form_data = json.loads(request.body)
        form = IngredientForm10(form_data)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse("ingredients-api:singleform"))

    remote_form = RemoteForm(form)
    # Errors in response_data['non_field_errors'] and response_data['errors']
    response_data.update(remote_form.as_dict())

    response = HttpResponse(json.dumps(response_data, cls=DjangoJSONEncoder),
                            content_type="application/json")

    # Process response for CSRF
    csrf_middleware.process_response(request, response)
    return response
예제 #6
0
def handle_login(request):
    csrf_middleware = CsrfViewMiddleware()

    response_data = {}
    form = None

    if request.raw_post_data:
        request.POST = json.loads(request.raw_post_data)
        csrf_middleware.process_view(request, None, None, None)
        if 'data' in request.POST:
            form = LoginForm(data=request.POST['data'])
            if form.is_valid():
                if not request.POST['meta']['validate']:
                    auth_login(request, form.get_user())
    else:
        form = LoginForm(request)
        response_data['csrfmiddlewaretoken'] = get_token(request)

    if form is not None:
        remote_form = RemoteForm(form)
        response_data.update(remote_form.as_dict())

    response = HttpResponse(json.dumps(response_data, cls=LazyEncoder), mimetype="application/json")
    csrf_middleware.process_response(request, response)
    return response
예제 #7
0
def subscribe_with_key(req):
    key = req.GET.get("key", "")
    if not key:
        return HttpResponse(UR.prepare_response({}, 1,  "NOT ALLOWED"))
    e = M.Ensemble.objects.get(invitekey=key)
    if not e.use_invitekey:
        return  HttpResponse(UR.prepare_response({}, 1,  "NOT ALLOWED"))
    auth_user = UR.getUserInfo(req)
    if req.method == 'GET':
        if auth_user is None:  # Guest retrieving the subscribe page
            remote_form = RemoteForm(forms.UserForm())
            return HttpResponse(UR.prepare_response({"new_user": True, "class_settings": UR.model2dict(e),
                                                     "form": remote_form.as_dict()}))
        else:  # Logged in user retrieving the subscribe page
            user = auth_user
            remote_form = RemoteForm(forms.UserForm(instance=user))
            m = M.Membership.objects.filter(user=user, ensemble=e)
            if m.count() ==0:
                m = M.Membership(user=user, ensemble=e)
                m.save()
            return HttpResponse(UR.prepare_response({"new_user": False, "user": UR.model2dict(user),
                                                     "class_settings": UR.model2dict(e), "form": remote_form.as_dict()}))
    else:  # POST requests
        if auth_user is None:  # Guest subscribing to a class
            user = M.User(confkey="".join([choice(string.ascii_letters+string.digits) for i in xrange(0,32)]))
            req.POST = dict(req.POST.iteritems()) # Convert immutable object to mutable object
            user_form = forms.UserForm(req.POST, instance=user)
            if user_form.is_valid():
                user_form.save()
                m = M.Membership(user=user, ensemble=e)
                m.save() # membership exists but user is still invalid until has confirmed their email
                p = {
                    "tutorial_url": settings.GUEST_TUTORIAL_URL,
                    "conf_url": "%s://%s/?ckey=%s" %(settings.PROTOCOL, settings.NB_SERVERNAME, user.confkey),
                    "firstname": user.firstname,
                    "email": user.email
                }
                email = EmailMessage(
                "Welcome to NB, %s" % (user.firstname,),
                render_to_string("email/confirm_subscribe", p),
                settings.EMAIL_FROM,
                (user.email, ),
                (settings.EMAIL_BCC, ))
                email.send()
                return HttpResponse(UR.prepare_response({"new_user": True, "class_settings": UR.model2dict(e),
                                                         "next": "/subscribe_thanks"}))
            else:  # Invalid form - return form with error messages
                __clean_form(user_form)  # Ensure user-generated data gets cleaned before sending back the form
                remote_form = RemoteForm(user_form)
                return HttpResponse(UR.prepare_response({"new_user": True, "user": UR.model2dict(user),
                                                     "class_settings": UR.model2dict(e), "form": remote_form.as_dict()}))
        else:  # Logged in user subscribing to a class
            user = auth_user
            m = M.Membership.objects.filter(user=user, ensemble=e)
            if m.count() ==0:
                m = M.Membership(user=user, ensemble=e)
                m.save()
            return HttpResponse(UR.prepare_response({"new_user": False, "class_settings": UR.model2dict(e), "next": "/"}))
예제 #8
0
파일: views.py 프로젝트: neuman/indiepen
    def get(self, request, *args, **kwargs):
        supes = super(MediaUpdateView, self).get(request, *args, **kwargs)
        context = self.get_context_data(**kwargs)
        if self.request.is_ajax():
            remote_form = RemoteForm(self.get_form(self.form_class))
            blob = {
                'form':remote_form.as_dict(),
                'available_verbs':self.object.get_available_verbs(self.request.user),
                'object_instance':None
            }
            data = json.dumps(blob)
            out_kwargs = {'content_type':'application/json'}
            return HttpResponse(data, **out_kwargs)

        return supes

#media ENDS
예제 #9
0
def user_name_form(req):
    user = UR.getUserInfo(req, False)
    if user is None:
        redirect_url = "/login?next=%s" % (req.META.get("PATH_INFO","/"),)
        return HttpResponse(UR.prepare_response({"redirect": redirect_url}))

    remote_form = RemoteForm(forms.UserForm(instance=user))
    if req.method == 'POST':
        user_form = forms.EnterYourNameUserForm(req.POST, instance=user)
        if user_form.is_valid():
            user_form.save()
            return HttpResponse(UR.prepare_response({"redirect": "/?ckey=%s" % user.confkey}))
        else:  # Invalid form - return form with error messages
            __clean_form(user_form)  # Ensure user-generated data gets cleaned before sending back the form
            remote_form = RemoteForm(user_form)
            return HttpResponse(UR.prepare_response({"form": remote_form.as_dict()}))
    else:
        return HttpResponse(UR.prepare_response({"form": remote_form.as_dict()}))
예제 #10
0
def form_as_json(form):
    """
    Usage:

        {% load remote_form %}

        <script type='text/javascript'>
            var formData = {{ form|form_as_json }}
        </script>
    """
    if isinstance(form, forms.BaseFormSet):
        rf = RemoteFormSet(form)
    else:
        rf = RemoteForm(form)
    dct = rf.as_dict()
    return json.dumps(dct, cls=DjangoJSONEncoder)
예제 #11
0
def newsite_form(req):
    import base.models as M, random, string
    auth_user = UR.getUserInfo(req)
    if auth_user is not None:
        return HttpResponse(UR.prepare_response({"redirect": "/"}))
    if req.method == 'GET':
        remote_user_form = RemoteForm(forms.UserForm())
        remote_class_form = RemoteForm(forms.EnsembleForm())
        return HttpResponse(UR.prepare_response({"user_form": remote_user_form.as_dict(), "class_form": remote_class_form.as_dict()}))
    else:
        user = M.User(confkey="".join([choice(string.ascii_letters+string.digits) for i in xrange(0,32)]))
        ensemble = M.Ensemble()
        req.POST = dict(req.POST.iteritems()) # Convert immutable object to mutable object
        user_form       = forms.UserForm(req.POST, instance=user)
        ensemble_form   = forms.EnsembleForm(req.POST, instance=ensemble)
        if user_form.is_valid() and ensemble_form.is_valid():
            user_form.save()
            ensemble.invitekey =  "".join([ random.choice(string.ascii_letters+string.digits) for i in xrange(0,50)])
            ensemble_form.save()
            m = M.Membership(user=user, ensemble=ensemble, admin=True)
            m.save()
            p = {
                "tutorial_url": settings.GUEST_TUTORIAL_URL,
                "conf_url": "http://%s?ckey=%s" %(settings.NB_SERVERNAME, user.confkey),
                "firstname": user.firstname,
                "email": user.email
            }
            email = EmailMessage(
                "Welcome to NB, %s" % (user.firstname),
                render_to_string("email/confirm_newsite", p),
                settings.EMAIL_FROM,
                (user.email, ),
                (settings.EMAIL_BCC, ))
            email.send()
            return HttpResponse(UR.prepare_response({"redirect": "/newsite_thanks"}))
        else:  # Invalid form - return form with error messages
            __clean_form(user_form)  # Ensure user-generated data gets cleaned before sending back the form
            __clean_form(ensemble_form)  # Ensure user-generated data gets cleaned before sending back the form
            remote_user_form = RemoteForm(user_form)
            remote_class_form = RemoteForm(ensemble_form)
            return HttpResponse(UR.prepare_response({"user_form": remote_user_form.as_dict(),
                                                     "class_form": remote_class_form.as_dict()}))
예제 #12
0
파일: views.py 프로젝트: leckman/nbproject
def user_name_form(req):
    user = UR.getUserInfo(req, False)
    if user is None:
        redirect_url = "/login?next=%s" % (req.META.get("PATH_INFO", "/"), )
        return HttpResponse(UR.prepare_response({"redirect": redirect_url}))

    remote_form = RemoteForm(forms.UserForm(instance=user))
    if req.method == 'POST':
        user_form = forms.EnterYourNameUserForm(req.POST, instance=user)
        if user_form.is_valid():
            user_form.save()
            return HttpResponse(
                UR.prepare_response({"redirect": "/?ckey=%s" % user.confkey}))
        else:  # Invalid form - return form with error messages
            __clean_form(
                user_form
            )  # Ensure user-generated data gets cleaned before sending back the form
            remote_form = RemoteForm(user_form)
            return HttpResponse(
                UR.prepare_response({"form": remote_form.as_dict()}))
    else:
        return HttpResponse(
            UR.prepare_response({"form": remote_form.as_dict()}))
예제 #13
0
 def get_data(self):
     context = super(UserAdminAddData, self).get_data()
     form = UserAddForm()
     context["data"]["form"] = RemoteForm(form).as_dict()
     context["data"]["form"]["fieldsets"] = OrderedDict(form.Meta.fieldsets)
     return context
예제 #14
0
def test_login_form():
    from tests.data.authentication_form import AuthenticationForm, EXPECTED_FORM
    form = AuthenticationForm()
    remote_form = RemoteForm(form)
    remote_form_dict = remote_form.as_dict()
    assert remote_form_dict == EXPECTED_FORM
예제 #15
0
파일: views.py 프로젝트: leckman/nbproject
def newsite_form(req):
    import base.models as M, random, string
    auth_user = UR.getUserInfo(req)
    if auth_user is not None:
        return HttpResponse(UR.prepare_response({"redirect": "/"}))
    if req.method == 'GET':
        remote_user_form = RemoteForm(forms.UserForm())
        remote_class_form = RemoteForm(forms.EnsembleForm())
        return HttpResponse(
            UR.prepare_response({
                "user_form": remote_user_form.as_dict(),
                "class_form": remote_class_form.as_dict()
            }))
    else:
        user = M.User(confkey="".join([
            choice(string.ascii_letters + string.digits)
            for i in xrange(0, 32)
        ]))
        ensemble = M.Ensemble()
        req.POST = dict(
            req.POST.iteritems())  # Convert immutable object to mutable object
        user_form = forms.UserForm(req.POST, instance=user)
        ensemble_form = forms.EnsembleForm(req.POST, instance=ensemble)
        if user_form.is_valid() and ensemble_form.is_valid():
            user_form.save()
            ensemble.invitekey = "".join([
                random.choice(string.ascii_letters + string.digits)
                for i in xrange(0, 50)
            ])
            ensemble_form.save()
            m = M.Membership(user=user, ensemble=ensemble, admin=True)
            m.save()
            p = {
                "tutorial_url":
                settings.GUEST_TUTORIAL_URL,
                "conf_url":
                "http://%s?ckey=%s" % (settings.NB_SERVERNAME, user.confkey),
                "firstname":
                user.firstname,
                "email":
                user.email
            }
            email = EmailMessage("Welcome to NB, %s" % (user.firstname),
                                 render_to_string("email/confirm_newsite",
                                                  p), settings.EMAIL_FROM,
                                 (user.email, ), (settings.EMAIL_BCC, ))
            email.send()
            return HttpResponse(
                UR.prepare_response({"redirect": "/newsite_thanks"}))
        else:  # Invalid form - return form with error messages
            __clean_form(
                user_form
            )  # Ensure user-generated data gets cleaned before sending back the form
            __clean_form(
                ensemble_form
            )  # Ensure user-generated data gets cleaned before sending back the form
            remote_user_form = RemoteForm(user_form)
            remote_class_form = RemoteForm(ensemble_form)
            return HttpResponse(
                UR.prepare_response({
                    "user_form": remote_user_form.as_dict(),
                    "class_form": remote_class_form.as_dict()
                }))
예제 #16
0
파일: views.py 프로젝트: leckman/nbproject
def subscribe_with_key(req):
    key = req.GET.get("key", "")
    if not key:
        return HttpResponse(UR.prepare_response({}, 1, "NOT ALLOWED"))
    try:
        e = M.Ensemble.objects.get(invitekey=key)
    except ObjectDoesNotExist:
        return HttpResponse(UR.prepare_response({}, 1, "NOT ALLOWED"))
    if not e.use_invitekey:
        return HttpResponse(UR.prepare_response({}, 1, "NOT ALLOWED"))
    auth_user = UR.getUserInfo(req)
    if req.method == 'GET':
        if auth_user is None:  # Guest retrieving the subscribe page
            remote_form = RemoteForm(forms.UserForm())
            return HttpResponse(
                UR.prepare_response({
                    "new_user": True,
                    "class_settings": UR.model2dict(e),
                    "form": remote_form.as_dict()
                }))
        else:  # Logged in user retrieving the subscribe page
            user = auth_user
            remote_form = RemoteForm(forms.UserForm(instance=user))
            m = M.Membership.objects.filter(user=user, ensemble=e)
            if m.count() == 0:
                m = M.Membership(user=user, ensemble=e)
                m.save()
            return HttpResponse(
                UR.prepare_response({
                    "new_user": False,
                    "user": UR.model2dict(user),
                    "class_settings": UR.model2dict(e),
                    "form": remote_form.as_dict()
                }))
    else:  # POST requests
        if auth_user is None:  # Guest subscribing to a class
            user = M.User(confkey="".join([
                choice(string.ascii_letters + string.digits)
                for i in xrange(0, 32)
            ]))
            req.POST = dict(req.POST.iteritems()
                            )  # Convert immutable object to mutable object
            user_form = forms.UserForm(req.POST, instance=user)
            if user_form.is_valid():
                user_form.save()
                m = M.Membership(user=user, ensemble=e)
                m.save(
                )  # membership exists but user is still invalid until has confirmed their email
                p = {
                    "tutorial_url":
                    settings.GUEST_TUTORIAL_URL,
                    "conf_url":
                    "%s://%s/?ckey=%s" %
                    (settings.PROTOCOL, settings.NB_SERVERNAME, user.confkey),
                    "firstname":
                    user.firstname,
                    "email":
                    user.email
                }
                email = EmailMessage(
                    "Welcome to NB, %s" % (user.firstname, ),
                    render_to_string("email/confirm_subscribe",
                                     p), settings.EMAIL_FROM, (user.email, ),
                    (settings.EMAIL_BCC, ))
                email.send()
                return HttpResponse(
                    UR.prepare_response({
                        "new_user": True,
                        "class_settings": UR.model2dict(e),
                        "next": "/subscribe_thanks"
                    }))
            else:  # Invalid form - return form with error messages
                __clean_form(
                    user_form
                )  # Ensure user-generated data gets cleaned before sending back the form
                remote_form = RemoteForm(user_form)
                return HttpResponse(
                    UR.prepare_response({
                        "new_user": True,
                        "user": UR.model2dict(user),
                        "class_settings": UR.model2dict(e),
                        "form": remote_form.as_dict()
                    }))
        else:  # Logged in user subscribing to a class
            user = auth_user
            m = M.Membership.objects.filter(user=user, ensemble=e)
            if m.count() == 0:
                m = M.Membership(user=user, ensemble=e)
                m.save()
            return HttpResponse(
                UR.prepare_response({
                    "new_user": False,
                    "class_settings": UR.model2dict(e),
                    "next": "/"
                }))
예제 #17
0
def test_empty_form():
    from tests.data.empty_form import EmptyForm, EXPECTED_FORM
    form = EmptyForm()
    remote_form = RemoteForm(form)
    remote_form_dict = remote_form.as_dict()
    assert remote_form_dict == EXPECTED_FORM
예제 #18
0
    def test_empty(self):
        form = TestForm()
        remote_form = RemoteForm(form)
        remote_form_dict = remote_form.as_dict()

        self.assertEqual(remote_form_dict, EXPECT)
def test_disabled_form():
    form = DisabledForm()
    remote_form = RemoteForm(form)
    remote_form_dict = remote_form.as_dict()
    assert remote_form_dict == EXPECTED_FORM
예제 #20
0
파일: models.py 프로젝트: SM2015/orchid
 def get_serialized_builder_form(self):
     remote_form = RemoteForm(self.get_form())
     remote_form_dict = remote_form.as_dict()
     return remote_form_dict
예제 #21
0
def handle_form(request):
    """
    Handles the user submitting changes to their user profile.

    The form expects a 'module' GET parameter and an optional 'item_id'.  It
    then uses these to update the existing item or create a new instance
    """
    http404_view = 'myprofile.views.handle_form'

    item_id = request.REQUEST.get('id', 'new')
    module = request.REQUEST.get('module')
    module = module.replace(" ", "")

    ctx = {}
    ctx["success"] = True

    item = None
    if item_id != 'new':
        try:
            item = request.user.profileunits_set.get(pk=item_id)
            item = getattr(item, module.lower())
        except ProfileUnits.DoesNotExist:
            # User is trying to access a nonexistent PU
            # or a PU that belongs to someone else
            raise Http404(
                "{view}: ProfileUnit does not exist".format(view=http404_view))

    item_class = item.__class__

    try:
        form = getattr(forms, module + 'Form')
    except KeyError:
        # Someone must have manipulated request data?
        raise Http404("{view}: No form for module {module}".format(
            view=http404_view, module=module))

    data_dict = {
        'view_name': 'My Profile',
        'item_id': item_id,
        'module': module
    }

    if request.method == 'POST':
        if request.POST.get('action') == 'updateEmail':
            activation = ActivationProfile.objects.get_or_create(
                user=request.user, email=item.email)[0]
            activation.send_activation_email(primary=False)
            return HttpResponse('success')

        if item_id == 'new':
            form_instance = form(user=request.user,
                                 data=request.POST.dict(),
                                 auto_id=False)
        else:
            form_instance = form(user=request.user,
                                 instance=item,
                                 auto_id=False,
                                 data=request.POST.dict())
        model = form_instance._meta.model
        data_dict['form'] = form_instance
        data_dict['verbose'] = model._meta.verbose_name.title()

        model_name = model._meta.verbose_name.lower()
        if form_instance.is_valid():
            instance = form_instance.save()
            if request.META.get('HTTP_ACCEPT') == 'application/json':
                return HttpResponse(content_type='application/json',
                                    content=json.dumps(ctx))
            else:
                return HttpResponseRedirect(reverse('view_profile'))
        else:
            if request.META.get('HTTP_ACCEPT') == 'application/json':
                remote_form = RemoteForm(form_instance)
                return HttpResponse(content_type='application/json',
                                    content=json.dumps(remote_form.as_dict()))
            elif request.is_ajax():
                return HttpResponse(json.dumps(form_instance.errors),
                                    status=400)
    else:
        if item_id == 'new':
            form_instance = form(user=request.user, auto_id=False)
            if data_dict['module'] == 'Summary':
                try:
                    summary = request.user.profileunits_set.get(
                        content_type__name='summary')
                except ProfileUnits.DoesNotExist:
                    summary = None
                if summary:
                    return HttpResponseRedirect(
                        reverse('handle_form') + '?id=' + str(summary.id) +
                        '&module=' + data_dict['module'])
        else:
            form_instance = form(instance=item, auto_id=False)
            if data_dict['module'] == 'SecondaryEmail':
                data_dict['verified'] = item.verified
        model = form_instance._meta.model
        data_dict['form'] = form_instance
        data_dict['verbose'] = model._meta.verbose_name.title()
        remote_form = RemoteForm(form_instance)
        return HttpResponse(content_type='application/json',
                            content=json.dumps(remote_form.as_dict()))
예제 #22
0
def handle_instance_form(request, app_label, model_name, instance_id=None):
    if not request.user.is_authenticated():
        return HttpResponse('Unauthorized', status=401)

    csrf_middleware = CsrfViewMiddleware()

    response_data = {
        'meta': {
            'app_label': app_label,
            'model_name': model_name
        },
        'admin': {}
    }

    instance = None

    for model, model_admin in site._registry.items():
        if app_label != model._meta.app_label or model_name != model._meta.module_name:
            continue

        field_configuration = {
            'include': model_admin.fields or [],
            'exclude': model_admin.exclude or [],
            'ordering': model_admin.fields or [],
            'fieldsets': model_admin.fieldsets or {},
            'readonly': model_admin.readonly_fields or []
        }

        if instance_id is not None:
            response_data[instance_id] = instance_id
            try:
                instance = model.objects.get(pk=instance_id)
            except model.DoesNotExist:
                raise Http404('Invalid instance ID')

        current_model = model

        CurrentModelForm = ADMIN_FORM_OVERRIDES.get(model_name, None)

        if CurrentModelForm is None:

            class CurrentModelForm(ModelForm):
                class Meta:
                    model = current_model

        if request.method == 'GET':
            # Return instance form for given model name
            # Return initial values if instance ID is supplied, otherwise return empty form
            if instance is None:
                form = CurrentModelForm()
            else:
                form = CurrentModelForm(instance=instance)
                for field_name, initial_value in form.initial.items():
                    if initial_value is not None and field_name in form.fields:
                        form.fields[field_name].initial = initial_value

            response_data['csrfmiddlewaretoken'] = get_token(request)

            remote_form = RemoteForm(form, **field_configuration)
            response_data.update(remote_form.as_dict())
        elif request.raw_post_data:
            request.POST = json.loads(request.raw_post_data)
            csrf_middleware.process_view(request, None, None, None)
            if 'data' in request.POST:
                if instance_id is None:
                    form = CurrentModelForm(request.POST['data'])
                else:
                    form = CurrentModelForm(request.POST['data'],
                                            instance=instance)
                if form.is_valid():
                    if not request.POST['meta']['validate']:
                        form.save()

                remote_form = RemoteForm(form, **field_configuration)
                response_data.update(remote_form.as_dict())

    response = HttpResponse(json.dumps(response_data, cls=LazyEncoder),
                            mimetype="application/json")
    csrf_middleware.process_response(request, response)
    return response
예제 #23
0
def test_my_form():
    from tests.data.my_form import MyForm, EXPECTED_FORM
    form = MyForm()
    remote_form = RemoteForm(form)
    remote_form_dict = remote_form.as_dict()
    assert remote_form_dict == EXPECTED_FORM
예제 #24
0
def newmessage(request):
    from django.middleware.csrf import CsrfViewMiddleware
    csrf_middleware = CsrfViewMiddleware()
    response_data = {}
    if request.method == 'GET':
        # Get form definition
        form = BroadcastForm()
    elif request.method == 'POST':
        request.POST = json.loads(request.body)
        # Process request for CSRF
        csrf_middleware.process_view(request, None, None, None)
        form_data = request.POST.get('data', {})
        form = BroadcastForm(form_data)
        if form.is_valid():
            message = form.cleaned_data["message"]

            #Send Member
            if form.cleaned_data["member"]:
                queryset = _get_queryset(form)
                if queryset:
                    persons = Person.objects.filter(queryset)
                else:
                    persons = Person.objects.all()

                _send_sms(persons, message)
                _write_log(persons, message)

            #Send External Receiver
            if form.cleaned_data["external"]:
                if form.cleaned_data["extra_phones"]:
                    phones = form.cleaned_data["extra_phones"].split(',')
                    for phone in phones:
                        _send_single_sms(phone, message)
                        _write_single_log(message)

            #Send Non Member Receiver
            if form.cleaned_data["nonmembers"]:
                if form.cleaned_data["non_member"]:
                    phones = form.cleaned_data["non_member"]
                    for phone in phones:
                        person = nonmember.objects.get(id=int(phone.id))
                        _send_single_sms(phone, message)
                        _write_single_log(message,None,person)

            #Send Member Ulang Tahun
            if form.cleaned_data["ultah"]:
                if form.cleaned_data["ultah_today"]:
                    phones = form.cleaned_data["ultah_today"]
                    for phone in phones:
                        person = Person.objects.get(id=phone.id)
                        _send_single_sms(phone, message)
                        _write_single_log(message,None,person)

    remote_form = RemoteForm(form)
    # Errors in response_data['non_field_errors'] and response_data['errors']
    response_data.update(remote_form.as_dict())

    response = HttpResponse(
        json.dumps(response_data, cls=DjangoJSONEncoder),
        content_type="application/json"
    )

    # Process response for CSRF
    csrf_middleware.process_response(request, response)
    return response
예제 #25
0
    queryset = apps.customer.models.Customer.objects.all()
    serializer_class = apps.customer.serializers.CustomerSerializer

    #authentication_classes = [SessionAuthentication]
    permission_classes = [permissions.DjangoModelPermissions]

    def get(self, request):

        c = super(API_List, self).get(request)

        return c


class API_Detail(views.APIView):
    def get_object(self, pk):
        try:
            return apps.customer.models.Customer.objects.get(pk=pk)
        except apps.customer.models.Customer.DoesNotExist:
            raise Http404


class API_CustomerForm(views.APIView):
    def get_object(self):
        form = apps.customer.forms.CustomerForm


form = apps.customer.forms.CustomerForm()
remote_form = RemoteForm(form)
remote_form_dict = remote_form.as_dict()
#print remote_form_dict
예제 #26
0
파일: models.py 프로젝트: SM2015/orchid
 def get_serialized_builder_form(self):
     remote_form = RemoteForm(self.get_form())
     remote_form_dict = remote_form.as_dict()
     return remote_form_dict
예제 #27
0
 def list(self, request, *args, **kwargs):
     form = IngredientForm10()
     remote_form = RemoteForm(form)
     remote_form_dict = remote_form.as_dict()
     return Response(remote_form_dict)
예제 #28
0
def newmessage(request):
    from django.middleware.csrf import CsrfViewMiddleware
    csrf_middleware = CsrfViewMiddleware()
    response_data = {}
    if request.method == 'GET':
        # Get form definition
        form = BroadcastForm()
    elif request.method == 'POST':
        request.POST = json.loads(request.body)
        # Process request for CSRF
        csrf_middleware.process_view(request, None, None, None)
        form_data = request.POST.get('data', {})
        form = BroadcastForm(form_data)
        if form.is_valid():
            message = form.cleaned_data["message"]

            #Send Member
            if form.cleaned_data["member"]:
                queryset = _get_queryset(form)
                if queryset:
                    persons = Person.objects.filter(queryset)
                else:
                    persons = Person.objects.all()

                _send_sms(persons, message)
                _write_log(persons, message)

            #Send External Receiver
            if form.cleaned_data["external"]:
                if form.cleaned_data["extra_phones"]:
                    phones = form.cleaned_data["extra_phones"].split(',')
                    for phone in phones:
                        _send_single_sms(phone, message)
                        _write_single_log(message)

            #Send Non Member Receiver
            if form.cleaned_data["nonmembers"]:
                if form.cleaned_data["non_member"]:
                    phones = form.cleaned_data["non_member"]
                    for phone in phones:
                        person = nonmember.objects.get(id=int(phone.id))
                        _send_single_sms(phone, message)
                        _write_single_log(message, None, person)

            #Send Member Ulang Tahun
            if form.cleaned_data["ultah"]:
                if form.cleaned_data["ultah_today"]:
                    phones = form.cleaned_data["ultah_today"]
                    for phone in phones:
                        person = Person.objects.get(id=phone.id)
                        _send_single_sms(phone, message)
                        _write_single_log(message, None, person)

    remote_form = RemoteForm(form)
    # Errors in response_data['non_field_errors'] and response_data['errors']
    response_data.update(remote_form.as_dict())

    response = HttpResponse(json.dumps(response_data, cls=DjangoJSONEncoder),
                            content_type="application/json")

    # Process response for CSRF
    csrf_middleware.process_response(request, response)
    return response
예제 #29
0
def handle_instance_form(request, app_label, model_name, instance_id=None):
    if not request.user.is_authenticated():
        return HttpResponse('Unauthorized', status=401)

    csrf_middleware = CsrfViewMiddleware()

    response_data = {
        'meta': {
            'app_label': app_label,
            'model_name': model_name
        },

        'admin': {}
    }

    instance = None

    for model, model_admin in site._registry.items():
        if app_label != model._meta.app_label or model_name != model._meta.module_name:
            continue

        field_configuration = {
            'include': model_admin.fields or [],
            'exclude': model_admin.exclude or [],
            'ordering': model_admin.fields or [],
            'fieldsets': model_admin.fieldsets or {},
            'readonly': model_admin.readonly_fields or []
        }

        if instance_id is not None:
            response_data[instance_id] = instance_id
            try:
                instance = model.objects.get(pk=instance_id)
            except model.DoesNotExist:
                raise Http404('Invalid instance ID')

        current_model = model

        CurrentModelForm = ADMIN_FORM_OVERRIDES.get(model_name, None)

        if CurrentModelForm is None:
            class CurrentModelForm(ModelForm):
                class Meta:
                    model = current_model

        if request.method == 'GET':
            # Return instance form for given model name
            # Return initial values if instance ID is supplied, otherwise return empty form
            if instance is None:
                form = CurrentModelForm()
            else:
                form = CurrentModelForm(instance=instance)
                for field_name, initial_value in form.initial.items():
                    if initial_value is not None and field_name in form.fields:
                        form.fields[field_name].initial = initial_value

            response_data['csrfmiddlewaretoken'] = get_token(request)

            remote_form = RemoteForm(form, **field_configuration)
            response_data.update(remote_form.as_dict())
        elif request.raw_post_data:
            request.POST = json.loads(request.raw_post_data)
            csrf_middleware.process_view(request, None, None, None)
            if 'data' in request.POST:
                if instance_id is None:
                    form = CurrentModelForm(request.POST['data'])
                else:
                    form = CurrentModelForm(request.POST['data'], instance=instance)
                if form.is_valid():
                    if not request.POST['meta']['validate']:
                        form.save()

                remote_form = RemoteForm(form, **field_configuration)
                response_data.update(remote_form.as_dict())

    response = HttpResponse(json.dumps(response_data, cls=LazyEncoder), mimetype="application/json")
    csrf_middleware.process_response(request, response)
    return response
예제 #30
0
def handle_form(request):
    """
    Handles the user submitting changes to their user profile.

    The form expects a 'module' GET parameter and an optional 'item_id'.  It
    then uses these to update the existing item or create a new instance
    """
    http404_view = "myprofile.views.handle_form"

    item_id = request.REQUEST.get("id", "new")
    module = request.REQUEST.get("module")
    module = module.replace(" ", "")

    ctx = {}
    ctx["success"] = True

    item = None
    if item_id != "new":
        try:
            item = request.user.profileunits_set.get(pk=item_id)
            item = getattr(item, module.lower())
        except ProfileUnits.DoesNotExist:
            # User is trying to access a nonexistent PU
            # or a PU that belongs to someone else
            raise Http404("{view}: ProfileUnit does not exist".format(view=http404_view))

    item_class = item.__class__

    try:
        form = getattr(forms, module + "Form")
    except KeyError:
        # Someone must have manipulated request data?
        raise Http404("{view}: No form for module {module}".format(view=http404_view, module=module))

    data_dict = {"view_name": "My Profile", "item_id": item_id, "module": module}

    if request.method == "POST":
        if request.POST.get("action") == "updateEmail":
            activation = ActivationProfile.objects.get_or_create(user=request.user, email=item.email)[0]
            activation.send_activation_email(primary=False)
            return HttpResponse("success")

        if item_id == "new":
            form_instance = form(user=request.user, data=request.POST.dict(), auto_id=False)
        else:
            form_instance = form(user=request.user, instance=item, auto_id=False, data=request.POST.dict())
        model = form_instance._meta.model
        data_dict["form"] = form_instance
        data_dict["verbose"] = model._meta.verbose_name.title()

        model_name = model._meta.verbose_name.lower()
        if form_instance.is_valid():
            instance = form_instance.save()
            if request.META.get("HTTP_ACCEPT") == "application/json":
                return HttpResponse(content_type="application/json", content=json.dumps(ctx))
            else:
                return HttpResponseRedirect(reverse("view_profile"))
        else:
            if request.META.get("HTTP_ACCEPT") == "application/json":
                remote_form = RemoteForm(form_instance)
                return HttpResponse(content_type="application/json", content=json.dumps(remote_form.as_dict()))
            elif request.is_ajax():
                return HttpResponse(json.dumps(form_instance.errors), status=400)
    else:
        if item_id == "new":
            form_instance = form(user=request.user, auto_id=False)
            if data_dict["module"] == "Summary":
                try:
                    summary = request.user.profileunits_set.get(content_type__name="summary")
                except ProfileUnits.DoesNotExist:
                    summary = None
                if summary:
                    return HttpResponseRedirect(
                        reverse("handle_form") + "?id=" + str(summary.id) + "&module=" + data_dict["module"]
                    )
        else:
            form_instance = form(instance=item, auto_id=False)
            if data_dict["module"] == "SecondaryEmail":
                data_dict["verified"] = item.verified
        model = form_instance._meta.model
        data_dict["form"] = form_instance
        data_dict["verbose"] = model._meta.verbose_name.title()
        remote_form = RemoteForm(form_instance)
        return HttpResponse(content_type="application/json", content=json.dumps(remote_form.as_dict()))
def serialize_BuilderForm(builder_form):
    c = Context()
    z = FormForForm(builder_form, c)
    remote_form = RemoteForm(z)
    remote_form_dict = remote_form.as_dict()
    return remote_form_dict