django.forms.models.model_to_dict

Here are the examples of the python api django.forms.models.model_to_dict taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

906 Examples 7

3 Source : views.py
with Apache License 2.0
from aropan

def query(request, name):
    redirect_url = request.GET.get('next', None)
    if redirect_url:
        request.session['next'] = redirect_url

    service = get_object_or_404(Service.active_objects, name=name)
    args = model_to_dict(service)
    args['redirect_uri'] = settings.HTTPS_HOST_ + reverse('auth:response', args=(name, ))
    args['state'] = generate_state()
    request.session['state'] = args['state']
    url = re.sub('[\n\r]', '', service.code_uri % args)
    return redirect(url)


@login_required

3 Source : pe_connect.py
with GNU Affero General Public License v3.0
from betagouv

def _model_fields_changed(initial, final_instance):
    """
    Return an array with fields of the model_instance object that will be changed on `save()`
    """
    final = model_to_dict(final_instance)
    class_name = type(final_instance).__name__
    return [f"{class_name}/{final_instance.pk}/{k}" for k, v in initial.items() if v != final.get(k)]


# External user data from PE Connect API:
# * transform raw data from API
# * dispatch data into models if possible
# * or store as key / value if needed


def set_pe_data_import_from_user_data(pe_data_import, user, status, user_data):

3 Source : test_models.py
with MIT License
from bihealth

    def test_initialization(self):
        expected = {
            'id': self.alert.pk,
            'message': 'alert',
            'user': self.superuser.pk,
            'date_expire': self.alert.date_expire,
            'active': True,
            'require_auth': True,
            'sodar_uuid': self.alert.sodar_uuid,
        }
        model_dict = model_to_dict(self.alert)
        # HACK: Can't compare markupfields like this. Better solution?
        model_dict.pop('description', None)
        self.assertEqual(model_dict, expected)

    def test__str__(self):

3 Source : test_models.py
with MIT License
from bihealth

    def test_initialization(self):
        expected = {
            'id': self.folder.pk,
            'name': 'folder',
            'project': self.project.pk,
            'folder': None,
            'owner': self.user_owner.pk,
            'description': 'description',
            'flag': None,
            'sodar_uuid': self.folder.sodar_uuid,
        }
        self.assertEqual(model_to_dict(self.folder), expected)

    def test_find_name(self):

3 Source : test_models.py
with MIT License
from bihealth

    def test_initialization(self):
        expected = {
            'id': self.file.pk,
            'name': 'file.txt',
            'file': self.file.file,
            'project': self.project.pk,
            'folder': self.folder.pk,
            'owner': self.user_owner.pk,
            'description': 'description',
            'public_url': True,
            'secret': SECRET,
            'flag': None,
            'sodar_uuid': self.file.sodar_uuid,
        }
        self.assertEqual(model_to_dict(self.file), expected)

    def test_find_name(self):

3 Source : test_models.py
with MIT License
from bihealth

    def test_file_access(self):
        """Test file can be accessed in database after creation"""
        file_data = FileData.objects.get(file_name=self.file.file.name)

        expected = {
            'id': file_data.pk,
            'file_name': 'filesfolders.FileData/bytes/file_name/'
            'content_type/file.txt',
            'content_type': 'text/plain',
            'bytes': base64.b64encode(self.file_content).decode('utf-8'),
        }

        self.assertEqual(model_to_dict(file_data), expected)

    def test_file_deletion(self):

3 Source : test_models.py
with MIT License
from bihealth

    def test_initialization(self):
        expected = {
            'id': self.hyperlink.pk,
            'name': 'Link',
            'url': 'http://www.google.com/',
            'project': self.project.pk,
            'folder': self.folder.pk,
            'owner': self.user_owner.pk,
            'description': 'description',
            'flag': None,
            'sodar_uuid': self.hyperlink.sodar_uuid,
        }
        self.assertEqual(model_to_dict(self.hyperlink), expected)

    def test__str__(self):

