Exemplo n.º 1
0
    def get_other_details(self):
        user_meta = UserMeta.objects.filter(user=self.author)
        tags = self.tags() if self.tags() else []
        categories = self.categories() if self.categories() else []
        # Post Detail
        data = {"post_details": model_to_dict(self, ["id", "author", "title", "post_date", "excerpt", "content"])}
        data["post_details"].update(PostMeta.get_featured_image(self))

        # Author Details
        data.update({"author_details":
                         {"first_name": user_meta.filter(key="first_name").values_list('value', flat=True)[0],
                          "last_name": user_meta.filter(key="last_name").values_list('value', flat=True)[0],
                          "description": user_meta.filter(key="description").values_list('value', flat=True)[0]}
                    })
        # Tags Detail
        tags_list = []
        for tag in tags:
            tags_list.append(model_to_dict(tag, ["id", "name", "slug"]))
        data.update({"tags": tags_list})
        # Categories Detail
        categories_list = []
        for category in categories:
            categories_list.append(model_to_dict(category, ["id", "name", "slug"]))
        data.update({"categories": categories_list})
        return data
Exemplo n.º 2
0
    def batch_import(cls, tags, current_vocabularies, current_languages):
        result = []

        for vocabulary_tag in tags:
            voc_dict = vocabulary_tag.attrib

            if voc_dict['ID'] == '0':
                continue

            value = vocabulary_tag.text
            if not value:
                value = ''

            vocabulary = Vocabulary(
                id=int(voc_dict['ID']),
                language=current_languages[int(voc_dict['langid'])],
                value=value
            )

            try:
                if model_to_dict(vocabulary) != model_to_dict(current_vocabularies[vocabulary.id]):
                    vocabulary.save()
            except KeyError:
                vocabulary.save()

            result.append(vocabulary)

        return result
Exemplo n.º 3
0
    def get_manage(self, request, method=None, pk=None):

        s = Auth().is_auth(request)
        if not s:
            return Auth.routeLogin

        from .forms import FormRegister

        self.form_obj = FormRegister
        self.form = self.form_obj()

        if method == 'update':
            self.instance = self.model.pp.get(pk=pk)
            self.form = self.form_obj(instance=self.instance, data=model_to_dict(self.instance))

        else:
            self.instance = self.model()
            self.form = self.form_obj(instance=self.instance)

        self.form = self.form_obj(instance=self.instance, data=model_to_dict(self.instance))

        self.set_template("users", "manage.html")
        self.set_menu("users", "menu.html")
        self.set_form_action(method, pk)
        self.page.view = "form-users.html"
        self.page.method = method
        self.page.obj = self.instance

        return render_to_response(
            self.template,
            {'page': self.page, 'form': self.form},
            context_instance=RequestContext(request)
        )
Exemplo n.º 4
0
def tree_add_from_parent( request, parentid ):
    if parentid != None:
        parent = get_object_or_404( Evalitem, pk=parentid )
    else:
        parent = None
    if request.method == 'GET':
        form = EvalitemCreateForm()
        return render( request, "evalitem/tree/add_from_parent.html",
                      {'parent':parent,
                       'form': form} )
    elif request.method == 'POST':
        form = EvalitemCreateForm( request.POST, request.FILES )
        if form.is_valid():
            obj = form.save( False )
            if parent == None:
                Evalitem.add_root( **model_to_dict( obj ) )
                return HttpResponseRedirect( reverse( tree_root ) )
            else:
                parent.add_child( **model_to_dict( obj ) )
                return HttpResponseRedirect( reverse( tree_from_parent,
                             kwargs={'parentid':parentid} )
                    )
        else:
            return render( request, "evalitem/tree/add_from_parent.html",
                      {'parent':parent,
                       'form': form} )
Exemplo n.º 5
0
    def batch_import(cls, tags, current_texs, current_languages):
        result = []
        for tex_tag in tags:
            tex_dict = tex_tag.attrib

            if tex_dict['ID'] == '0':
                continue

            value = tex_tag.text
            if not value:
                value = ''

            tex = Tex(
                id=int(tex_dict['ID']),
                language=current_languages[int(tex_dict['langid'])],
                value=value
            )

            try:
                if model_to_dict(tex) != model_to_dict(current_texs[tex.id]):
                    tex.save()
            except KeyError:
                tex.save()

            result.append(tex)

        return result
Exemplo n.º 6
0
 def to_json(self):
     config = model_to_dict(self)
     config['fuzzy_properties'] = [
         model_to_dict(fuzzy_property, exclude=['id']) for fuzzy_property in config['fuzzy_properties']
     ]
     config['ignore_patterns'] = [
         model_to_dict(ignore_pattern, exclude=['id']) for ignore_pattern in config['ignore_patterns']
     ]
     return config
Exemplo n.º 7
0
 def test_citizen_created(self, get_records, open):
     citizen = CitizenFactory()
     data = model_to_dict(citizen)
     citizen.delete()
     get_records.return_value = [data]
     self.assertFalse(Citizen.objects.exists())
     stats = import_citizen_dump(input_filename=None)
     self.assertEqual(1, stats.records_read)
     new_cit = Citizen.objects.get()
     self.assertEqual(data, model_to_dict(new_cit))
Exemplo n.º 8
0
 def test_citizen_updated(self, get_records, open):
     cit1 = CitizenFactory()
     cit2 = CitizenFactory()
     citizen = CitizenFactory()
     data = model_to_dict(citizen)
     new_name = 'Jim Bob'
     data['first_name'] = new_name
     get_records.return_value = [model_to_dict(cit1), model_to_dict(cit2), data]
     stats = import_citizen_dump(input_filename=None, max_change_percent=34)
     self.assertEqual(3, stats.records_read)
     updated_cit = Citizen.objects.get(pk=citizen.pk)
     self.assertEqual(new_name, updated_cit.first_name)
Exemplo n.º 9
0
def jselaus(request):
    junat = list(sql_komentajat.hae_junat())
    junat = [model_to_dict(juna) for juna in junat]
    junat = json.dumps(junat, default=date_handler)

    pysahdykset = list(sql_komentajat.hae_pysahdykset())
    pysahdykset = [model_to_dict(pysahdys) for pysahdys in pysahdykset]
    pysahdykset[0]["saapumisaika"] = str(pysahdykset[0]["saapumisaika"])
    pysahdykset[0]["lahtoaika"] = str(pysahdykset[0]["lahtoaika"])
    pysahdykset = json.dumps(pysahdykset, default=date_handler)

    return render(request, 'junaApp/jselaus.html', {"junat" : junat, "pysahdykset" : pysahdykset})
Exemplo n.º 10
0
 def dump_tr_model(self, item, exclude=[]):
     result = model_to_dict(item, exclude=exclude)#, exclude=('password',))
     #result['author'] = model_to_dict(item.author, exclude=('password',))
     result['locale'] = model_to_dict(item.locale)
     result['canEdit'] = False
     if self.request.user:
         result['canEdit'] = self.request.user.id == item.author_id
     try:
         result['statistic'] = item.grammar().statistic()
     except NotImplementedError as _:
         pass
     result['application'] = model_to_dict(item.application)
     return result
