Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Running tensorflow application using django with wsgi
I deployed my application which runs with Tesorflow object detection API on Ubuntu 16.04LTS. It is a web application running on django and i want to serve it with apache and wsgi. When i access the apache server through my server's IP address i get the following error: ImportError at / Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 41, in from tensorflow.python.pywrap_tensorflow_internal import * File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in _pywrap_tensorflow_internal = swig_import_helper() File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) ImportError: /usr/local/lib/python3.5/dist-packages/tensorflow/python/_pywrap_tensorflow_internal.so: undefined symbol: PyBytes_AsStringAndSize Failed to load the native TensorFlow runtime. -
Truncated text in django template filter with an href link
I want to truncate my post content using a Django template tag filter such as (|truncatewords_html: my_number) But with an href link for the dots that redirect the user to the detailed post url. I know I can build a custom template tag to perform this functionality. But I just wanted to check (since I did not found any) if there is a built-in method to do what I want. -
Why is the Django decimal max_digits validation failing with strange behaviour?
I have a model field full_time_equivalent: full_time_equivalent = models.DecimalField( max_digits=5, decimal_places=2, default=100, validators=[ MinValueValidator(Decimal(0)), MaxValueValidator(Decimal(100)) ] ) To ensure that the validators fire I have override save with: def save(self, *args, **kwargs): # Run validations self.full_clean() return super().save(*args, **kwargs) With the following test: project2_membership = ProjectMembership( user=self.new_user, project=project2, is_project_manager=False, full_time_equivalent=10.01 ) When I step into the validation the following value is shown and respective error: Decimal('10.0099999999999997868371792719699442386627197265625') django.core.exceptions.ValidationError: {'full_time_equivalent': ['Ensure that there are no more than 5 digits in total.'] What am I doing wrong? -
How to get field[] in django?
I'm trying to use array field in django to dynamically add fields using javascript like user clicks on button and a new field appear However I cannot figure out how to make django to render field as "field[]" name, neither I can't get that field value in django view. I was thinking in FormSets but it doesn't seems to be what I need -
DJANGO how to send one of the model parameters instead of it's url to .json
I am a Django beginner and I believe this is a rather simple question, still, i couldn't find anything on it. Thanks in advance! I am trying to get the parameter "nome" from the "Especie" model to appear on the .json file: My models.py: from django.db import models class Zona(models.Model): codigo = models.CharField(max_length=120) especies = models.ForeignKey('Especie') def __str__(self): return self.codigo class Especie(models.Model): nome = models.CharField(max_length=120) zonas = models.ForeignKey(Zona) def __str__(self): return self.nome My serialisers.py(using django rest framework): class EspecieSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Especie fields = ('nome', 'nome_latino', 'zonas', 'id') class ZonaSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Zona fields = ('codigo', 'area', 'especies', 'id') views.py: from django.shortcuts import render from species.models import Especie, Zona from rest_framework import viewsets from rest.serializers import ZonaSerializer, EspecieSerializer class EspecieViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = Especie.objects.all().order_by('-data_insercao') serializer_class = EspecieSerializer class ZonaViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = Zona.objects.all() serializer_class = ZonaSerializer Instead im getting the URL to the "especie" in question, as you can see here: "codigo": "A1", "area": "Alvalade", "especies": "http://127.0.0.1:8000/especies/1/", "id": 1 thank you! -
Django sqlite3 timeout has no effect
I have a simple integration test in Django that spawns a single Celery worker to run a job, which writes a record to the database. The Django thread also writes a record to the database. Because its a test, I use the in-memory sqlite database. There are no transactions being used. I often get this error: django.db.utils.OperationalError: database table is locked which according to the Django docs is due to one connection timing out while waiting for another to finish. It's "more concurrency than sqlite can handle in default configuration". This seems strange given that it's two records in two threads. Nevertheless, the same docs say to increase the timeout option to force connections to wait longer. Ok, I change my database settings to this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'OPTIONS': {'timeout': 10000000}, } } This has no effect. The error still appears and it clearly has not waited 1e7 seconds or 1e7 milliseconds or 1e7 microseconds before doing so. Is there an additional setting I'm missing? This is in Python 3.5 and I tried both Django 1.11 and Django 2.0. -
django haystack elasticsearch wont give correct result
I have a problem with django-haystack elasticsearch. I have a search for question where one field is study_level which is an int of 1 to 13. When I try to make a search to include question within a range like 10-12 it also gives questions with other study_level. It seems like study_level don't matter in the search. I have this index class QuestionIndex(indexes.SearchIndex, indexes.Indexable): """ A Haystack search index for Questions. """ text = indexes.EdgeNgramField(document=True, use_template=True) id = indexes.IntegerField(model_attr='id') user_id = indexes.IntegerField(model_attr='user_id') question = indexes.EdgeNgramField(model_attr='question', boost=1.15) study_level = indexes.IntegerField(model_attr='study_level') is_answered = indexes.IntegerField(model_attr='is_answered') is_archived = indexes.BooleanField(model_attr='is_archived') created_at = indexes.DateTimeField(model_attr='created_at') tags = indexes.MultiValueField() schools = indexes.MultiValueField() answers = indexes.IntegerField(indexed=False) has_answer = indexes.IntegerField(indexed=False) content = indexes.CharField(indexed=False) content_short = indexes.CharField(indexed=True) def get_model(self): return Question def prepare_study_level(self, obj): study_level = obj.study_level There is more def prepare_x but study_level is where my problem is. Then it is used in this code class QuestionSearch(object): # Plain old Python object for question search. MAX_RESULT_LENGTH = 12 def __init__(self, user, query='', limit=MAX_RESULT_LENGTH, subjects=[], study_level_min=None, study_level_max=None): self.user = user self.query = query self.limit = limit self.subjects = subjects self.study_level_min = study_level_min self.study_level_max = study_level_max # Swaps the min and max values if they are in the wrong order. if study_level_min … -
Why do I get not allowed access when using keycloak JavaScript adapter?
I have a Django app authenticating via Keycloak as described here. From this Django app I now wants to call a microservice also protected by Keycloak using the same login. I don't want the suer to have to login again. I am trying to yse the JavaScript adapter. I am trying to configure it something like: <script> var keycloak = Keycloak({ url: "{{Keycloakurl}}/auth", realm: 'myrealm', clientId: 'myclient' }); keycloak.init({ onLoad: 'login-required' }).success(function(authenticated) { alert(authenticated ? 'authenticated' : 'not authenticated'); }).error(function() { alert('failed to initialize'); }); </script> But when I load the page I get this sort of error messages: Failed to load http://keycloak.FOO.com/auth/realms/toxhq/protocol/openid-connect/token: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myapp.Foo.com' is therefore not allowed access. I am not fully sure why this is but I am beginning to wonder if it is because of same-origin policy in some way. How can I set up the functionality I want with Keycloak protected microservices sharing one Keycloak authentication? -
DJango HttpResponseRedirect not passing "request" to function
I am using the DJango login/authentication functionality. I have extended it with a Profile using the Extending The Existing User Model approach. In the "Profile" is a variable called restrole. In the code below, restrole is being used to control the NEXT screen the user sees (as well as as the data on it): def user_login(request): if request.method == 'POST': # First get the username and password supplied username = request.POST.get('username') password = request.POST.get('password') # Django's built-in authentication function: user = authenticate(username=username, password=password) if user: # Check it the account is active if user.is_active: # Log the user in. login(request, user) myprofile = user.userprofileinfo restrole = myprofile.restrole if restrole == 1: return HttpResponseRedirect(reverse('authinduction:induct-owner')) elif restrole == 2: return HttpResponseRedirect(reverse('authinduction:induct-office')) elif restrole == 3: return HttpResponseRedirect(reverse('authinduction:induct-customer')) elif restrole == 4: return HttpResponseRedirect(reverse('authinduction:induct-field-work')) else: return HttpResponse("Unrecognized Role") This Part works fine I can get data from the "request" variable # First get the username and password supplied username = request.POST.get('username') <<< data is returned password = request.POST.get('password') <<< data is returned The problem When I execute one of the branches: if restrole == 1: return HttpResponseRedirect(reverse('authinduction:induct-owner')) It goes to the correct function, but "request" does not appear to have any data associated … -
how to change www to something else in Django urls?
I've created a rest API for my Django app but how I go to api.website.com rather than something like www.website.com/api Btw I'm using nginx if that has to do anything with this -
TzInfo error when unsing Func() on a DatetimeField
I have a model A: class A(models.Model): start_datetime = models.DatetimeField() end_datetime = models.DatetimeField() status = models.CharField(max_length=3) And I'm trying to count the number of "row" group by "day". So here is my query: queryset = A.objects.filter(status='OK').annotate(day=Func(F('start_datetime'), function='DATE')).values('day').annotate(total=Count('id')) And when I try to print the queryset: print(queryset) I got this error message: AttributeError: 'datetime.date' object has no attribute 'tzinfo' I understand why but I don't how to solve this. In my settings: LANGUAGE_CODE = 'en' TIME_ZONE = 'America/Montreal' USE_TZ = True USE_I18N = True USE_L10N = True Please advise. Thank you. -
How to extend Django filer image model field by category
I recently had problems with extending django filer, probably my knowledge about django is not sufficient yet. Basically what I would like to achieve is to extend django filer image model to be able to add category to images. Of course would be nice to have manytomany relation to category model. Could someone help me with this topic? my code (all in myPlugins app): models.py from filer.models.abstract.BaseImage class CustomImage(BaseImage): category = models.CharField(max_length=20, blank=True, null=True,) class Meta: app_label = 'myPlugins' admin.py from django.contrib import admin from filer.admin.imageadmin import ImageAdmin from myPlugins.models import CustomImage class CustomImageAdmin(ImageAdmin): pass CustomImageAdmin.fieldsets = CustomImageAdmin.build_fieldsets( extra_main_fields=('author', 'default_alt_text', 'default_caption', 'category'), extra_fieldsets=( ('Subject Location', { 'fields': ('subject_location',), 'classes': ('collapse',), }), ) ) admin.site.unregister(ImageAdmin) admin.site.register(CustomImage, CustomImageAdmin) in settings.py I've added: FILER_IMAGE_MODEL = 'myPlugins.models.CustomImage' and I'm getting an error: File ".../mysite/myPlugins/admin.py", line 27, in admin.site.unregister(ImageAdmin) File ".../venv/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 118, in unregister for model in model_or_iterable: TypeError: 'MediaDefiningClass' object is not iterable -
DJango authentication User search not working properly
What I am trying to do is the following: 1. Retrieve a User record (from the DJango authentication system) is in the DB 2. get the Username (from that record) 3. Use the "username" to look for a record in a *different* table. 4. If the record *is not* there (in the *different* table), then create one. I am getting an error on what looks like the query into the User table even though I have the following in the views.py from django.contrib.auth.models import User Also, it is not clear why the DoesNotExist error is taking place (when one is looking for the User in the authentication system). Why am I getting this error? TIA This is the error message This is how the "app" is structured views.py from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from authinduction.models import Mstrauthownerrdx from django.contrib.auth.models import User def inductowner(request): username = request.POST.get('username') user = User.objects.get(username=username) myprofile = user.userprofileinfo num_results = Mstrauthownerrdx.objects.filter(logonid=username).count() if not ( num_results == 0 or num_results == 1 ): raise ValueError('Number of items found '+ num_results + ' is not valid') if num_results == 0: u = Mstrauthownerrdx.objects.create(logonid=username, emailaddr=user.email, worktype=1, memo='OWNER', active=1, formpagelastfilled=myprofile.lastpgprocno, formcomplete=myprofile.nextpgprocno, reclocktype=1, … -
checking if data existing in my array of dict
i'd like to check if data exists in all my fields and if there is None in one field return False for all the rest otherwise return True if all the fields are filled up. It's only returning True. Can Anyone help ret = {'complete': False} try: company_director = CompanyDirector.objects.filter(company__token=token).values( 'username','directorTitle','directorInitials', 'directorName','administrativeOrder', 'directorSurname','directorId','directorQualification', 'releventExperiance','education','directorInsolvent', 'directorProffesionalAssociation','profileImage','profileImageThumbNail', 'directorProffesionalAssociationList','releventExperiance','shareInBusiness', 'profileImage','qualifications','criminalOffence','capInBuss','spSkill').first() if company_director: ret['complete'] = True for field, value in company_director.items(): if (type(value) in [str, unicode] is None and len(value)) == "": ret['complete'] = False break; if str(exclude_items) in field: if (type(value) in [str, unicode] and len(value) > 0 and value is not None) or type(value) in \ [int]: ret['complete'] = True except ValueError as e: print (e) return Response(ret) -
Made image is not shown in html
Made image is not shown in html. I wrote in views.py @login_required def view_plot(request): left = np.array([1, 2, 3, 4, 5]) height = np.array([100, 200, 300, 400, 500]) plt.bar(left, height) filename = "output.png" save_fig=plt.savefig(filename) response = HttpResponse(content_type="image/png") save_fig.save(response, "PNG") return save_fig in html <body> <img src='/accounts/view_plot' width=300 height=300> </body> in urls.py urlpatterns = [ url(r'^view_plot$', views.view_plot,name='view_plot'), ] But now ,web page is like cracked image is shown. I do not know why this error happens. In Django app,output.png is saved. I doubt image is not made in view_plot.But i cannot know whether or not. What is wrong in my code?How should I fix this? -
Django Geojson Serializer does not return any "properties"
I am trying to load PostGIS data to GeoJSON using Django's serializing objects from this reference: GeoJSON Serializer I was able to successfully load the said data to a map with its corresponding geometrie. However the rest of its fields in the model does not exist in its GeoJSON properties field when I checked. Instead of an output: { 'type': 'FeatureCollection', 'crs': { 'type': 'name', 'properties': {'name': 'EPSG:4326'} }, 'features': [ { 'type': 'Feature', 'geometry': { 'type': 'Point', 'coordinates': [-87.650175, 41.850385] }, 'properties': { 'name': 'Chicago' } } ] } If would get: { 'type': 'FeatureCollection', 'crs': { 'type': 'name', 'properties': {'name': 'EPSG:4326'} }, 'features': [ { 'type': 'Feature', 'geometry': { 'type': 'Point', 'coordinates': [-87.650175, 41.850385] }, 'properties': { } } ] } I basically wanted the properties to be included so that I can manipulate it in the Leaflet layers. However, unable to serialize the other fields (or at least a specific field from my model), I won't be able to do this. How can I include for example trail_name in the output GeoJSON properties? models.py class Trail(models.Model): ogc_fid = models.AutoField(auto_created=True, primary_key=True, null=False) trail_name = models.CharField(max_length=100, blank=True, null=True) trail_id = models.CharField(max_length=100, blank=True, null=True) trail_type = models.CharField(max_length=300, blank=True, null=True) wkb_geometry … -
How to ordering by specific rules django
I want to order my objects in django by this rule: All characters with is_sold == True must be in the end of query result. I am use two query, to get both sold and not sold characters: characters = list(Character.objects.all().filter(is_sold=False).order_by('server__ranking')) characters += list(Character.objects.filter(is_sold=True).order_by('server__ranking')) Can i do this using only one query using order_by -
Django1.8 ClassBasedView success_url not working
I am trying to create a form save the data and redirect the page views.py class VolunteerCreateView(SuccessMessageMixin, CreateView): model = Volunteer form_class = VolunteerForm template_name = 'volunteer.html' success_url = reverse_lazy('home') success_message = 'Thank you!' volunteer.html <form method="post" class="myform" action="{% url 'volunteer' %}"> {% csrf_token %} <p> {{form.name}}{{form.age}} </p> <p> {{form.location}} </p> <p> {{form.email}} </p> <p> {{form.phone}} </p> <p class="as-comment"> {{form.about}} </p> <p class="as-submit"> <input type="submit" value="Submit" class="as-bgcolor"> </p> </form> </div> models.py class Volunteer(models.Model): name = models.CharField(max_length=255) age = models.IntegerField() location = models.TextField() about = models.TextField() email = models.EmailField() phone = models.CharField(max_length=20) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return "{0}".format(self.name) urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^volunteer/', web.views.VolunteerCreateView.as_view(), name='volunteer'), url(r'^$', web.views.home, name='home'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Everything works except the redirection part. The browser console shows 2 request first volunteer url(302 POST) other to home url(200 GET) but the page is not changed its the same page. What could be the reason for this. I am using Python3.5 Django1.8 -
Mommy receipe with m2m not working - 'RecipeForeignKey' object has no attribute 'pk'
I'm using model-mommy==1.4.0 within my tests in my django==1.11.6 project. Here's my receipe: group_employee = Recipe( Group, name="employee" ) user = Recipe( User, ... groups=[foreign_key(group_employee)], ... ) I use it in my test setUp() like this: self.user = mommy.make_recipe('apps.account.user') When I run the test I get: File "[...]/site-packages/model_mommy/mommy.py", line 351, in _handle_m2m if not value.pk: AttributeError: 'RecipeForeignKey' object has no attribute 'pk' I checked the mommy source code and yes, it's true, the RecipeForeignKey really doesn't have a pk value because it's on a meta level, the real object is inside it. I searched Google up and down but nobody seems to have at least a similar problem. Any ideas? Thx -
How can I load big numpy array to the PostgreSQL database in Django project with Docker container?
I have a very big numpy array. After printing it looks in this way: myArray = np.array(df_array) print(myArray) 2007-01-01 Estimates of Iraqi Civilian Deaths. Romania and Bulgaria Join European Union. Supporters of Thai Ex-Premier Blamed for Blasts. U.S. Questioned Iraq on the Rush to Hang Hussein. States Take Lead on Ethics Rules for LawsraeCanadian Group. 2007-01-02 For Dodd, Wall Street Looms Large. Ford's Lost Legacy. Too Good to Be Real?. A Congressman, a Muslim and a Buddhist Walk Into a Bar.... For a Much-Mocked Resume, One More Dig. Corporate America Gets the (McNulty) Memo. Completely. Floating Away From New York. National Mourning. The NYSE's Electronic Man. Developer Accuses Hard Rock of Rigging Sale. Shoney's Chain Finds New Buyer. Nucor to Acquire Harris Steel for $1.07 Billion. Will Bill Miller Have a Happier New Year?. 2007-01-03 Ethics Changes Proposed for House Trips, K Street. Teatime With Pelosi. Turning a Statistic On Its Head. War Protest Mom Upstages Democrats. An Investment Banking Love Story. Revolving Door: Weil Gotshal. Should U.S. Airlines Give Foreign Owners a Try?. 2007-01-04 I Feel Bad About My Face. Bush Recycles the Trash. A New Racing Web Site. What&#8217;s the Theme?. The Product E-Mails Pile Up. ... I … -
Pass xml file from django to javascript
I'm creating an .xml file and then trying to pass this file to javascript, so I could use it there. Here is my view function: def index(request): markers_set = Marker.objects.all() root = Element('markers') tree = ElementTree(root) for m in markers_set: name = Element('marker') name.set('id', str(m.id)) name.set('name', m.name) name.set('address', m.address) name.set('lat', str(m.lat)) name.set('lng', str(m.lng)) name.set('type', m.type) root.append(name) tree.write(open(r'Markers\static\Markers\data.xml', 'wb')) return render_to_response('index.html', {'xmldata' : r'D:\Geoinformation systems\Maps\Markers\static\Markers\data.xml'}) Here is a piece of index.html where javascript code is located: <html> <body> <div id="map"></div> <script> function initMap() { var map = new google.maps.Map(document.getElementById('map'), { center: new google.maps.LatLng(-33.863276, 151.207977), zoom: 12 }); var infoWindow = new google.maps.InfoWindow; <!--Here I'm taking data that is passed--> downloadUrl('{{ xmldata }}', function(data) { var xml = data.responseXML; var markers = xml.documentElement.getElementsByTagName('marker'); ... }); } </script> </html> How should I pass/get the file, so not to failing loading it? -
ProgrammingError in Django when adding a new model-instance to the Database, what could be wrong?
When using the Django Admin panel, I am able to add new instances to Users and Groups. The same thing goes for all my apps, except for one. This one app, resultregistration, always gives me a ProgrammingError whenever I try to add a new model. For example, this app has a Competition-model where data about a sport competition should be stored. When I click "+ Add" I am taken to the correct site where I can add a new competition. However, when I press save I get: ProgrammingError at /admin/resultregistration/competition/add/ column "competition_category" of relation "resultregistration_competition" does not exist LINE 1: INSERT INTO "resultregistration_competition" ("competition_c... Of course, I assume something is wrong with the migrations. However, I have run python manage.py makemigrations appname, and python manage.py migrate appname, and that works fine. I get a message that there are "No changes detected", and "No migrations to apply". I have tried solutions posted on SO, but none of them worked. What is the general reason for this error? And does anyone know what could be wrong in this specific case? Could one get this error if something is wrongly defined in the model? Or does it have to be a migration problem? … -
How to get property names from super class in sub class python
I have a class like below class Paginator(object): @cached_property def count(self): some_implementation class CachingPaginator(Paginator): def _get_count(self): if self._count is None: try: key = "admin:{0}:count".format(hash(self.object_list.query.__str__())) self._count = cache.get(key, -1) if self._count == -1: self._count = self.count # Here, I want to get count property in the super-class, this is giving me -1 which is wrong cache.set(key, self._count, 3600) except: self._count = len(self.object_list) count = property(_get_count) As indicated in the comment above, self._count = <expression> should get the count property in super-class. If it is method we can call it like this super(CachingPaginator,self).count() AFAIK. I have referred many questions in SO, but none of it helped me. Can anyone help me in this. -
How can I not need to query the database every time?
How can I not need to query the database every time? From the bellow snapshot: I have five tabs, name as: 云主机,云硬盘,云主机快照,云硬盘快照,安全组: And in the bottom of the list, there is <<, <, >,>>, and GO buttons that can calculate the page_num. Then I can use the localhost:8000/app_admin/myServers-1-1-1-1-1 analogous link to query the data. 1-1-1-1-1 represents 云主机,云硬盘,云主机快照,云硬盘快照,安全组's page_num. In the views.py, there are key codes: def myServers(request, server_nid,disk_nid,snapshot_server_nid, snapshot_block_nid,security_group_nid, tab_nid): data = get_res_myserver(request, server_nid,disk_nid,snapshot_server_nid, snapshot_block_nid,security_group_nid, tab_nid) return render(request, 'app_admin/my-server.html', {"data":data}) ... def get_res_myserver(request, server_nid,disk_nid,snapshot_server_nid, snapshot_block_nid,security_group_nid, tab_nid): # query all the data, and paginator there ... return data But, my issue is, every time I query the localhost:8000/app_admin/myServers-x-x-x-x-x, it will take a long time, sometimes more than 8 seconds(the time can not be shorter), its a long time for user experience. So, Whether there is a method that I only query my data once, then paginator can be multiple times? -
Passing with-declared variables to a custom function in Django template tags
I want to build a table of 5 columns and 8 rows with the data contained in a list of 40 elements: {% for row_num in 0|range:8 %} {% with startrange=row_num|multiply:5 endrange=row_num|multiply:5|add:5 %} {{ startrange }} {{ endrange }} <div class="row"> {% for item in items|slice:startrange,endrange %} <div class="col"> {% include "shop/item_card.html" %} </div> {% endfor %} </div> {% endwith %} {% endfor %} I have successfully defined multiply and add custom functions, and I have defined startrange and endrange. Now, I need to pass them to slice function. I've tried slice:"startrange:endrange" among other possibilities, but none seems correct. How can I pass 2 (or more) variables to a custom function?