3 Source : test_models.py
with MIT License
from bihealth

    def test_initialization(self):
        """Test Role initialization"""
        expected = {
            'id': self.role.pk,
            'name': PROJECT_ROLE_OWNER,
            'description': self.role.description,
        }
        self.assertEqual(model_to_dict(self.role), expected)

    def test__str__(self):

3 Source : test_models.py
with MIT License
from bihealth

    def test_initialization(self):
        """Test RoleAssignment initialization"""
        self.assertEqual(
            model_to_dict(self.assignment_owner), self.expected_default
        )

    def test__str__(self):

3 Source : test_models.py
with MIT License
from bihealth

    def test_get_assignment(self):
        """Test get_assignment() results"""
        self.assertEqual(
            model_to_dict(
                RoleAssignment.objects.get_assignment(
                    self.user_alice, self.category_top
                )
            ),
            self.expected_default,
        )

    def test_get_assignment_anon(self):

3 Source : test_models.py
with MIT License
from bihealth

    def test_initialization(self):
        """Test ProjectInvite initialization"""
        expected = {
            'id': self.invite.pk,
            'email': '[email protected]',
            'project': self.project.pk,
            'role': self.role_contributor.pk,
            'issuer': self.user.pk,
            'date_expire': self.invite.date_expire,
            'message': '',
            'secret': SECRET,
            'sodar_uuid': self.invite.sodar_uuid,
            'active': True,
        }
        self.assertEqual(model_to_dict(self.invite), expected)

    def test__str__(self):

3 Source : test_models.py
with MIT License
from bihealth

    def test_initialization(self):
        """Test AppSetting initialization"""
        expected = {
            'id': self.setting_str.pk,
            'app_plugin': get_app_plugin(EXAMPLE_APP_NAME).get_model().pk,
            'project': self.project.pk,
            'name': 'str_setting',
            'type': 'STRING',
            'user': None,
            'value': 'test',
            'value_json': {},
            'user_modifiable': True,
            'sodar_uuid': self.setting_str.sodar_uuid,
        }
        self.assertEqual(model_to_dict(self.setting_str), expected)

    def test_initialization_integer(self):

3 Source : test_models.py
with MIT License
from bihealth

    def test_initialization_integer(self):
        """Test initialization with integer value"""
        expected = {
            'id': self.setting_int.pk,
            'app_plugin': get_app_plugin(EXAMPLE_APP_NAME).get_model().pk,
            'project': self.project.pk,
            'name': 'int_setting',
            'type': 'INTEGER',
            'user': None,
            'value': '170',
            'value_json': {},
            'user_modifiable': True,
            'sodar_uuid': self.setting_int.sodar_uuid,
        }
        self.assertEqual(model_to_dict(self.setting_int), expected)

    def test_initialization_json(self):

3 Source : test_models.py
with MIT License
from bihealth

    def test_initialization_json(self):
        """Test initialization with JSON value"""
        expected = {
            'id': self.setting_json.pk,
            'app_plugin': get_app_plugin(EXAMPLE_APP_NAME).get_model().pk,
            'project': self.project.pk,
            'name': 'json_setting',
            'type': 'JSON',
            'user': None,
            'value': None,
            'value_json': {'Testing': 'good'},
            'user_modifiable': True,
            'sodar_uuid': self.setting_json.sodar_uuid,
        }
        self.assertEqual(model_to_dict(self.setting_json), expected)

    def test__str__(self):

3 Source : test_models.py
with MIT License
from bihealth

    def test_initialization(self):
        """Test AppSetting initialization"""
        expected = {
            'id': self.setting_str.pk,
            'app_plugin': get_app_plugin(EXAMPLE_APP_NAME).get_model().pk,
            'project': None,
            'name': 'str_setting',
            'type': 'STRING',
            'user': self.user.pk,
            'value': 'test',
            'value_json': {},
            'user_modifiable': True,
            'sodar_uuid': self.setting_str.sodar_uuid,
        }
        self.assertEqual(model_to_dict(self.setting_str), expected)

    def test_initialization_integer(self):