Exemplo n.º 11
0
 def test_too_many_changes(self, get_records, open):
     cit1 = CitizenFactory()
     cit2 = CitizenFactory()
     citizen = CitizenFactory()
     data = model_to_dict(citizen)
     new_name = 'Jim Bob'
     data['first_name'] = new_name
     get_records.return_value = [model_to_dict(cit1), model_to_dict(cit2), data]
     # Import raises an exception:
     with self.assertRaises(TooManyChanges):
         import_citizen_dump(input_filename=None, max_change_percent=10)
     # Citizen is unchanged:
     new_citizen = refresh_model(citizen)
     self.assertEqual(citizen.first_name, new_citizen.first_name)
Exemplo n.º 12
0
def recent( request ):
    _cur_user = request.META.get('HTTP_X_COMICWEB_USER')
    logger.debug('get recentlist for user %s' % _cur_user)
    ret = []
    volumes = []
    try:
        user = User.objects.get(username=_cur_user)
        for r in Reading.objects.filter(user=user).order_by('when').reverse():
            if not r.issue.volume in volumes:
                volumes.append(r.issue.volume)
                ret.append({'issue' : model_to_dict(r.issue), 'volume' : model_to_dict(r.issue.volume), 'latest_reading' : model_to_dict(r.issue.get_latest_reading(user))})
    except:
        logger.warn("Unable to get recent list :\n%s" % traceback.format_exc())
    return HttpResponse(json.dumps(ret, cls=DjangoJSONEncoder), content_type="application/json")
Exemplo n.º 13
0
	def get(self, request, id):
		context = {}
		nemov = Nemovitost.objects.get(id=id)
		if nemov.typ == 'Stavba':
			result = Stavba.objects.get(id=nemov)
			context['typ'] = 'Stavba'
		else:
			result = Parcela.objects.get(id=nemov)
		context['nemov'] = model_to_dict(nemov)
		context['object'] = model_to_dict(result)
		context['dotaz_form'] = self.dotaz_form()
		context['navhr_form'] = self.navhr_form()
		
		return render_to_response(self.template, RequestContext(request, context))
Exemplo n.º 14
0
def scrumboard_sprint_active_select(context):
    from django.forms import model_to_dict
    from scrumboard.models import Sprint

    active_sprints = [model_to_dict(sprint, fields=['id', 'name']) for sprint in Sprint.get_active_sprints()]

    if 'current_sprint_pk' in context.request.session:
        current_sprint = Sprint.objects.get(pk=context.request.session['current_sprint_pk'])
    else:
        current_sprint = Sprint.get_current_sprint()

    return {'active_sprints': active_sprints,
            'current_sprint': model_to_dict(current_sprint),
            'current_url': context.request.get_full_path()}
Exemplo n.º 15
0
def getTrip(request):
    tripId = request.GET['tripId']
    trip = models.Trip.objects.get(id=tripId)
    tripValues = models.Trip.objects.values('name', 'type', 'date').get(id=tripId)
    tripLegValues = []   
    tripLegs = trip.tripleg_set.all()
    
    for tripLeg in tripLegs:
        tripLegData = {'startAddress': model_to_dict(tripLeg.startAddress),
                       'endAddress': model_to_dict(tripLeg.endAddress)}
        tripLegValues.append(tripLegData)
    
    returnValues = {'trip': tripValues, 'tripLegs': tripLegValues} 
    
    return HttpResponse(json.dumps(returnValues, cls=DjangoJSONEncoder), mimetype="application/json")
Exemplo n.º 16
0
def getJSONObj():
    mainObj = {}
    issues = Issue.objects.order_by('categoryName').all()
    for issue in issues:
        issuekey = issue.keyid

        mainObj[issuekey] = model_to_dict(issue)
        mainObj[issuekey]['layers'] = {}
        layers = issue.layer_set.order_by('subject').all()
        #order layers
        for layer in layers:
            layerkey = layer.keyid

            mainObj[issuekey]['layers'][layerkey] = model_to_dict(layer)

    return json.dumps(mainObj)
Exemplo n.º 17
0
    def store_performance_artifact(
            self, job_ids, performance_artifact_placeholders):
        """
        Store the performance data
        """

        # Retrieve list of job signatures associated with the jobs
        job_data = self.get_job_signatures_from_ids(job_ids)

        job_ref_data_signatures = set()
        map(
            lambda job_guid: job_ref_data_signatures.add(
                job_data[job_guid]['signature']
            ),
            job_data.keys()
        )

        for perf_data in performance_artifact_placeholders:
            job_guid = perf_data["job_guid"]
            ref_data_signature = job_data[job_guid]['signature']
            ref_data = model_to_dict(ReferenceDataSignatures.objects.get(
                signature=ref_data_signature))

            # adapt and load data into placeholder structures
            if perf_data['name'] == 'talos_data':
                load_talos_artifacts(self.project, ref_data, job_data, perf_data)
            else:
                load_perf_artifacts(self.project, ref_data, job_data, perf_data)
Exemplo n.º 18
0
 def update(self, request, slug):
     "update a project"
     p = Project.objects.filter(slug=slug)
     if not p:
         return rc.NOT_FOUND
     elif len(p) > 1:
         return rc.BAD_REQUEST
     elif "has_admin_perm" in p[0].get_perms(request.user):
         p = p[0]
         initial = model_to_dict(p)
         data = request.PUT
         data._mutable = True
         if "admins" not in data:
             data["admins"] = ",".join([a.username for a in p.admins.all()])
         if "members" not in data:
             data["members"] = ",".join([m.username for m in p.members.all()])
         filt = lambda v: v not in data.keys()
         for field in filter(filt, [f.name for f in p._meta.fields]):
             data[field] = initial.get(field, None)
         form = ProjectEditForm(data=data, instance=p)
         if form.is_valid():
             p = form.save()
             return p
         return rc.BAD_REQUEST
     else:
         return rc.FORBIDDEN
Exemplo n.º 19
0
 def validate_unique(self):
     super(ToleranceForm, self).validate_unique()
     if not self.instance.pk:
         params = forms.model_to_dict(self.instance)
         params.pop("id")
         if models.Tolerance.objects.filter(**params).count() > 0:
             self._update_errors({forms.models.NON_FIELD_ERRORS: ["Duplicate Tolerance. A Tolerance with these values already exists"]})
Exemplo n.º 20
0
 def post(self, request):
     reviewer_id = request.POST.get('reviewer_id')
     movie_id = request.POST.get('movie_id')
     rating = request.POST.get('rating')
     review_object = Review.objects.create(reviewer_id=reviewer_id, movie_id=movie_id, rating=rating)
     review_dict = model_to_dict(review_object)
     return HttpResponse(json.dumps(review_dict), status=201, content_type='application/json')
Exemplo n.º 21
0
    def post(self, request):
        pro_id = request.GET.get('id', 1)
        prod = Products.objects.get(sku=pro_id)

        temp = get_template("pay.html")
        paypalform = PaypalForm(request.POST)
        html = RequestContext(request, {'form': paypalform})

        if paypalform.is_valid():
            model_instance = paypalform.save(commit=False)
            model_instance.item = prod
            model_instance.save()
            payinfo = model_to_dict(model_instance)
            try:
                d = paypal()
                item = paypal.convert_items(prod)
                payinfo = paypal.convertpaymentinfo(model_instance, item)
                q = d.handler(payinfo)
                payinfo['result'] = q
                if (q):
                    logging.debug("not succeed")
                    return HttpResponseRedirect('/thanks/')
                else:
                    return HttpResponseRedirect('/failed/?reason=' + d.getError())

            except Exception as E:
                return HttpResponseRedirect('/failed/?reas=' + E.message)
            html = RequestContext(request, {'form': paypalform, "info": payinfo})

        return render_to_response("pay.html", html)
