Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to be able to add records using Http Methods on django
I'm creating a Django rest API authentication system and I want to return data in JSON format,the main purpose of this question is : I want to add or delete users only by adding fields on json format , not in the inputs that've created : this is my views.py : # Rendering plant data as json : def plant_json(request): data=list(new_Plant.objects.values()) return JsonResponse(data,safe=False) this is my output ( don't mind the values ) : [{"id": 5, "name": "dqsd", "adress": "sdq", "type": "PV", "location": "dqd", "list_gateway": "gggdds", "status": "etude"}, {"id": 6, "name": "fdsfds", "adress": "fsdfds", "type": "PV", "location": "fdsfds", "list_gateway": "fdsfs", "status": "etude"}, {"id": 7, "name": "sdqdssd", "adress": "dsdsq", "type": "HYBRID", "location": "dqsdqs", "list_gateway": "dsdqss", "status": "online"}] normally in order to add a new plant I've created a HTML template that has inputs where the user can add a plant , but what I want is that I can add a plant only by adding fields directly using json format ( using postman for example ) no need for the inputs. Thank you -
Hvplot with django and netcdf
im working on a django project for visulisation of netcdf data , i use hvplot to plot the data and there is no interactivity , i want to know if possible how to make it possible. the plot in browser my code : import hvplot import hvplot.xarray import xarray as xr import holoviews as hv import panel as pn from panel.interact import interact import numpy as np from bokeh.plotting import figure from bokeh.embed import components from bokeh.layouts import column, grid from bokeh.models import ColumnDataSource, CustomJS, Slider,HoverTool hv.extension('bokeh') def data_visualization(request): ds = xr.open_dataset('T_mensuel.nc') def plot(variable): return ds[variable].hvplot.line() model = interact(plot, variable = list(ds.data_vars)) script, div = components(model.get_root()) return render(request,'visualization.html',{'script': script, 'div': div}) -
Database population with django models, module not found error
I am just getting started with the Django framework through the book "The Definitive Guide to Django." I used psycopg2 to write my SQL insert statements (Postgres) through a script named scrape.py. I wanted to switch to using the Django models, however, I get an django.core.exceptions.ImproperlyConfigured error when I try to run from models import articles. I first used import os os.environ['DJANGO_SETTINGS_MODULE'] = 'CannaMed.settings' But got the error File "/home/ian/CannaMed/venv/lib/python3.8/site-packages/django/db/models/base.py", line 127, in __new__ app_config = apps.get_containing_app_config(module) File "/home/ian/CannaMed/venv/lib/python3.8/site-packages/django/apps/registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "/home/ian/CannaMed/venv/lib/python3.8/site-packages/django/apps/registry.py", line 137, in check_apps_ready settings.INSTALLED_APPS File "/home/ian/CannaMed/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 87, in __getattr__ self._setup(name) File "/home/ian/CannaMed/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 74, in _setup self._wrapped = Settings(settings_module) File "/home/ian/CannaMed/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 183, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'CannaMed' I then added import django django.setup() and got the error: Traceback (most recent call last): File "scrape.py", line 2, in <module> django.setup() File "/home/ian/CannaMed/venv/lib/python3.8/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/ian/CannaMed/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 87, in __getattr__ self._setup(name) File "/home/ian/CannaMed/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 67, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Lastly … -
Django/Pandas/Website - Querying a pandas dataframe instead of database, is it possible?
My table has some advanced features and queries that Pandas can accomplish but a database can't, so I am wondering about the implications of using a pandas dataframe on the server as a read-only database. The setup would be the basetable being a big pandas dataframe (400mb) on the webserver, and users submit GET requests that filter it in unique ways in order to make charts off of the data. The question is are there serious costs and/or bottlenecks when many users query a webservers dataframe? I know databases are meant to serve many people concurrently, but is this a problem for my case? Further, after a user filters the table, I imagine this filtered table is temporarily saved during their session....could this lead to memory requirements of the webserver gettings wildly out of hand? (Ex: 1000 users x 200MB avg table size = 200GB of memory demanded) Any explanation and tips would be appreciated! -
Django advanced i18n url patterns
I'm trying to create urlpatterns in django that would allow me something like this: .../en/admin .../en/some_view .../api/en/another_view basically i'd like to sort some of my views under "/api/" but I would like to prepend this before the /en/ for those views. Is something like this possible in django? -
Distribution for Django_Eel not found after Django_eel converted to exe by using Pyinstaller
I try to convert Django Eel to exe so client can run the page from their end without publish the django eel to server, I try to exe the django by pyinstaller --noconfirm --onefile --console "C:\KMME\demo\manage.py" But when i run the EXE I get below error: pkg_resources.DistributionNotFound: The 'django-eel' distribution was not found and is required by the application [1712] Failed to execute script 'manage' due to unhandled exception! Please help and share ideas to overcome this even though Django EEL already being install. -
Django search Form <QuerySet []>
I am creating a Search_Model with QuerySet. For example, if i search for apples The result is displayed as Search By <QuerySet []> Why is this? My html declaration is like this <h1> Search By {{posts}} <h2 MY BASE.HTML <form class="form-inline my-2 my-lg-0" action="{% url 'search' %}"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> MY SEARCH.HTML {% extends "shopping_mall/base.html" %} {% block search %} <div> <h1> Search </h1> <h2> Search By {{posts}} </h2> </div> {% endblock %} MY urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('search/',views.search, name='search'), path('top_cloth/', views.top_cloth), path('top_cloth/<int:pk>/', views.cloth_detail, name='top_cloth_pk'), path('top_cloth/<int:pk>/comment/', views.add_comment, name='add_comment'), path('top_cloth/<int:pk>/remove/', views.comment_remove, name='comment_remove'), path('top_cloth/<int:pk>/modify/', views.comment_modify, name='comment_modify'), ] MY views.py def search(request): search_post = request.GET.get('search') if search_post: posts = ProductList.objects.filter(Q(product_name__icontains=search_post)) else: posts = ProductList.objects.all().order_by("-date_created") return render(request, 'shopping_mall/search.html', {'posts': posts}) -
What's the difference between MEDIA_ROOT = BASE_DIR / 'media'` and MEDIA_ROOT= os.path.join(BASE_DIR, "media") in Django setting.py
I wanted to know the difference between using MEDIA_ROOT = BASE_DIR / 'media' and MEDIA_ROOT= os.path.join(BASE_DIR, "media") in settings.py. I used MEDIA_ROOT = BASE_DIR / 'media' and my file uploading works fine but when I delete a file it stays in the directory. -
heroku open =>relation "main_goal" does not exist LINE 1: ...y", "main_goal"."date", "main_goal"."status" FROM "main_goal
When I run the Heroku open command , it returns an error Everything works locally heroku run manage.py migrate doesn't help, makemigrations too, manage.py migrate r run-syncdb - also does not give anything enter image description here enter image description here -
Send JavaScript value to method on views.py (Django)
I'm using django (4.0.4) to develop a 'simple' interface with three dropdown list with the data of the last two depends of the value selected of the first. This is the front: This is the project structure dir: ├── db.sqlite3 ├── manage.py ├── example_web │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── web ├── admin.py ├── apps.py ├── __init__.py ├── migrations ├── models.py ├── static │ ├── css │ │ └── style.css │ └── js │ └── app.js ├── templates │ ├── index.html ├── tests.py └── views.py This is urls.py from django.contrib import admin from django.urls import path from web.views import homePageView urlpatterns = [ path('admin/', admin.site.urls), path('', homePageView), ] views.py from django.shortcuts import render from django.template import loader from django.http import HttpResponse from jf.clients import RPClient def homePageView(request): a = _get_coaches() b = _get_devices() value_js = request.GET.get('id') print(value_js) context = { 'coaches': a, 'devices': b, } return render(request, 'index.html', context) def _get_coaches(): client = RPClient('dev', proxy_ip='10.10.1.15') a = client.get_current_value('status/coach') return [i['id'] for i in a['items']] def _get_devices(request): client = RPClient('dev', proxy_ip='10.10.1.15') a = client.get_current_value('status/cable/X') # !!!!!!!!!! # HERE is where in the X place I want to store the value_js variable … -
How to create a Django queryset based on items from another
I'm using Django 2.2.28 and Python 3.7.7 in a legacy application. I have a display page that displays People based on a class PeopleQuerySet(models.QuerySet) that's filtered and paginated. This works, but I'd like to know if it's possible to do something like this: new_people_queryset = PeopleQuerySet() for person in existing_queryset.iterator(): if some_condition: new_people_queryset.add(person) Is there a way to do what I'm implying above; create an empty PeopleQuerySet() object and then insert people into it from a queryset that's the result of filtering? The some_condition thing is some arbitrary Python logic I'm using for illustration purposes here. Any ideas, pointers, etc. would be greatly appreciated. -
populating django database using migrations
I created an api that allows to read some data with filters based on the models I created. and launch the database is empty so I created a script to populate the database. I then dockerized the app and deployed to AWS. the issue here is that everytime the container restarts the script is re-run. I would like to use migrations to do this. how? for now the docker entrypoint is python manage.py wait_for_db python manage.py makemigrations API python manage.py migrate # python import_csv.py uwsgi --socket :9000 --workers 4 --master --enable-threads --module myapi.wsgi -
display:'table' is not working as it supposed to be
I want the table to be visible only after the submit button clicks. But it's not staying on the screen as it is supposed to be. Once I click the submit button, the table comes up for a second and then again becomes invisible. Please let me know what I am doing wrong in my code. Also please let me know if there is any other way to do it. index.html <form action="#" id="form" method="post"> <div style="margin-left: 2rem;"> <!-- <input class="btn btn-primary" type="submit" value="Submit" id="btn" onclick="hide()"> --> <input class="btn btn-primary" type="button" value="Submit" id="btn" onclick="hide()"> </div> </form> <div style="margin-top: 4rem; display: flex; justify-content: center; align-content: center;"> <table style="display: none;" id="table"> <tbody> <tr> <th scope="row">Profile No. : </th> <td>{{ProfileNo}}</td> </tr> <tr> <th scope="row">Name : </th> <td>{{Name}}</td> </tr> </tbody> </table> </div> <script> function hide() { document.getElementById("form").submit(); let table = document.getElementById("table"); if (table.style.display === 'none') { table.style.display = 'table'; } } </script> -
Selecting items from a many to many field to link specific items in the list to a model in the admin panel
I am working on a recipe book app, and I currently have my models connected in this way: class Tool(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=200) def __str__(self): return self.name class Recipe(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=200) servings = models.IntegerField(default=1, blank=False) tools = models.ManyToManyField(Tool) def __str__(self): return self.name The admin panel input currently looks like this: Upon saving the data as shown in the screenshot, I get the following error: OperationalError at /admin/recipeBook/recipe/add/ no such table: recipeBook_recipe_tools Here is my admin.py, just incase it's useful: from django.contrib import admin from .models import Recipe, Ingredient, Instruction, Tool # Register your models here. class IngredientInline(admin.TabularInline): model = Ingredient extra = 2 class RecipeAdmin(admin.ModelAdmin): fieldsets = [ ('Information', {'fields': ['name', 'description', 'servings']}), ('Tools', {'fields': ['tools']}) ] inlines = [IngredientInline] list_display = ('name', 'description', 'servings') search_fields = ['name'] list_filter = ['servings'] admin.site.register(Recipe, RecipeAdmin) admin.site.register(Ingredient) admin.site.register(Instruction) admin.site.register(Tool) -
Django POST getlist for dynamic content
I a database I have a list of products. If they are need to be found = True they will appear in the screen : <h2>Shopping list</h2> <section> {% for market in markets %} <button class="collapsible">{{market.name}}</button> <div class="content"> <ul> {% for shopping in shoppings %} {% if shopping.marketplace.name == market.name %} <div id="conteneurs"> <div class="product"><label for="stock" class="control-label">{{shopping.name}}</label></div> <div class="stock"><input type="number" name="stock" value="{{shopping.quantitytobuy}}" id="stock"></div> <div class="checkbox"><input type="checkbox" name="found"></div> </div> {% endif %} {% endfor %} </ul> </div> {% endfor %} </section> <div id="validation"> <div class="validation"><input type="submit" value="Found"></div> </div> If I found the product I can check a box. I would like to recover the amount for the products where I check the box the quantity to can update the stock of them. I have no idea where to start : should I need to define a variable for the checkbox ? how do I recover the quantity with the associate product for all the line checked in the file views.py def shopping(request): marketplaces = Marketplaces.objects.order_by('name') products = Products.objects.all().filter(buy=True) template = loader.get_template('stock/shopping.html') context = {'markets' : marketplaces, 'shoppings' : products, } return HttpResponse(template.render(context, request=request)) -
Django / Access to previous or next instance from the same class
My app starts with Scene1 Here is my Models.py where Scenes are defined class Scenes(models.Model): name = models.SlugField('Scene name', max_length=60,unique=True) description = models.TextField(blank=True) fileGltf = models.FileField(null=TRUE, blank=False, upload_to="3dfiles/") record_date = models.DateTimeField('Scene date') manager = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL) prev = models.ForeignKey( 'self', related_name='next', blank=True, null=True, on_delete=models.SET_NULL) def __str__(self): return self.name The creation is ok. Then in views.py, let's say my current scene is : myScene=Scenes.objects.get(name=whichScene) If I want to list all next scenes from this scene : scene_list=myScene.next.all() If I want to access to the previous scene, what is the correct syntax ? scene_previous=myScene.prev -
Load foreign model instances into queryset.values()
I have queryset that groups and aggregates some data: EmployeeAssessment.objects.all().annotate(month=TruncMonth('assessment_date')).values( 'month', 'assessed_employee', 'subject' ).annotate(average_score=Sum('scores__score') / Count('scores__score', distinct=True)) And because of .values() I get assessed_employee and subject as IDs rather than model instances I know that there are some similar questions here, but they're all talking about single relation, that can be reversed to get the needed data from related model. My problem is that I need to get two nested objects: "assessed_employee" and "subject". Both of them are ForeignKeys I use DRF serializer like this: class EmployeeAverageScoreSerializer(Serializer): month = DateField() assessed_employee = EmployeeSerializer() # <- ModelSerializer subject = AssessmentSubjectSerializer() # <- ModelSerializer average_score = FloatField() It is ok if I will have some subqueries or something, but I need a single queryset that still can be paginated. How can I load models by ID after applying ".values" or maybe what other way can I use to get that data without losing model instances in resulting queryset? -
No module named 'crispy_formsecommerce' error
I already installed crispy forms, and fixed settings. But raising an error. The Error: enter image description here My settings.py file: enter image description hereenter code here enter image description here my pipenv installed apps : enter image description here some template: enter image description here my forms.py: enter image description here Please help! -
How can i call class function thats insert row into db properly from my django template?
Hellow, I am noob and I make instagram followers scraper on Django. I make a function that should add 1 (only 1 cos it works really slow) new follower in to db which takes from already working sсraping functions and place it into class. class ListOfFollowers(ListView): model = Followers context_object_name = 'followers_of' template_name = 'insta/followers.html' def get_follower(self, username): loader = instaloader.Instaloader() loader.login('***', '***') profile = instaloader.Profile.from_username(loader.context, username) followers = profile.get_followers() followers_tuple = tuple(followers) i = random.randint(0, len(followers_tuple) - 1) login = followers_tuple[i].username photo = followers_tuple[i].get_profile_pic_url() url = f'https://www.instagram.com/{login}/' mutual_subscription = followers_tuple[i] in profile.get_followees() res = {'login': login, 'photo': photo, 'url': url, 'mutual_subscription': mutual_subscription} return res def add_followers(self): username = WhoFollow.objects.get(follow_on__contains=self.kwargs['follow_id']).title context = None while not context: try: context = get_follower(username) except: next context.update({'follow_on': self.kwargs['follow_id']}) res = Followers(context) res.save() def get_queryset(self): return Followers.objects.filter(follow_on=self.kwargs['follow_id']) function calls add_followers (try block is just because its not always working from 1st try) My models class WhoFollow(models.Model): title = models.CharField(max_length=255) def __str__(self): return self.title def get_absolute_url(self): return reverse('follow', kwargs={'follow_id': self.pk}) class Followers(models.Model): login = models.CharField(max_length=255) photo = models.ImageField(upload_to="photos/", blank=True) url = models.URLField() mutual_subscription = models.BooleanField(default=False) time_add = models.DateTimeField(auto_now_add=True) time_unfollow = models.DateTimeField(blank=True) follow_on = models.ForeignKey(WhoFollow, on_delete=models.PROTECT) def __str__(self): return self.login And my template {% extends 'insta/Base.html' %} … -
How to reduce size of input box in html used in django
Is there any way to reduce the size of the description box used below? I used it on a HTML template under a django project when I rendered the page the description box was huge. <div class="container-fluid"> <div class="card-body"> <form action="{% url 'create_post' pk=classroom.id %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> {{ post_form.title|attr:"class:form-control"|attr:"placeholder:Title"}} </div> <div class="container"> {{ post_form.description|attr:"class:form-control"|attr:"placeholder:Description" }} </div> <button type = "submit" class="btn btn-sm btn-primary m-1 pl-3 pr-3 float-right"> Post </button> <button id = "cancel-post" class="btn btn-sm btn-outline-dark m-1 float-right"> Cancel </button> </form> </div> </div> -
Web app such as libgen using Python and SQL?
I'm trying to make a webapp almost like the website libgen essentially using Python that can access a MySQL database and query and search through the database in order to find what they are looking for. I'm a bit stuck on how to approach this as I believe using Django as a framework to access the database would be good but I can't seem to understand how to connect the database (which I have locally) to the project. But then I would need to be able to move this online for hosting. I would really appreciate the help. -
Null value in column violates not-null constraint after deleting objects incorrectly
Help me please I don't know what's going on. I wrote some simple blog, where I could add posts and comments. It was working well. views.py: def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) # calls the given model and get the object, type = <class 'blog.models.Post' if request.method == "POST": # if we posted data form = CommentForm(request.POST) if form.is_valid(): # if all fields are filled comment = form.save(commit=False) # create instance and return which not saved in database "Comment" <class Comment> comment.post = post # return Title comment.author = request.user comment.save() return redirect('post_detail', pk=post.pk) else: form = CommentForm() # type = <class 'blog.forms.CommentForm'> return render(request, 'blog/add_comment_to_post.html', {'form': form}) But when I added a function for deleting comments, that wrote me a mistake, like this: null value in column "approved_comment" of relation "blog_comment" violates not-null constraint views.py: def comment_remove(request, pk): post = get_object_or_404(Post, pk=pk) comment = get_object_or_404(Comment, pk=pk) print(comment) comment.delete() return redirect('post_detail', pk=post.pk) I think I deleted comment incorrectly. I don't understand how primary keys works, how comments and posts are related each other. And I don't understand how to understand it. -
django remove object from list that match query filter
At my Django application I have two lists. One list called keys and anotherone existing_keys: for key in keys: if Files.objects.filter(file_name=Path(key).name).exists(): existing_keys.append(key) while key in existing_keys: keys.remove(key) print(f'key {key} removed') How can I now remove all entries in keys that have a match with existing_keys? currently im always running into the following error: raised unexpected: ValueError('list.remove(x): x not in list') Thanks in advance -
Need to perform update method on writable Nested serializers in django
models.py class Product(models.Model): product_id = models.CharField(max_length=50,default=uuid.uuid4, editable=False, unique=True, primary_key=True) product_name = models.CharField(unique=True,max_length=255) class Client(models.Model): client_id = models.CharField(max_length=50,default=uuid.uuid4, editable=False, unique=True, primary_key=True) org = models.ForeignKey(Organisation, on_delete=models.CASCADE, related_name='org',null=True) product = models.ManyToManyField(Product,related_name='product') client_name = models.CharField(unique=True,max_length=100) .... serializers.py class Clientpost_Serializers(serializers.ModelSerializer): billing_method = Billingmethod_Serializers() product = Product_Serializers(many=True) def create(self, validated_data): billing_method_data = validated_data.pop('billing_method') product_data = validated_data.pop('product') billing_method = Billing_Method.objects.create(**billing_method_data) validated_data['billing_method'] = billing_method client = Client.objects.create(**validated_data) product = [Product.objects.create(**product_data) for product_data in product_data] client.product.set(product) return client def update(self, instance, validated_data): billing_method_data = validated_data.pop('billing_method') billing_method = instance.billing_method # product_data = validated_data.pop('product') # product = instance.product instance.currency = validated_data.get('currency', instance.currency) instance.currency_type = validated_data.get('currency_type', instance.currency_type) instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.description = validated_data.get('description', instance.description) instance.street_address = validated_data.get('street_address', instance.street_address) instance.city = validated_data.get('city', instance.city) instance.state = validated_data.get('state', instance.state) instance.country = validated_data.get('country', instance.country) instance.pincode = validated_data.get('pincode', instance.pincode) instance.industry = validated_data.get('industry', instance.industry) instance.company_size = validated_data.get('company_size', instance.company_size) instance.client_name = validated_data.get('client_name', instance.client_name) instance.contact_no = validated_data.get('contact_no', instance.contact_no) instance.mobile_no = validated_data.get('mobile_no', instance.mobile_no) instance.email_id = validated_data.get('email_id', instance.email_id) instance.client_logo = validated_data.get('client_logo', instance.client_logo) instance.client_code = validated_data.get('client_code', instance.client_code) instance.save() billing_method.billing_name = billing_method_data.get('billing_name', billing_method.billing_name) billing_method.description = billing_method_data.get('description', billing_method.description) billing_method.save() # product.product_name = product_data.get('product_name', product.product_name) # product.save() product_data = validated_data.pop('product', []) instance = super().update(instance, validated_data) for products_data in product_data: product = Product.objects.get(pk=products_data.get('product_id')) product.product_name = products_data.get('product_name', product.product_name) instance.product_data.add(product) instance.save() return instance When … -
Django makemirgations not updating database
When I make changes to models.py, I am expecting django to update the database structure for me when I run python3 manage.py makemigrations or python3 manage.py makemigrations appname. It doesn't detect any changes. I have had this issue once before and had to delete everything in the database to update it, which seems a bit drastic. What am I doing wrong? This is the new line I have just added: l3_interfaces = JSONField (py38-venv) [xxxxxx@xxxxxxn]$ python3 manage.py makemigrations No changes detected Contents of models.py from django.db import models #Generic for models from django.contrib.auth.models import User #Required for dynamic user information from django.forms import ModelForm #Custom form from jsonfield import JSONField #Unique order. Top of heirachy tree class Order(models.Model): order_name = models.CharField(max_length=100, unique=True)#, null=True, blank=True) #Unique name of order created_by = models.ForeignKey(User, related_name='Project_created_by', on_delete=models.DO_NOTHING) #Person who created the order created_at = models.DateTimeField(auto_now_add=True) #Date/Time order was created def __str__(self): return self.order_name #For CE router definition. Required for all orders. class Ce_Base(models.Model): #Hardware models of router ROUTER_MODELS = ( ('CISCO2901', 'CISCO2901'), ('ISR4331', 'ISR4331'), ('CISCO1921', 'CISCO1921'), ('ISR4351', 'ISR4351'), ('ISR4451', 'ISR4451'), ('ISR4231', 'ISR4231'), ('ISR4431', 'ISR4431'), ('ISR4461', 'ISR4461'), ) #Available regions in which the router can reside. REGION = ( ('1', '1'), ('2', '2'), ('3', '3'), …