3 Source : test_models.py
with MIT License
from bihealth

    def test_initialization_integer(self):
        """Test initialization with integer value"""
        expected = {
            'id': self.setting_int.pk,
            'app_plugin': get_app_plugin(EXAMPLE_APP_NAME).get_model().pk,
            'project': None,
            'name': 'int_setting',
            'type': 'INTEGER',
            'user': self.user.pk,
            'value': '170',
            'value_json': {},
            'user_modifiable': True,
            'sodar_uuid': self.setting_int.sodar_uuid,
        }
        self.assertEqual(model_to_dict(self.setting_int), expected)

    def test_initialization_json(self):

3 Source : test_models.py
with MIT License
from bihealth

    def test_initialization_json(self):
        """Test initialization with integer value"""
        expected = {
            'id': self.setting_json.pk,
            'app_plugin': get_app_plugin(EXAMPLE_APP_NAME).get_model().pk,
            'project': None,
            'name': 'json_setting',
            'type': 'JSON',
            'user': self.user.pk,
            'value': None,
            'value_json': {'Testing': 'good'},
            'user_modifiable': True,
            'sodar_uuid': self.setting_json.sodar_uuid,
        }
        self.assertEqual(model_to_dict(self.setting_json), expected)

    def test__str__(self):

3 Source : test_models.py
with MIT License
from bihealth

    def test_initialization(self):
        """Test ProjectUserTag initialization"""
        expected = {
            'id': self.tag.pk,
            'project': self.project.pk,
            'user': self.user.pk,
            'name': PROJECT_TAG_STARRED,
            'sodar_uuid': self.tag.sodar_uuid,
        }
        self.assertEqual(model_to_dict(self.tag), expected)

    def test__str__(self):

3 Source : test_models.py
with MIT License
from bihealth

    def test_initialization(self):
        """Test RemoteSite initialization"""
        expected = {
            'id': self.site.pk,
            'name': REMOTE_SITE_NAME,
            'url': REMOTE_SITE_URL,
            'mode': SODAR_CONSTANTS['SITE_MODE_TARGET'],
            'description': '',
            'secret': REMOTE_SITE_SECRET,
            'sodar_uuid': self.site.sodar_uuid,
            'user_display': REMOTE_SITE_USER_DISPLAY,
        }
        self.assertEqual(model_to_dict(self.site), expected)

    def test__str__(self):

3 Source : test_models.py
with MIT License
from bihealth

    def test_initialization(self):
        """Test RemoteProject initialization"""
        expected = {
            'id': self.remote_project.pk,
            'project_uuid': self.project.sodar_uuid,
            'project': self.project.pk,
            'site': self.site.pk,
            'level': SODAR_CONSTANTS['REMOTE_LEVEL_VIEW_AVAIL'],
            'date_access': None,
            'sodar_uuid': self.remote_project.sodar_uuid,
        }
        self.assertEqual(model_to_dict(self.remote_project), expected)

    def test__str__(self):

3 Source : test_models.py
with MIT License
from bihealth

    def test_initialization(self):
        expected = {
            'id': self.item.pk,
            'project': self.project.pk,
            'app_name': TEST_APP_NAME,
            'name': 'test_item',
            'user': self.user_owner.pk,
            'sodar_uuid': self.item.sodar_uuid,
            'data': {'test_key': 'test_val'},
        }

        self.assertEqual(model_to_dict(self.item), expected)

    def test__str__(self):

3 Source : test_models.py
with MIT License
from bihealth

    def test_initialization(self):
        """Test ProjectEvent initialization"""
        expected = {
            'id': self.event.pk,
            'project': self.project.pk,
            'app': 'projectroles',
            'user': self.user_owner.pk,
            'event_name': 'test_event',
            'description': 'description',
            'classified': False,
            'extra_data': {'test_key': 'test_val'},
            'sodar_uuid': self.event.sodar_uuid,
        }
        self.assertEqual(model_to_dict(self.event), expected)

    def test_initialization_no_project(self):