Exemplo n.º 22
0
    def test_superseded_by_saves(self):
        self.item2 = self.itemType.objects.create(name="admin_page_test_oc_2",definition=" ",workgroup=self.wg1,**self.create_defaults)

        self.login_editor()
        response = self.client.get(reverse("admin:%s_%s_change"%(self.itemType._meta.app_label,self.itemType._meta.model_name),args=[self.item1.pk]))
        self.assertResponseStatusCodeEqual(response,200)

        updated_item = dict((k,v) for (k,v) in model_to_dict(self.item1).items() if v is not None)
        updated_name = updated_item['name'] + " updated!"
        updated_item['name'] = updated_name

        updated_item.update({
            'statuses-TOTAL_FORMS': 0, 'statuses-INITIAL_FORMS': 0, # no statuses
            'superseded_by':self.item2.id
        })
        updated_item.update(self.form_defaults)

        response = self.client.post(
                reverse("admin:%s_%s_change"%(self.itemType._meta.app_label,self.itemType._meta.model_name),args=[self.item1.pk]),
                updated_item
                )

        # Make sure it saves
        self.assertRedirects(response,reverse("admin:%s_%s_changelist"%(self.itemType._meta.app_label,self.itemType._meta.model_name)))

        self.item1 = self.itemType.objects.get(pk=self.item1.pk)
        self.assertTrue(self.item2 == self.item1.superseded_by.item)
Exemplo n.º 23
0
    def store_performance_artifact(
            self, job_ids, performance_artifact_placeholders):
        """
        Store the performance data
        """

        # Retrieve list of job signatures associated with the jobs
        job_data = self.get_job_signatures_from_ids(job_ids)

        job_ref_data_signatures = set()
        map(
            lambda job_guid: job_ref_data_signatures.add(
                job_data[job_guid]['signature']
            ),
            job_data.keys()
        )

        for perf_data in performance_artifact_placeholders:
            job_guid = perf_data["job_guid"]
            ref_data_signature = job_data[job_guid]['signature']
            # At the moment there could be multiple signatures returned
            # by this, but let's just ignore that and take the first
            # if there are multiple (since the properties we care about should
            # be the same)
            ref_data = model_to_dict(ReferenceDataSignatures.objects.filter(
                signature=ref_data_signature,
                repository=self.project)[0])

            # adapt and load data into placeholder structures
            load_perf_artifacts(self.project, ref_data, job_data, perf_data)
Exemplo n.º 24
0
def retrieve_licenses(request):
    try:
        type_ = int(request.REQUEST['public_access'])
        licenses = License.get_suitable_licenses(type_)
    except KeyError:
        licenses = License.get_suitable_licenses()
    return HttpResponse(json.dumps([model_to_dict(x) for x in licenses]))
Exemplo n.º 25
0
def clicks_chart(request, pk):
    # TODO: Add a stats page for each link where you can see the traffic for that link for the last 30 days in a line chart.
    # FIXME: Add error checking if 0 clicks
    thirty_days_ago = timezone.now() - timedelta(days=30)
    clicks = Click.objects.filter(bookmark_id=pk).filter(
        timestamp__gte=thirty_days_ago)  # .annotate(count_recent=Count('click'))
    df = pd.DataFrame(model_to_dict(click) for click in clicks)
    df['count'] = 1
    df.index = df['timestamp']
    counts = df['count']
    counts = counts.sort_index()
    series = pd.expanding_count(counts).resample('D', how=np.max,
                                                 fill_method='pad')
    response = HttpResponse(content_type='image/png')

    fig = plt.figure()
    # ax = fig.add_subplot(111)
    # ax.plot(series)
    series.plot()
    plt.title("Total clicks over past 30 days")
    plt.xlabel("")
    plt.xlim(thirty_days_ago, timezone.now())
    canvas = FigureCanvas(fig)
    # ax = fig.add_subplot(1, 1, 1, axisbg='red')
    # ax.plot(series)
    canvas.print_png(response)
    return response
Exemplo n.º 26
0
    def post(self, request, format=None):
        print "movie post method"
       
        movie_data = MoviesData()
        movie_data.name = request.POST.get('name')
        movie_data.ssdb_score = int(request.POST.get('ssdb_score'))
        movie_data.popularity = int(request.POST.get('popularity'))
        movie_data.director = request.POST.get('director')
        movie_data.description = request.POST.get('description')
        movie_data.stars = request.POST.get('stars')
        movie_data.save()


        for genre_id in request.POST.getlist('genre[]'):
            movie_data.genre.add(int(genre_id))    
       
        dict_data = model_to_dict(movie_data)
        print "previous data",request.data
        print "dict data",dict_data
        # import pdb
        # pdb.set_trace()
        serializer = MoviesDataSerializer(data=dict_data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 27
0
def unread_messages(request):
    if not request.user.is_authenticated():
        data = {
            'unread_count':0,
            'unread_list':[]
        }
        return JsonResponse(data)

    unread_list = []
    messages = Message.objects.filter(recipient=request.user,read=False,deleted=False).order_by('date').reverse()
    for n in messages:
        struct = model_to_dict(n)
        if n.sender:
            struct['sender'] = str(n.sender)
        if n.recipient:
            struct['recipient'] = str(n.recipient)
        if n.date:
            struct['date'] = defaultfilters.timesince(n.date)
        if n.message:
            struct['message'] = str(n.message)
        struct['link'] = n.url()

        unread_list.append(struct)
    data = {
        'unread_count': messages.count(),
        'unread_list': unread_list
    }
    return JsonResponse(data)
Exemplo n.º 28
0
    def test_editor_change_item(self):
        self.login_editor()
        response = self.client.get(reverse("admin:%s_%s_change"%(self.itemType._meta.app_label,self.itemType._meta.model_name),args=[self.item1.pk]))
        self.assertResponseStatusCodeEqual(response,200)

        updated_item = dict((k,v) for (k,v) in model_to_dict(self.item1).items() if v is not None)
        updated_name = updated_item['name'] + " updated!"
        updated_item['name'] = updated_name

        updated_item.update({
            'statuses-TOTAL_FORMS': 0, 'statuses-INITIAL_FORMS': 0 # no statuses
        })
        updated_item.update(self.form_defaults)
        self.assertTrue(self.wg1 in self.editor.profile.editable_workgroups.all())

        self.assertEqual([self.wg1],list(response.context['adminform'].form.fields['workgroup'].queryset))

        self.assertTrue(perms.user_can_edit(self.editor,self.item1))
        self.assertTrue(self.item1.workgroup in self.editor.profile.editable_workgroups.all())
        response = self.client.post(
                reverse("admin:%s_%s_change"%(self.itemType._meta.app_label,self.itemType._meta.model_name),args=[self.item1.id]),
                updated_item
                )

        self.assertResponseStatusCodeEqual(response,302)

        self.item1 = self.itemType.objects.get(pk=self.item1.pk)
        self.assertEqual(self.item1.name,updated_name)
Exemplo n.º 29
0
def whoami(request, format='json'):
    if ServicesMetadata.objects.count() == 1:
        services_metadata = ServicesMetadata.objects.all()[0]
        _md = model_to_dict(services_metadata)
        domain = Site.objects.all()[0].domain
        _md['uri'] = 'http://%s' % domain
        _md['sk_domain_name'] = domain
        # TODO sistemare
        _md['endpoint_SOS_url'] = settings.SITEURL + 'observations/sos'
    else:
        _md = {
            'message': 'Missing metadata'
            }

    # software
    _md['software'] = {
        'ubuntu': get_ubuntu_release(),
        'java': get_java_version(),
        'tomcat': get_tomcat_version(),
        'postgresql': get_postgres_version(),
        'postgis': get_postgis_version(),
        'python': sys.version,
        'getit': geosk_version(),
        'geonode': geonode_version(),
        'pycsw': pycsw.__version__,
        'django': django_version(),
        'sos': get_sos_version()
    }

    return JsonResponse(_md)
Exemplo n.º 30
0
def get_data_api(request, format='json'):
    if request.method not in ('GET','POST'):
        return HttpResponse(status=405)

    rtype = request.REQUEST.get('rtype')
    id = request.REQUEST.get('id')

    if rtype == 'layer':
        r = Layer.objects.get(pk=id)
        exclude = LayerForm._meta.exclude
    elif rtype == 'map':
        r = Map.objects.get(pk=id)
        exclude = MapForm._meta.exclude

    exclude = exclude + ('owner', 'title', 'distribution_url', 'distribution_description')
    data = model_to_dict(r, exclude=exclude)

    #f=LayerForm(model_to_dict(l), prefix='layer')


    data['keywords'] = r.keyword_csv
    # data_prefix = {"layer-%s" % k: v for k, v in data.items()}

    results = {
        'data': data
        }
    return HttpResponse(json.dumps(results, cls=DjangoJSONEncoder), mimetype="application/json")
Exemplo n.º 31
0
 def toJSON(self):
     item = model_to_dict(self)
     item['gender'] = {'id': self.gender, 'name': self.get_gender_display()}
     item['date_birthday'] = self.date_birthday.strftime('%Y-%m-%d')
     return item
Exemplo n.º 32
0
def section(request, content_id):
    section = get_object_or_404(Section, id=content_id)
    # 阅读量+1
    section.view = section.view + 1
    section.save()
    note = Note.objects.get(id=section.note_id)
    # 上下篇笔记
    second = Catalogue.objects.get(section=section.id)
    second_min = Catalogue.objects.filter(father=second.father).aggregate(Min('order'))["order__min"]
    second_max = Catalogue.objects.filter(father=second.father).aggregate(Max('order'))["order__max"]
    first = Catalogue.objects.get(id=second.father)
    first_min = Catalogue.objects.filter(note=note).filter(level=1).aggregate(Min('order'))["order__min"]
    first_max = Catalogue.objects.filter(note=note).filter(level=1).aggregate(Max('order'))["order__max"]
    if second.order == second_min:
        if first.order == first_min:
            # 第一篇文章
            last_content = None
        else:
            # 上一篇找上一章最后一篇
            last_father = Catalogue.objects.filter(note=note).filter(level=1).filter(order=first.order - 1)
            last_second_max = Catalogue.objects.filter(father=last_father[0].id).aggregate(Max('order'))["order__max"]
            last_content = Catalogue.objects.filter(father=last_father[0].id).filter(order=last_second_max)[0]
        next_content = Catalogue.objects.filter(father=first.id).filter(order=second.order + 1)[0]
    elif second.order == second_max:
        if first.order == first_max:
            # 最后一篇文章
            next_content = None
        else:
            # 下一篇找上一章第一篇
            next_father = Catalogue.objects.filter(note=note).filter(level=1).filter(order=first.order + 1)
            next_second_min = Catalogue.objects.filter(father=next_father[0].id).aggregate(Min('order'))["order__min"]
            next_content = Catalogue.objects.filter(father=next_father[0].id).filter(order=next_second_min)[0]
        last_content = Catalogue.objects.filter(father=first.id).filter(order=second.order - 1)[0]
    else:
        last_content = Catalogue.objects.filter(father=first.id).filter(order=second.order - 1)[0]
        next_content = Catalogue.objects.filter(father=first.id).filter(order=second.order + 1)[0]
    # 笔记目录
    first_catalogue = Catalogue.objects.filter(note=note.id).filter(level=1)
    num = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八"]
    catalogue_list = []
    for i in first_catalogue:
        catalogue_dict = {}
        catalogue_dict["title"] = num[i.order] + "、\t" + i.name
        if i.id == first.id:
            catalogue_dict["spread"] = 'true'
        children_list = []
        catalogue_dict["children"] = children_list
        second_catalogue = Catalogue.objects.filter(note=note.id).filter(father=i.id)
        for j in second_catalogue:
            children_dict = {}
            children_dict["id"] = str(j.section.id)
            children_dict["title"] = str(j.order) + ".\t" + j.section.title
            children_dict["href"] = '/blog/section-' + str(j.section.id)
            children_list.append(children_dict)
        catalogue_list.append(catalogue_dict)
    # 用户已登录
    article_like = '0'
    if request.user.id:
        # 添加阅读记录(第一次:添加,已有记录:更新时间)
        history = SectionViewHistory.objects.filter(section_id=section.id).filter(user_id=request.user)
        if history:
            change_history = history[0]
            change_history.time = timezone.now()
            change_history.save()
        else:
            new_history = SectionViewHistory()
            new_history.section = section
            new_history.note = section.note
            new_history.user = request.user
            new_history.save()
        # 判断是否已收藏文章
        user_list = SectionViewHistory.objects.filter(section_id=section.id)
        for i in user_list:
            if request.user == i.user and i.is_like == 1:
                article_like = 1
                break
        # 评论列表
        # 全部评论
        content_count = SectionMessage.objects.filter(section=section).count()
        all_comment = []
        for info in SectionMessage.objects.filter(section=section):
            # 根评论
            if info.reply_id is None:
                # 单条记录
                record = []
                info_dict = model_to_dict(info)
                info_dict['username'] = SectionMessage.objects.get(id=info.id).user.username
                info_dict['reply_id'] = 'None'
                info_dict['root_id'] = 'None'
                info_dict['reply_name'] = 'None'
                info_dict['photo'] = SectionMessage.objects.get(id=info.id).user.userinfo.photo.name
                info_dict['web'] = SectionMessage.objects.get(id=info.id).user.userinfo.web
                info_dict['time'] = SectionMessage.objects.get(id=info.id).time.strftime("%Y-%m-%d %H:%M:%S")
                record.append(info_dict)
                # 根据根留言查找子回复
                record = note_record(section, info.id, record)
                all_comment.append(record)
        # 热门评论
        hot_comment = SectionMessage.objects.filter(section=section).filter(level=0).order_by('-like')
        # 我的评论
        user_id = request.user.id
        if user_id:
            my_comment = SectionMessage.objects.filter(section=section).filter(level=0).filter(user_id=user_id)
        else:
            my_comment = None
    # 评论统计
    comment_count = SectionMessage.objects.filter(section=section).count()
    return render(request, 'blog/section.html', locals())
Exemplo n.º 33
0
 def toJSON(self):
     item = model_to_dict(self, exclude=['sale'])
     item['prod'] = self.prod.toJSON()
     item['price'] = format(self.price, '.2f')
     item['subtotal'] = format(self.subtotal, '.2f')
     return item
Exemplo n.º 34
0
 def _convert_to_valid_search_dict(self, contact):
     d = model_to_dict(contact)
     del d['phone']
     del d['organisation']
     return d
Exemplo n.º 35
0
def queryLists(requests,queryID):
	try:
		query = model_to_dict(Query.objects.get(id=queryID))
	except:
		query = {}
	return JsonResponse(query)
def test_post_job_artifacts_by_add_artifact(
    test_repository,
    failure_classifications,
    result_set_stored,
    monkeypatch,
    mock_post_json,
):
    """
    test submitting a job with artifacts added by ``add_artifact``

    This has pre-parsed logs.  Verify parse_status of "parsed" and that it
    doesn't parse the logs.

    Submitted ``text_log_artifact`` should still trigger generation of the
    bug suggestions.
    """

    mock_parse = MagicMock(name="parse_line")
    monkeypatch.setattr(StepParser, 'parse_line', mock_parse)

    job_guid = 'd22c74d4aa6d2a1dcba96d95dccbd5fdca70cf33'
    tjc = client.TreeherderJobCollection()
    tj = client.TreeherderJob({
        'project': test_repository.name,
        'revision': result_set_stored[0]['revision'],
        "job": {
            "artifacts": [],
            "job_guid":
            job_guid,
            "log_references": [{
                "name":
                "autophone-nexus-one-1.log",
                "parse_status":
                "parsed",
                "url":
                "https://autophone-dev.s3.amazonaws.com/pub/mozilla.org/mobile/tinderbox-builds/mozilla-inbound-android-api-9/1432676531/en-US/autophone-autophone-s1s2-s1s2-nytimes-local.ini-1-nexus-one-1.log"
            }],
            "state":
            "completed",
        },
    })

    tls_blob = json.dumps({
        "logurl":
        "https://autophone-dev.s3.amazonaws.com/pub/mozilla.org/mobile/tinderbox-builds/mozilla-inbound-android-api-9/1432676531/en-US/autophone-autophone-s1s2-s1s2-nytimes-local.ini-1-nexus-one-1.log",
        "step_data": {
            "steps": [{
                "name":
                "foobar",
                "result":
                "testfailed",
                "started_linenumber":
                1,
                "finished_linenumber":
                100000,
                "started":
                "2016-07-13 16:09:31",
                "finished":
                "2016-07-13 16:09:31",
                "errors": [{
                    "line":
                    "TEST_UNEXPECTED_FAIL | /sdcard/tests/autophone/s1s2test/nytimes.com/index.html | Failed to get uncached measurement.",
                    "linenumber": 64435
                }]
            }]
        }
    })

    ji_blob = json.dumps(
        {"job_details": [{
            "title": "mytitle",
            "value": "myvalue"
        }]})
    bapi_blob = json.dumps({"buildername": "merd"})
    pb_blob = json.dumps({
        "build_url": "feh",
        "chunk": 1,
        "config_file": "mah"
    })

    tj.add_artifact("text_log_summary", "json", tls_blob)
    tj.add_artifact("Job Info", "json", ji_blob)
    tj.add_artifact("buildapi", "json", bapi_blob)
    tj.add_artifact("privatebuild", "json", pb_blob)

    tjc.add(tj)

    post_collection(test_repository.name, tjc)

    assert JobDetail.objects.count() == 1
    assert model_to_dict(JobDetail.objects.get(job__guid=job_guid)) == {
        'id': 1,
        'job': 1,
        'title': 'mytitle',
        'value': 'myvalue',
        'url': None
    }

    assert TextLogStep.objects.count() == 1
    assert model_to_dict(TextLogStep.objects.get(job__guid=job_guid)) == {
        'id': 1,
        'job': 1,
        'started': datetime.datetime(2016, 7, 13, 16, 9, 31),
        'finished': datetime.datetime(2016, 7, 13, 16, 9, 31),
        'name': 'foobar',
        'result': 1,
        'started_line_number': 1,
        'finished_line_number': 100000
    }

    assert TextLogError.objects.count() == 1
    text_log_error = TextLogError.objects.get(step__job__guid=job_guid)
    assert model_to_dict(text_log_error) == {
        'id': 1,
        'line':
        'TEST_UNEXPECTED_FAIL | /sdcard/tests/autophone/s1s2test/nytimes.com/index.html | Failed to get uncached measurement.',
        'line_number': 64435,
        'step': 1,
    }

    # assert that some bug suggestions got generated
    assert len(get_error_summary(Job.objects.get(guid=job_guid))) == 1

    check_job_log(test_repository, job_guid, JobLog.PARSED)

    # ensure the parsing didn't happen
    assert mock_parse.called is False
Exemplo n.º 37
0
 def get(self, request):
     produtos = Produto.objects.all()
     lista_produtos = []
     for p in produtos:
         lista_produtos.append(model_to_dict(p))
     return JsonResponse(lista_produtos, safe=False)
Exemplo n.º 38
0
def api(request):
    produtos = Produto.objects.all()
    lista_produtos = []
    for p in produtos:
        lista_produtos.append(model_to_dict(p))
    return JsonResponse(lista_produtos, safe=False, status=200)
Exemplo n.º 39
0
    def handle(self, request, data):
        system = data['system']

        question_id = request.GET.get('question_id', None)
        answer_id = request.GET.get('answer_id', None)
        action = request.GET.get('action', 'questions')

        question = None
        if question_id is not None and question_id != 'new':
            question = get_object_or_404(Question, pk=question_id)
            data['question'] = question

        if action == 'question':
            kwargs = {'params': system.parameter_set}

            if question is not None:
                kwargs['initial'] = model_to_dict(question)

            if request.method == 'POST':
                form = QuestionForm(request.POST, request.FILES, **kwargs)
                form.set_system(system)
                form.set_question(question)

                if form.is_valid():
                    question = form.save()
                    return HttpResponseRedirect(
                        reverse('office_system',
                                kwargs={
                                    'sid': system.id,
                                    'section': 'questions'
                                }))
            else:
                form = QuestionForm(**kwargs)
                form.set_system(system)
                form.set_question(question)

            data['form'] = form

            return render(request, 'office/systems/single/questions_form.html',
                          data)
        elif action == 'delete':
            if question is None:
                raise Http404

            if answer_id is not None:
                answer = get_object_or_404(Answer, pk=answer_id)
                answer.delete()
                return HttpResponse()
            else:
                question.delete()
                return HttpResponse()
        elif action == 'answers':
            if question is None:
                raise Http404

            answers = question.answer_set.all()
            data['answers'] = answers

            return render(request, 'office/systems/single/answers.html', data)
        elif action == 'answer':
            if question is None:
                raise Http404

            kwargs = {'question': question}

            answer = None
            if answer_id is not None and answer_id != 'new':
                answer = get_object_or_404(Answer, pk=answer_id)
                kwargs['initial'] = model_to_dict(answer)

            if request.method == 'POST':
                form = AnswerForm(request.POST, request.FILES, **kwargs)
                form.set_answer(answer)

                if form.is_valid():
                    answer = form.save()
                    return HttpResponseRedirect(
                        reverse('office_system',
                                kwargs={
                                    'sid': system.id,
                                    'section': 'questions'
                                }) + ('?question_id=%s&action=%s' %
                                      (question.id, 'answers')))
            else:
                form = AnswerForm(**kwargs)
                form.set_answer(answer)

            data['form'] = form

            return render(request, 'office/systems/single/answers_form.html',
                          data)

        else:
            questions = system.question_set.all()
            data['questions'] = questions
            return render(request, 'office/systems/single/questions.html',
                          data)
Exemplo n.º 40
0
def withdraw(request):
    amount = request.DATA.get("amount", "").strip()
    card_id = request.DATA.get("card_id", "").strip()
    vcode = request.DATA.get("validate_code", "").strip()
    if not amount or not card_id:
        return {"ret_code": 20061, "message": u"信息输入不完整"}

    user = request.user
    if not user.wanglibaouserprofile.id_is_valid:
        return {"ret_code": 20062, "message": u"请先进行实名认证"}

    if user.wanglibaouserprofile.frozen:
        return {"ret_code": 20072, "message": u"用户账户已冻结,请联系客服"}

    try:
        float(amount)
    except:
        return {"ret_code": 20063, 'message': u'金额格式错误'}
    amount = util.fmt_two_amount(amount)
    if len(str(amount)) > 20:
        return {"ret_code": 20064, 'message': u'金额格式错误,大于100元且为100倍数'}

    margin = user.margin.margin
    if amount > margin:
        return {"ret_code": 20065, 'message': u'余额不足'}

    phone = user.wanglibaouserprofile.phone
    status, message = validate_validation_code(phone, vcode)
    if status != 200:
        # Modify by hb on 2015-12-02
        #return {"ret_code": 20066, "message": u"验证码输入错误"}
        return {"ret_code": 20066, "message": message}

    card = Card.objects.filter(pk=card_id).first()
    if not card or card.user != user:
        return {"ret_code": 20067, "message": u"请选择有效的银行卡"}
    # 检测银行卡是否在黑名单中
    black_list = BlackListCard.objects.filter(card_no=card.no).first()
    if black_list and black_list.user != user:
        return {"ret_code": 20072, "message": u'银行卡号异常,请联系客服'}

    # 检查白名单
    white_list = WhiteListCard.objects.filter(user=user,
                                              card_no=card.no).first()
    if not white_list:
        # 增加银行卡号检测功能,检测多张卡
        card_count = Card.objects.filter(no=card.no).count()
        if card_count > 1:
            return {"ret_code": 20073, "message": u'银行卡号有多张重复,请联系客服'}

        # 检测银行卡在以前的提现记录中是否为同一个用户
        payinfo_record = PayInfo.objects.filter(
            card_no=card.no, type='W').order_by('-create_time').first()
        if payinfo_record:
            if payinfo_record.user != user:
                return {"ret_code": 20074, "message": u'银行卡号与身份信息不符,请联系客服'}

    # 计算提现费用 手续费 + 资金管理费
    bank = card.bank
    uninvested = user.margin.uninvested  # 充值未投资金额

    # 获取费率配置
    fee_misc = WithdrawFee()
    fee_config = fee_misc.get_withdraw_fee_config()

    # 检测提现最大最小金额
    if amount > fee_config.get('max_amount') or amount <= 0:
        return {"ret_code": 20068, 'message': u'提现金额超出最大提现限额'}
    if amount < fee_config.get('min_amount'):
        if amount != margin:
            return {
                "ret_code": 20069,
                'message':
                u'账户余额小于{}时需要一次性提完'.format(fee_config.get('min_amount'))
            }

    # 检测银行的单笔最大提现限额,如民生银行
    if bank and bank.withdraw_limit:
        bank_limit = util.handle_withdraw_limit(bank.withdraw_limit)
        bank_max_amount = bank_limit.get('bank_max_amount', 0)

        if bank_max_amount:
            if amount > bank_max_amount:
                return {"ret_code": 20070, 'message': u'提现金额超出银行最大提现限额'}

    # 获取计算后的费率
    fee, management_fee, management_amount = fee_misc.get_withdraw_fee(
        user, amount, margin, uninvested)

    # 实际提现金额
    actual_amount = amount - fee - management_fee
    if actual_amount <= 0:
        return {"ret_code": 20071, "message": u'实际到账金额为0,无法提现'}

    pay_info = PayInfo()
    pay_info.amount = actual_amount
    pay_info.fee = fee
    pay_info.management_fee = management_fee
    pay_info.management_amount = management_amount
    pay_info.total_amount = amount
    pay_info.type = PayInfo.WITHDRAW
    pay_info.user = user
    pay_info.card_no = card.no
    pay_info.account_name = user.wanglibaouserprofile.name
    pay_info.bank = card.bank
    pay_info.request_ip = util.get_client_ip(request)
    pay_info.status = PayInfo.ACCEPTED
    pay_info.channel = "app"

    try:
        order = OrderHelper.place_order(user,
                                        Order.WITHDRAW_ORDER,
                                        pay_info.status,
                                        pay_info=model_to_dict(pay_info))
        pay_info.order = order
        keeper = MarginKeeper(user, pay_info.order.pk)
        margin_record = keeper.withdraw_pre_freeze(
            amount, uninvested=management_amount)
        pay_info.margin_record = margin_record

        pay_info.save()
        return {
            "ret_code": 0,
            'message': u'提现成功',
            "amount": amount,
            "phone": phone,
            "bank_name": bank.name,
            "order_id": order.id
        }
    except Exception, e:
        pay_info.error_message = str(e)
        pay_info.status = PayInfo.FAIL
        pay_info.save()
        return {"ret_code": 20065, 'message': u'余额不足'}
Exemplo n.º 41
0
 def toJSON(self):  # Retorna JSON
     item = model_to_dict(self)
     return item
Exemplo n.º 42
0
 def to_dict(self):
     model_dict = model_to_dict(self)
     model_dict['votes'] = self.votes
     model_dict['slug'] = self.slug
     return model_dict
Exemplo n.º 43
0
def test(request):
    articleModel = ArticleModel.objects.all().first()
    articleDict = model_to_dict(articleModel)
    print articleDict
    return HttpResponse(articleDict)
Exemplo n.º 44
0
 def get(self, request, *args, **kwargs):
     defs = {}
     for d in Definition.objects.all():
         defs[d.get_dict_key()] = model_to_dict(d)
         
     return HttpResponse(simplejson.dumps(defs), content_type='application/json')
Exemplo n.º 45
0
def generateDocXReport(month_id, year, lang, film_id):
    langMap = dict(fr={
        'template': 'template-fr.docx',
        'locale': 'fr_FR',
        'emptyList': 'Pas Encore.'
    },
                   en={
                       'template': 'template-en.docx',
                       'locale': 'en_US',
                       'emptyList': 'Not yet.'
                   })

    locale.setlocale(locale.LC_TIME, langMap.get(lang).get('locale'))

    file_path = os.path.join(MEDIA_ROOT, 'reportTemplate/')
    currentFilm = Film.objects.get(id=film_id)
    subList = Submission.objects.filter(dateSubmission__year=year).filter(
        dateSubmission__month=month_id).filter(film_id=film_id)

    selectList = Submission.objects.filter(responseDate__year=year).filter(
        responseDate__month=month_id).filter(film_id=film_id).filter(
            response__iexact='SELECTIONED')
    rejectList = Submission.objects.filter(responseDate__year=year).filter(
        responseDate__month=month_id).filter(film_id=film_id).filter(
            response__iexact='REFUSED')

    subOutput, selectOutput, rejectOutput = [], [], []

    for item in subList:
        subOutput.append({'festival': model_to_dict(item.festival)})
    if not subOutput:
        subOutput.append({'festival': {'name': langMap[lang]['emptyList']}})

    for item in selectList:
        selectOutput.append({'festival': model_to_dict(item.festival)})
    if not subOutput:
        selectOutput.append({'festival': {'name': langMap[lang]['emptyList']}})

    for item in rejectList:
        rejectOutput.append({'festival': model_to_dict(item.festival)})
    if not subOutput:
        rejectOutput.append({'festival': {'name': langMap[lang]['emptyList']}})

    document = DocxTemplate(file_path + langMap[lang]['template'])

    dic = {
        'INSCRIPTIONS_LIST':
        subOutput,
        'MOVIE_NAME':
        currentFilm.name.upper(),
        'CURRENT_DATE':
        format_datetime(date.today(),
                        format='dd MMMM YYYY',
                        locale=langMap[lang]['locale']),
        'TARGET_MONTH':
        format_datetime(datetime.datetime(1900, int(month_id), 1),
                        format='MMMM',
                        locale=langMap[lang]['locale']),
        'TARGET_YEAR':
        str(year),
        'SELECTIONS_LIST':
        selectOutput,
        'REJECTIONS_LIST':
        rejectOutput,
        'PROJECTIONS_LIST':
        langMap[lang]['emptyList']
    }
    document.render(dic)

    document.core_properties.title = currentFilm.name + "-" + lang
    return document
Exemplo n.º 46
0
 def toJSON(self):
     item = model_to_dict(self)
     item['cate'] = self.cate.toJSON()
     item['pvp'] = format(self.pvp, '.2f')
     return item
 def toJson(self):
     item = model_to_dict(self)
     return item
Exemplo n.º 48
0
def get_section_dict(section):
    """ Returns a dictionary of a section including indicator of whether that section is filled """
    section_data = model_to_dict(section)
    section_data['is_section_filled'] = section.is_full()
    return section_data
Exemplo n.º 49
0
 def toJSON(self):
     item = model_to_dict(self)
     return item
Exemplo n.º 50
0
def show(request, article_id):
    article = get_object_or_404(Article, id=article_id)
    # 阅读量+1
    article.view = article.view + 1
    article.save()
    article_like = 0
    # 用户已登录
    if request.user.id:
        # 添加阅读记录(第一次:添加,已有记录:更新时间)
        history = ArticleViewHistory.objects.filter(article_id=article_id).filter(user_id=request.user)
        if history:
            change_history = history[0]
            change_history.time = timezone.now()
            change_history.save()
        else:
            new_history = ArticleViewHistory()
            new_history.article = article
            new_history.category = article.category
            new_history.user = request.user
            new_history.save()
        # 判断是否已收藏文章
        user_list = ArticleViewHistory.objects.filter(article_id=article_id)
        for i in user_list:
            if request.user == i.user and i.is_like == 1:
                article_like = 1
                break
    # 下一篇,找出id大于当前文章id的文章,升序排序后取第一个,即为下一篇
    next_article = Article.objects.filter(id__gt=article_id).filter(is_release=True).order_by("id")[:1]
    if len(next_article) == 0:
        next_article = 0
    else:
        for next in next_article:
            next_article = next
    # 上一篇,找出id小于当前文章id的文章,降序排序后取第一个,即为上一篇
    last_article = Article.objects.filter(id__lt=article_id).filter(is_release=True).order_by("-id")[:1]
    if len(last_article) == 0:
        last_article = 0
    else:
        for last in last_article:
            last_article = last
    # 评论列表
    # 全部评论
    all_comment = []
    for info in CommentMessage.objects.filter(article=article):
        # 根评论
        if info.reply_id is None:
            # 单条记录
            record = []
            info_dict = model_to_dict(info)
            info_dict['username'] = CommentMessage.objects.get(id=info.id).user.username
            info_dict['reply_id'] = 'None'
            info_dict['root_id'] = 'None'
            info_dict['reply_name'] = 'None'
            info_dict['photo'] = CommentMessage.objects.get(id=info.id).user.userinfo.photo.name
            info_dict['web'] = CommentMessage.objects.get(id=info.id).user.userinfo.web
            info_dict['time'] = CommentMessage.objects.get(id=info.id).time.strftime("%Y-%m-%d %H:%M:%S")
            record.append(info_dict)
            # 根据根留言查找子回复
            record = comment_record(article, info.id, record)
            all_comment.append(record)
    # 热门评论
    hot_comment = CommentMessage.objects.filter(article=article).filter(level=0).order_by('-like')
    # 我的评论
    user_id = request.user.id
    if user_id:
        my_comment = CommentMessage.objects.filter(article=article).filter(level=0).filter(user_id=user_id)
    else:
        my_comment = None
    # 评论统计
    count = CommentMessage.objects.filter(article=article).count()
    # 猜你喜欢
    guess1 = Article.objects.filter(is_release=True).filter(tags=article.tags.all()[0]).order_by('?')[:2]
    guess2 = Article.objects.filter(is_release=True).filter(tags=article.tags.all()[1]).order_by('?')[:2]
    return render(request, 'blog/show.html',
                  {"article": article, "articke_like": article_like, "next_article": next_article,
                   "last_article": last_article, "all_comment": all_comment, "hot_comment": hot_comment,
                   "my_comment": my_comment, "count": count, "aside_dict": aside(), "guess1": guess1, "guess2": guess2})
Exemplo n.º 51
0
 def to_dict(self):
     data = model_to_dict(self)
     data.pop('id')
     return data
Exemplo n.º 52
0
 def delete_form_valid(self, object):
     success_message = self.get_success_message(model_to_dict(object))
     if success_message:
         messages.success(self.request, success_message)
Exemplo n.º 53
0
 def get_item_comment_by_id(cls, comment_id):
     try:
         model_obj = cls.objects.get(pk=comment_id)
         return model_to_dict(model_obj)
     except cls.DoesNotExist:
         return None
Exemplo n.º 54
0
Arquivo: file.py Projeto: yeguoku/s25
def file(request, project_id):
    """ 文件列表 & 添加文件夹 """

    parent_object = None
    folder_id = request.GET.get('folder', "")
    if folder_id.isdecimal():
        parent_object = models.FileRepository.objects.filter(
            id=int(folder_id), file_type=2,
            project=request.tracer.project).first()

    # GET 查看页面
    if request.method == "GET":

        breadcrumb_list = []
        parent = parent_object
        while parent:
            # breadcrumb_list.insert(0, {'id': parent.id, 'name': parent.name})
            breadcrumb_list.insert(0, model_to_dict(parent, ['id', 'name']))
            parent = parent.parent

        # 当前目录下所有的文件 & 文件夹获取到即可
        queryset = models.FileRepository.objects.filter(
            project=request.tracer.project)
        if parent_object:
            # 进入了某目录
            file_object_list = queryset.filter(
                parent=parent_object).order_by('-file_type')
        else:
            # 根目录
            file_object_list = queryset.filter(
                parent__isnull=True).order_by('-file_type')
        form = FolderModelForm(request, parent_object)

        context = {
            'form': form,
            "file_object_list": file_object_list,
            "breadcrumb_list": breadcrumb_list,
            'folder_object': parent_object
        }
        return render(request, 'file.html', context)

    # POST 添加文件夹 & 文件夹的修改
    fid = request.POST.get('fid', '')
    edit_object = None
    if fid.isdecimal():
        edit_object = models.FileRepository.objects.filter(
            id=int(fid), file_type=2, project=request.tracer.project).first()

    if edit_object:
        form = FolderModelForm(request,
                               parent_object,
                               data=request.POST,
                               instance=edit_object)
    else:
        form = FolderModelForm(request, parent_object, data=request.POST)

    if form.is_valid():
        form.instance.project = request.tracer.project
        form.instance.file_type = 2
        form.instance.update_user = request.tracer.user
        form.instance.parent = parent_object
        form.save()
        return JsonResponse({'status': True})

    return JsonResponse({'status': False, 'error': form.errors})
Exemplo n.º 55
0
    def default(self, o):

        if isinstance(o, Model):
            return model_to_dict(o)

        return super().default(o)
Exemplo n.º 56
0
def query(request, document_id):
    docJson = model_to_dict(Document.objects.get(pk=document_id))
    return JsonResponse(docJson, safe=False)
Exemplo n.º 57
0
 def get(self, request, *args, **kwargs):
     # print(request.GET)
     try:
         fields_name = [i.name for i in Movie._meta.get_fields()]
         queryset = None
         if kwargs.get('pk'):
             # queryset = Movie.objects.filter(id=kwargs.get('pk')).values()
             queryset = Movie.objects.filter(
                 id=kwargs.get('pk')).prefetch_related()
             print(queryset)
             main_json = list()
             for i in queryset:
                 data = model_to_dict(i)
                 data['genres_movie'] = list()
                 for d in i.genres_movie.values('name'):
                     data['genres_movie'].append(d.get('name'))
                 main_json.append(data)
             print(main_json)
         elif request.GET.get('search_field') == 'year':
             if len(request.GET.get('search_term')) > 4:
                 query_args = {
                     'released_year__range':
                     request.GET.get('search_term').split('-')
                 }
             else:
                 query_args = {
                     'released_year': request.GET.get('search_term')
                 }
             print(query_args)
             # queryset = Movie.objects.filter(**query_args).values()
             queryset = Movie.objects.filter(
                 **query_args).prefetch_related()
             print(queryset)
             main_json = list()
             for i in queryset:
                 data = model_to_dict(i)
                 data['genres_movie'] = list()
                 for d in i.genres_movie.values('name'):
                     data['genres_movie'].append(d.get('name'))
                 main_json.append(data)
             print(main_json)
         elif request.GET.get('search_field') == 'rating':
             if request.GET.get('condition') == 'higher':
                 query_args = {
                     '{0}__gte'.format(request.GET.get('search_field')):
                     request.GET.get('search_term')
                 }
             else:
                 query_args = {
                     '{0}__lte'.format(request.GET.get('search_field')):
                     request.GET.get('search_term')
                 }
             queryset = Movie.objects.filter(
                 **query_args).prefetch_related()
             print(queryset)
             main_json = list()
             for i in queryset:
                 data = model_to_dict(i)
                 data['genres_movie'] = list()
                 for d in i.genres_movie.values('name'):
                     data['genres_movie'].append(d.get('name'))
                 main_json.append(data)
             print(main_json)
         elif request.GET.get('search_field') in fields_name:
             query_args = {
                 '{0}__icontains'.format(request.GET.get('search_field')):
                 request.GET.get('search_term')
             }
             # queryset = Movie.objects.filter(**query_args).values()
             queryset = Movie.objects.filter(
                 **query_args).prefetch_related()
             print(queryset)
             main_json = list()
             for i in queryset:
                 data = model_to_dict(i)
                 data['genres_movie'] = list()
                 for d in i.genres_movie.values('name'):
                     data['genres_movie'].append(d.get('name'))
                 main_json.append(data)
             # print(main_json)
         elif request.GET.get('search_field') == 'genres':
             query_args = {
                 'name__icontains': request.GET.get('search_term')
             }
             queryset = Genres.objects.filter(**query_args).select_related()
             # print(queryset)
             main_json = list()
             for i in queryset:
                 data = model_to_dict(i.movie)
                 main_json.append(data)
             response = {'message': main_json}
             return JsonResponse(response, status=200)
         else:
             response = {'message': 'Field name not matched.'}
             return JsonResponse(response, status=200)
         # print(queryset)
         if queryset:
             response = {'message': main_json}
             return JsonResponse(response, status=200)
         else:
             response = {'message': 'Not found'}
             return JsonResponse(response, status=206)
     except Exception as e:
         print(e)
         response = {'message': 'Internal server error'}
         return JsonResponse(response, status=500)
Exemplo n.º 58
0
    def handle(self, request, data):
        system = data['system']

        object_id = request.GET.get('object_id', None)
        if object_id is not None:
            if request.method == 'POST':
                if request.GET.get('action', None) == 'delete':
                    obj = get_object_or_404(Object, pk=object_id)
                    obj.delete()
                    return HttpResponse()
                form = ObjectForm(request.POST, request.FILES)
            elif object_id == 'new':
                form = ObjectForm()
            else:
                obj = get_object_or_404(Object, pk=object_id)
                form = ObjectForm(initial=model_to_dict(obj))

            object_attrs = []
            if object_id != 'new':
                obj = get_object_or_404(Object, pk=object_id)
                form.set_object(obj)
                object_attrs = list(obj.objectattributevalue_set.all())

            form.set_system(system)
            data['form'] = form

            attrs = system.attribute_set.prefetch_related(
                'attributeallowedvalue_set').all()

            attrs_data = []
            for attr in attrs:
                active = None
                for oav in object_attrs:
                    if oav.attribute_id == attr.id:
                        active = oav.attribute_value_id
                        break

                allowed = [{
                    'val': val,
                    'active': val.id == active
                } for val in attr.attributeallowedvalue_set.all()]
                attrs_data.append({
                    'attr': attr,
                    'allowed_vals': allowed,
                })

            data['attrs'] = attrs_data

            # print(attrs_data)

            if request.method == 'POST':
                if form.is_valid():
                    object = form.save()
                    return HttpResponseRedirect(
                        reverse('office_system',
                                kwargs={
                                    'sid': system.id,
                                    'section': 'objects'
                                }))

            return render(request, 'office/systems/single/objects_form.html',
                          data)

        else:
            objects = system.object_set.all()
            data['objects'] = objects
            return render(request, 'office/systems/single/objects.html', data)
Exemplo n.º 59
0
 def get_inline_address(self):
     return '{cus_uid}-{receiver_name}-{receiver_mobile}-{receiver_state},{receiver_city},{receiver_district},{receiver_address}'.format(
         **model_to_dict(self)
     )
Exemplo n.º 60
0
 def toJSON(self):
     item = model_to_dict(self)
     item['cat'] = self.cat.toJSON()
     item['image'] = self.get_image()
     item['pvp'] = format(self.pvp, '.2f')
     return item