3 Source : test_models.py
with MIT License
from bihealth

    def test_initialization(self):
        """Test ProjectEventObject initialization"""
        expected = {
            'id': self.obj_ref.pk,
            'event': self.event.pk,
            'label': 'test_label',
            'name': 'test_name',
            'object_model': 'RoleAssignment',
            'object_uuid': self.assignment_owner.sodar_uuid,
            'extra_data': {'test_key': 'test_val'},
        }

        self.assertEqual(model_to_dict(self.obj_ref), expected)

    def test__str__(self):

3 Source : test_models.py
with MIT License
from bihealth

    def test_initialization(self):
        """Test ProjectEventStatus init"""
        expected = {
            'id': self.event_status_ok.pk,
            'event': self.event.pk,
            'status_type': 'OK',
            'description': 'OK',
            'extra_data': {'test_key': 'test_val'},
        }
        self.assertEqual(model_to_dict(self.event_status_ok), expected)

    def test_initialization_no_user(self):

3 Source : test_models.py
with MIT License
from bihealth

    def test_get_current_status(self):
        """Test the get_current_status() function of ProjectEvent"""
        status = self.event.get_current_status()

        expected = {
            'id': self.event_status_ok.pk,
            'event': self.event.pk,
            'status_type': 'OK',
            'description': 'OK',
            'extra_data': {'test_key': 'test_val'},
        }

        self.assertEqual(model_to_dict(status), expected)

    def test_get_timestamp(self):

3 Source : test_models.py
with MIT License
from bihealth

    def test_set_status(self):
        """Test the set_status() function of ProjectEvent"""
        new_status = self.event.set_status(
            'FAILED', status_desc='FAILED', extra_data={'test_key': 'test_val'}
        )

        expected = {
            'id': new_status.pk,
            'event': self.event.pk,
            'status_type': 'FAILED',
            'description': 'FAILED',
            'extra_data': {'test_key': 'test_val'},
        }

        self.assertEqual(model_to_dict(new_status), expected)

3 Source : views.py
with GNU General Public License v3.0
from canway

    def set_apply_by_manual(apply, ips, params, username):
        ip_pool = IpPools.objects.get(id=params["apply_ip_pool"])
        ip_net = IpNet.objects.get(id=params["apply_ip_net"])
        Ips.objects.filter(ip__in=ips).update(
            allocate_status=Ips.DISTRIBUTION,
            reserve_status=False,
            allocate_at=datetime.datetime.now(),
        )
        apply.auditor = username
        apply.audit_time = datetime.datetime.now()
        apply.apply_status = Apply.APPROVAL
        apply.saved_ips = {
            "ip_pool": model_to_dict(ip_pool),
            "sub_net_work": model_to_dict(ip_net),
            "ip_list": ips,
        }
        apply.save()

    @staticmethod

3 Source : serializers.py
with GNU General Public License v3.0
from canway

    def get_ip_obj(obj):
        ip_obj = model_to_dict(obj.ip)
        ip_obj["ip_pool"] = obj.ip.ip_net.ip_pool.name if obj.ip.ip_net else ""
        return ip_obj

    @staticmethod

3 Source : views.py
with GNU General Public License v3.0
from canway

    def destroy(self, request, *args, **kwargs):
        ip_pool = self.get_object()
        if ip_pool.can_delete():
            OperationLog.objects.create(
                operate_type=OperationLog.DELETE,
                operate_obj=IP_ADDRESS_POOL_MANAGEMENT,
                operator=request.user.username,
                operate_detail="删除地址池,详情:{}".format(json.dumps(model_to_dict(ip_pool))),
                result=True,
            )
            ip_pool.delete()
            return JsonResponse({"result": True, "message": "删除成功"})
        return JsonResponse({"result": False, "message": "删除失败,地址池下还存在正在使用或者待回收的IP"})

    @action(methods=["get"], detail=False)

3 Source : serializers.py
with GNU General Public License v3.0
from canway

    def get_ip_obj(obj):
        ip_obj = model_to_dict(obj.ip)
        try:
            ip_obj["ip_pool"] = obj.ip.ip_net.ip_pool.name
        except AttributeError:
            ip_obj["ip_pool"] = ""
        return ip_obj

    @staticmethod

3 Source : schedule_item_attendance.py
with GNU General Public License v2.0
from costasiella

    def __str__(self):
        from django.forms.models import model_to_dict
        data = model_to_dict(self)
        values = ["-----", str(type(self)), "-----"]
        for key, value in data.items():
            values.append(f'{key}: {value}')

        values.append("-----")
        return "\n".join(values)

        # return str(self.schedule_item.id) + ' [' + self.account.full_name + " - " + str(self.date) + '] ' + \
        #        self.attendance_type

    def get_cancel_before(self):

3 Source : chooser.py
with MIT License
from DivineITLimited

    def serialize(self, item):
        if isinstance(item, Model):
            return model_to_dict(item)
        else:
            return item

    def paginate(self, request, q, page=1):

3 Source : views.py
with MIT License
from ecjtuseclab

def backjson(page,rows,records,queryset):
    data = {
            'page':page,
            'total':math.ceil(records/rows),
            'records':records,
            'rows':[model_to_dict(item) for item in queryset]
        }
    json_data = json.dumps(data, default = __default)
    #print(json_data)
    return json_data

#统一的json返回
def backajax(state,message):

3 Source : tests_forms.py
with GNU General Public License v3.0
from esrg-knights

    def test_widget_changes(self):
        """ Tests if MartorWidgets are changed to ImageUploadMartorWidget """
        form = DummyLogEntryMarkdownForm(model_to_dict(self.obj), instance=self.obj, user=self.user)
        obj_repr_field = form['object_repr']
        self.assertIsNotNone(obj_repr_field)
        widget = obj_repr_field.field.widget
        self.assertIsNotNone(widget)
        self.assertIsInstance(widget, ImageUploadMartorWidget)

        # Correct widget params
        self.assertEqual(widget.content_type, self.content_type)
        self.assertEqual(widget.object_id, self.obj.id)

    def test_adopt_orphan_images_on_new_save(self):

3 Source : test_forms.py
with GNU General Public License v3.0
from esrg-knights

    def test_field_updates(self):
        """ Tests if the user does not change before saving, and is updated after saving """
        form = DummyForm(model_to_dict(self.obj), instance=self.obj, user=self.new_user)

        # Initial user is unchanged
        self.assertEqual(form['user'].value(), self.initial_user.id)
        self.assertEqual(LogEntry.objects.get(id=self.obj.id).user, self.initial_user)
        self.assertTrue(form.is_valid())

        # User changes after update
        form.save()
        self.assertEqual(LogEntry.objects.get(id=self.obj.id).user, self.new_user)

    def test_field_sanity_check(self):

3 Source : test_forms.py
with GNU General Public License v3.0
from esrg-knights

    def test_field_sanity_check(self):
        """ Tests if an AssertionError is raised if the Form does not have updating_user_field_name """
        class DummyForm2(DummyForm):
            updating_user_field_name = "foo"

        with self.assertRaisesMessage(AssertionError,
                "  <  class 'django.contrib.admin.models.LogEntry'> has no field foo"):
            DummyForm2(model_to_dict(self.obj), instance=self.obj, user=self.new_user)

class DummyModelAdmin(RequestUserToFormModelAdminMixin, ModelAdmin):

3 Source : test_serializer.py
with MIT License
from everhide

    def test_model(self):
        item = Entity.objects.first()
        pattern = model_to_dict(item)
        self.assertEqual(pattern, serial(item))

    def test_unknowns(self):

3 Source : archivehistory.py
with MIT License
from g0v

    def dump_row(self, base_dir, sub_dir, filename, house):
        target_dir = path.join(base_dir, sub_dir)
        makedirs(target_dir, exist_ok=True)

        plain_obj = model_to_dict(house)
        with open(path.join(target_dir, filename), 'w') as dest_file:
            json.dump(plain_obj, dest_file, ensure_ascii=False, cls=GeneralEncoder)

3 Source : views.py
with MIT License
from garyburgmann

    def get(self, request, format=None):
        """ Return request.user and request.auth """
        return Response({
            'request.user': model_to_dict(request.user),
            'request.auth': request.auth
        })

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_modelform_subclassed_model(self):
        class BetterWriterForm(forms.ModelForm):
            class Meta:
                # BetterWriter model is a subclass of Writer with an additional `score` field
                model = BetterWriter
                fields = '__all__'

        bw = BetterWriter.objects.create(name='Joe Better', score=10)
        self.assertEqual(sorted(model_to_dict(bw)),
                         ['id', 'name', 'score', 'writer_ptr'])

        form = BetterWriterForm({'name': 'Some Name', 'score': 12})
        self.assertTrue(form.is_valid())
        bw2 = form.save()
        self.assertEqual(bw2.score, 12)

    def test_onetoonefield(self):

3 Source : tests.py
with Apache License 2.0
from gethue

    def test_many_to_many(self):
        """Data for a ManyToManyField is a list rather than a lazy QuerySet."""
        blue = Colour.objects.create(name='blue')
        red = Colour.objects.create(name='red')
        item = ColourfulItem.objects.create()
        item.colours.set([blue])
        data = model_to_dict(item)['colours']
        self.assertEqual(data, [blue])
        item.colours.set([red])
        # If data were a QuerySet, it would be reevaluated here and give "red"
        # instead of the original value.
        self.assertEqual(data, [blue])

3 Source : schema.py
with BSD 2-Clause "Simplified" License
from getmetamapper

    def resolve_jdbc_connection(instance, info):
        """Returns JDBC connection information as a separate object.
        """
        return model_to_dict(instance, ['engine', 'host', 'username', 'database', 'port', 'extras'])

    def resolve_ssh_config(instance, info):

3 Source : signal_processor.py
with Apache License 2.0
from ihopeit

def post_delete_callback(sender, instance=None, using=None, **kwarg):
    dict_obj = model_to_dict( instance, exclude=("picture","attachment", "created_date", "modified_date") )
    message = "Instance of %s has been deleted: %s" % (type(instance), json.dumps(dict_obj, ensure_ascii=False))
    logger.info(message)
    send(message)

## 手工注册信号处理器
post_delete.connect(post_delete_callback, sender=Resume, dispatch_uid="resume_post_delete_dispatcher")

3 Source : operation_env.py
with Apache License 2.0
from JoyMobileDevelopmentTeam

def env_list(request):
    if request.method == "GET":
        return render(request, 'api/environment_manage.html')
    elif request.method == "POST":
        index = int(request.POST.get('index'))
        objects = EnvInfo.objects.filter().order_by('-id')
        envs = pagination_for_objects(objects, index)

        project_id_to_name = {}
        count = objects.count()
        for env in envs:
            project_id_to_name[env.belong_project_id] = env.belong_project.project_name
        data = dataToJson([model_to_dict(i) for i in envs])
        return JsonResponse(get_ajax_msg(1, 1, '获取环境列表成功', {'envs': data, 'count': count, 'currPage': index,'id_to_name':project_id_to_name}))


def env_query(request):

3 Source : operation_env.py
with Apache License 2.0
from JoyMobileDevelopmentTeam

def env_query(request):
    if request.method == "POST":
        env_info = json.loads(request.body.decode('utf-8'))
        env_id = env_info['id']
        envs = EnvInfo.objects.filter(id=env_id)
        if len(envs) == 0:
            return JsonResponse(get_ajax_msg(0, 0, '没有这条数据', {}))
        data = dataToJson([model_to_dict(i) for i in envs])
        return JsonResponse(get_ajax_msg(1, 1, '获取环境信息成功', {'envs': data}))

def env_search(request):

3 Source : operation_index.py
with Apache License 2.0
from JoyMobileDevelopmentTeam

def fail_task_list(request):
    if request.method == "POST":
        failRecords = filter_fail_records_for_user(request.user, TaskFailedRecord.objects.all().order_by('-id')[0:20], AUTH_VIEW)
        task_to_project = {}
        task_to_name = {}
        for record in failRecords:
            task_to_project[record.task_id.id] = record.task_id.belong_project.project_name
            task_to_name[record.task_id.id] = record.task_id.task_name
        data = dataToJson([model_to_dict(i) for i in failRecords])
        return JsonResponse(get_ajax_msg(1, 1, '获取失败记录成功', {'records': data, 'project_info':task_to_project,'task_info':task_to_name})) 

def summary_fail_task(request):

3 Source : operation_module.py
with Apache License 2.0
from JoyMobileDevelopmentTeam

def module_query(request):
    if request.method == 'POST':
        module_id = request.POST.get('id')
        modules = ModuleInfo.objects.filter(id=module_id)
        if len(modules) == 0:
            return JsonResponse(get_ajax_msg(0, 0, '没有这条数据', {}))
        modules = filter_modules_for_user(request.user, modules, AUTH_VIEW)
        data = dataToJson([model_to_dict(i) for i in modules])
        return JsonResponse(get_ajax_msg(1, 1, '获取模块成功', {'modules': data}))


def module_update(request):

3 Source : operation_project.py
with Apache License 2.0
from JoyMobileDevelopmentTeam

def project_list(request):
    if request.method == "GET":
        return render(request, 'api/project_list.html')
    elif request.method == "POST":
        index = int(request.POST.get('index'))
        objects = get_objects_for_user(request.user, AUTH_VIEW).all()
        projects = pagination_for_objects(objects, index)
        count = objects.count()
        data = dataToJson([model_to_dict(i) for i in projects])
        return JsonResponse(get_ajax_msg(1, 1, '获取工程列表成功', {'projects': data, 'count': count, 'currPage': index}))


def project_search(request):

3 Source : operation_project.py
with Apache License 2.0
from JoyMobileDevelopmentTeam

def project_query(request):
    if request.method == 'POST':
        project_id = request.POST.get('id')
        projects = ProjectInfo.objects.filter(id=project_id)
        if len(projects) == 0:
            return JsonResponse(get_ajax_msg(0, 0, '没有这条数据', {}))
        projects = get_objects_for_user(request.user, AUTH_VIEW, projects)  # 根据用户权限筛选项目对象
        data = dataToJson([model_to_dict(i) for i in projects])
        return JsonResponse(get_ajax_msg(1, 1, '获取项目成功', {'projects': data}))


def project_update(request):

3 Source : operation_report.py
with Apache License 2.0
from JoyMobileDevelopmentTeam

def report_list(request):
    if request.method == 'GET':
        return render_to_response('api/report_list.html')
    elif request.method == 'POST':
        index = int(request.POST.get('index'))
        objects = filter_reports_for_user(request.user, ReportInfo.objects.defer('result_data').all().order_by('-id'), AUTH_VIEW)
        reports = pagination_for_objects(objects, index)
    count = len(objects)
    # 去除不需要的数据---数据特别多
    tempData = [model_to_dict(i) for i in reports]
    del_fields(tempData, ['result_data', 'original_data'])
    data = dataToJson(tempData)
    return JsonResponse(get_ajax_msg(1, 1, '获取报告列表成功', {'reports': data, 'count': count, 'currPage': index}))


def report_search(request):

See More Examples