Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why my menus are not showing in internal pages?
I am new to Django and I created category, Subcategory in my Django app, but the main issue is this my all category and subcategory are showing on home page view, but when i click on any subcategory it's open new page, then nothing is showing in menus. All category and subcategory are hiding from navigation. Please let me know what is this issue, I am unable to solve this issue. -
How can I install MySQLClient?
This is for a starter Django project. I've installed the virtual enviroment and run the server. Now the tutorial I'm using recommends that I install mysqlclient instead of the pre-installed sqllite3 and I want to follow allong exactly. I run the command pip install mysqlclient and get the following output: Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/4d/38/c5f8bac9c50f3042c8f05615f84206f77f03db79781db841898fde1bb284/mysqlclient-1.4.4.tar.gz Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'c:\users\alex\envs\py1\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Alex\\AppData\\Local\\Temp\\pip-install-7u7ymyig\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\Alex\\AppData\\Local\\Temp\\pip-install-7u7ymyig\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\Alex\AppData\Local\Temp\pip-wheel-ya5ndkrz' --python-tag cp37 cwd: C:\Users\Alex\AppData\Local\Temp\pip-install-7u7ymyig\mysqlclient\ Complete output (30 lines): running bdist_wheel running build running build_py creating build creating build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension creating build\temp.win32-3.7 creating build\temp.win32-3.7\Release creating build\temp.win32-3.7\Release\MySQLdb E:\Programs\VisualStudio\VC\Tools\MSVC\14.22.27905\bin\HostX86\x86\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -Dversion_info=(1,4,4,'final',0) -D__version__=1.4.4 "-IC:\Program Files (x86)\MySQL\MySQL Connector C … -
Permission classess decorator is ignored. "Authentication credentials were not provided" response
I am using Django Rest Framework for my API service. In my settings.py I've got following REST_FRAMEWORK setting: REST_FRAMEWORK = { ... 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated' ) ... } Now I want to change permission classes to allow anyone to use one view. I had used @permission_classes decorator. class UserViewSet(viewsets.ModelViewSet): serializer_class = RegisterSerializer queryset = User.objects.all() @permission_classes([permissions.AllowAny,]) def create(self, request, *args, **kwargs): data = request.data ... I should be able to perform create action without any permissions. Instead I receive Authentication error when try to access the API. "detail": "Authentication credentials were not provided." According to docs @permission_classes decorator is correct way for such permission overriding. This is Django 2.2.4 and DRF 3.10.2. -
Python3 Django: Getting Invalid Salt Error Bcrypt
I'm making a miniter. I'm making an api by encrypting password, and I'm testing it with httpie. In bcrypt.checkpw(password.encode('UTF-8'), account_exists_id.get().password.encode("UTF-8") is There is an invalid salt error. How do you approach it? Actually, I encrypted my password and put it in db, but I don't know how to test it yet. class login_post(View): def post(self, request): data = json.loads(request.body) user_id = data['user_id'] password = data['password'] account_exists_id = Account.objects.filter(user_id = data['user_id']) if account_exists_id.exists() and bcrypt.checkpw(password.encode('UTF-8'), account_exists_id.get().password.encode("UTF-8")): user_id = account_exists_id.get().user_id payload = { 'user_id': user_id, 'exp' : datetime.utcnow() + timedelta(seconds = 60 * 60 * 24) } token = jwt.encode(payload, 'SECRET_KEY') return JsonResponse({"access_token" : token.decode('UTF-8')}) else: return JsonResponse(status = 401) Traceback (most recent call last): File "/home/gapgit/miniconda3/envs/api01/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/gapgit/miniconda3/envs/api01/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/gapgit/miniconda3/envs/api01/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/gapgit/miniconda3/envs/api01/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/gapgit/miniconda3/envs/api01/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/home/gapgit/miniconda3/tweet_copy/tweet_project/login/views.py", line 25, in post if account_exists_id.exists() and bcrypt.checkpw(password.encode('UTF-8'), account_exists_id.get().password.encode("UTF-8")): File "/home/gapgit/miniconda3/envs/api01/lib/python3.7/site-packages/bcrypt/init.py", line 107, in checkpw ret = hashpw(password, hashed_password) File "/home/gapgit/miniconda3/envs/api01/lib/python3.7/site-packages/bcrypt/init.py", line 86, in hashpw raise ValueError("Invalid salt") -
Toggle Image On-click Using JavaScript/Jquery in list of divs
I am new to web language and need help with toggling image. So I have a list of divs displaying images, and the source of the image is from a database. I want the image to toggle in a way to replace the url from the database with another url from the same database table (e.g. switch before_url to after_url). I have tried a few ways and the closest I got is click on one image, but it updates for all elements.. The code below is something I've tried (yes I'm trying to toggle by clicking button) some CSS: .card { box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2); padding: 16px; } .card:hover { box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2); } HTML: <div class="row"> {% for c in card_list %} <div class="column"> <div class="card"> <img class="myCard_before" src="{{ c.img_url_before }}" style="width:100%;" /> <img class="myCard_after" src="{{ c.img_url_after }}" style="width:100%;display:none" /> <div class="container"> <h4>{{ c.card_title }}</h4> <input class="button" type="button" onclick="changeImg1() "value="before" /> <input class="button" type="button" value="after" /> </div> </div> </div> {% endfor %} </div> JS: <script> var elements = document.getElementsByClassName("card"); console.log(elements); for(var i = 0; i < elements.length; i++) { elements[i].onclick = function(event) { this.classList.toggle('red'); this.classList.toggle('myCard_afterEvol'); } } function changeImg1() { for (var i = … -
How to convert "127.0.0.1:8080" to www.projectname.com" on local?
How can i change URL django running server from 127.0.0.1:8080 to http://www.projectname.com ? -
AJAX Django Delete Function is Not Deleting the Object
I am trying to delete an object with a close button and it was working without using AJAX but I had to reload the page in order to reflect some changes in my methods. When I applied AJAX, it was no longer deleting. views.py elif request.method == 'DELETE': id = json.loads(request.body)['id'] project = get_object_or_404(Project,id=id) project.delete() return JsonResponse('') profile.html <a onclick="deleteProject(this)" data-id="{{project.id}}" class="close col-sm-2" aria-label="Close"> <span class="card-block float-right" aria-hidden="true">&times</span> </a> ... <script> $(document).on('.close',function(e){ e.preventDefault(); $.ajax({ type:'DELETE' url:'user/profile' data: { 'id' : id } success: function deleteProject(e) { let id = e.dataset.id e.closest('li').remove() fetch('',{ method: 'DELETE', headers: { 'X-CSRFToken': '{{ csrf_token }}' }, body: JSON.stringify({ 'id': id }), credentials: 'same-origin', }) } }); }); </script> Is there something wrong with the way I am using AJAX with Django? It works when I just keep everything from "function deleteProject(e)..." but I don't want to have to reload the page to show how the number of projects and total budget changes. Is there a way I can fix this or maybe an alternative to using AJAX? -
How to perform CRUD operations in mysql django project?
Please post a code for performing the crud operations in django with mysql database ... Add Upadate Delete Create -
How can I reload python code in dockerized django?
I am using docker-compose to run 3 containers: django + gunicorn, nginx, and postgresQL. Every time I change my python .py code, I will run docker-compose restart web but it takes a long time to restart. I try to restart gunicorn with docker-compose exec web ps aux |grep gunicorn | awk '{ print $2 }' |xargs kill -HUP . But it didn't work. How can I reload .py code in a shorter time? I know that gunicorn can be set to hot reload python code. Can I do it manually with a command? -
Is it able to build models like this by using django rest framework?
I want to builds some models like these: tbl_Book: ID Title Author Category 1 Lazy Ant Tom Story 2 Python3 for beginner Sam IT 3 Knowledge about Cat & Dog Kay Animal tbl_Story: ID BookID AgeRangeID 1 1 3 2 1 4 tbl_IT: ID BookID Language 1 2 Python tbl_Animal: ID BookID AnimalType 1 3 Cat 2 3 Dog will have more categories…. And when I make a post call, the content will be something like: {"Title":"Lazy Ant","Author":"Tom","Category":"Story","story_content":[{"AgeRangeID":3},{"AgeRangeID":4}]} I have checked some about foreignkey, relation and join but seems not match with what I want. Currently I have in models.py: class Book(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) author = models.CharField(max_length=50) Category= models.CharField(max_length=20) class Meta: db_table = "tbl_Book" def __str__(self): return str(self.id) class Story(models.Model): id = models.AutoField(primary_key=True) book_id = models.ForeignKey(Node,related_name='story_content',on_delete=models.CASCADE,db_column='book_id') AgeRangeID = models.IntegerField(db_column=AgeRangeID') class Meta: db_table = "tbl_Story" in serializer.py: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('id','Title','Author','Category') class StorySerializer(serializers.ModelSerializer): class Meta: model = Story fields = ('id','book_id','AgeRangeID') Please let me know what I should add or correct. -
How to make authentication token available to web based client on future requests? Server is running Django + Django Rest Framework
I've got a nice REST API that I made using django-rest-framework, and interacting with it from a local client is simple - just request a token from the API endpoint and then add that token to the HTTP headers when you make requests using curl or httpie or something. I've written some wrappers that look like so: token = getAPIToken(username, password) data = getDataFromEndpoint(resourceID, token) postDataToEndpoint(resourceID, data, token) My problem is that I can't figure out how to consume this API from the browser or the server. For example, I want the user to be able to POST a form to someView and then have that view conditionally call call one of the aforementioned wrappers. The problem is that the server can't get a token without prompting the user for a password every time - all it knows is the request.user field that Django gave it, and even that only if I have SessionAuthentication enabled. Somehow I need to tell the client to include the "Authorization: Token XXXX" header on every future HTTP request after they log in. One option I've considered: Django's default login view uses sessions, so I suppose I could hack up that view to call my … -
Is there any method which can help me in domain rendering for php to django (python)?
i have a website which is in django(python) excatly like https://www.byond.travel/ now i have another website which is in php https://blog.byond.travel/ now i want to change this php website into (https://www.byond.travel/blog) so what can i do. do i need to config server again or i can render domain in django any suggestions ? -
How to validate and serialize recursive many to many relationship using Django REST framework in a most optimal way?
I have a model CitizenInfo that contains a field 'relatives' with many to many relationship on itself. When i do a POST request what i want is to validate and deserialize the raw data from JSON using the optimal way. What i found so far is a library for recursive model fields. https://github.com/heywbj/django-rest-framework-recursive and this not super informative topic https://github.com/encode/django-rest-framework/issues/4183 This is my POST request: [ { "citizen_id": 1, "name": "Dave", "relatives": [2] }, { "citizen_id": 2, "name": "Jack", "relatives": [1, 3] }, { "citizen_id": 3, "name": "Alex", "relatives": [2] } ] model.py: class CitizenInfo(models.Model): citizen_id = models.PositiveIntegerField(primal_key=True) name = models.CharField(max_length=255) relatives = models.ManyToManyField('self', blank=True) views.py class CitizenInfoImportView(APIView): def post(self, request): # Because of many=True we will use BulkCitizensSerializer serializer = CitizenListSerializer(data=request.data, many=True) if serializer.is_valid(): serializer_response = serializer.save() return Response(status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py # Using this function for bulk_save operation def save_citizens(citizen_data): new_citizen = CitizenInfo(citizen_id=citizen_data.get('citizen_id'), name=citizen_data.get('name')) # Looping through relative list and do some custom serialization for relative in citizen_data.get('relatives'): pass return new_citizen class BulkCitizensSerializer(serializers.ListSerializer): def create(self, validated_data): new_citizens = [save_citizens(citizen_data) for citizen_data in validated_data] return CitizenInfo.objects.bulk_create(new_citizens) class CitizenListSerializer(serializers.ModelSerializer): class Meta: model = CitizenInfo field = '__all__' list_serializer_class = BulkCitizensSerializer Also i had a limit that for one request … -
Obtaining number of errors in template with template tags
I'd like to use a template tag to only show certain html if the form doesn't load with errors. I've got this in def clean(): forms.py home_zipcode = cleaned_data.get('home_zipcode') if ' ' in home_zipcode: self.add_error('home_zipcode', "Please remove all spaces from the Zip Code.") raise forms.ValidationError('Please review the errors below.') template {% if no errors %} some html {% endif %} Do you know what template tag I would use to do this? -
give context to page without render
I am trying to make a help section for my team. I have a form that the person that needs help will fill out, then that data will go to a page only my team my can view to see which one of us will tackle the problem. But, I am having trouble rendering the context of the form to the help page my team can view. right now I am using render(), but when the user clicks submit he/she gets redirected to the page only my team should be able to see. and the data doesn't stay on the page when it is reloaded. here is the views.py def help_form(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = HelpForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required name = form.cleaned_data['your_name'] room_number = form.cleaned_data['room_number'] email = form.cleaned_data['email'] when = form.cleaned_data['when'] subject = form.cleaned_data['subject'] description = form.cleaned_data['description'] context = { 'name': name, 'room_number': room_number, 'email': email, 'when': when, 'subject': subject, 'description': description, } # redirect to a new URL: … -
Using $not $in $regex in PyMongo
I want to do a PyMongo equivalent to vendor NOT IN ('Amazon', 'eBay', 'AliBaba'). I am able to get it to work in MongoDB by doing: 'vendor': {'$not': {'$in': [/^Amazon/, /^eBay/, /^AliBaba/]}} This works. In PyMongo no matter what I try, I am getting no result. It is not throwing any errors but not returning any results either. Here is what I have tried: 1) import re vendor = {'$not': {'$in': [re.compile('^Amazon'), re.compile('^eBay'), re.compile('^AliBaba')]}} 2) import re vendor = {'$not': {'$in': [re.compile('.*Amazon.*'), re.compile('.*eBay.*'), re.compile('.*AliBaba.*')]}} What am I missing? Why can't I get not in work with PyMongo? -
How to fix the " unexpected token ']' " error in python3,django2?
I'm trying to add the module to urls.py. Here's the code: """ Definition of urls for learning_log. """ from datetime import datetime from django.urls import path from django.contrib import admin from django.contrib.auth.views import LoginView, LogoutView from app import forms, views #added from django.conf.urls import include, url import learning_logs.views from django.urls import path,re_path app_name='learning_logs' urlpatterns =[ #added path('', include('learning_logs/urls',namespace='learning_logs'), path('contact/', views.contact, name='contact'), path('about/', views.about, name='about'), path('login/', LoginView.as_view ( template_name='app/login.html', authentication_form=forms.BootstrapAuthenticationForm, extra_context= { 'title': 'Log in', 'year' : datetime.now().year, } ), name='login'), path('logout/', LogoutView.as_view(next_page='/'), name='logout'), path('admin/', admin.site.urls)] The code seems alright,but Visual Studio keeps reporting error: unexpected token ']' It says the last ']' has some problem.But it is part of the grammar. How to solve this problem? -
Why does request.FILES["file"].open() is None, though request.FILES.["file"].name works well?
I'm trying to get image file using ajax into Django views.py. I can print the file name and size of it. But when I open the file, it become None..! The reason I'm trying to open image is to use it for vision analysis. Currently I'm working on Django 1.11, python 3.6.7. Here are some codes. views.py def receipt_ocr(request): if request.method == 'POST': print(type(request.FILES["file"])) #<class 'django.core.files.uploadedfile.InMemoryUploadedFile'> print(request.FILES["file"]) #bank.png print(request.FILES["file"].size) #119227 print(request.FILES["file"].name) #bank.png print(request.FILES["file"].content_type) #image/png print(type(request.FILES["file"].open())) #<class 'NoneType'> print(request.FILES["file"].open()) #None print(type(request.FILES["file"].read())) #<class 'bytes'> imageFile = request.FILES["file"] receipt_image = imageFile.read() print(type(receipt_image)) #<class 'bytes'> print(receipt_image) #b'' ajax part in html $.ajax({ url: "{% url 'ocr:receipt_ocr' %}", enctype: 'multipart/form-data', type: 'POST', cache: false, processData: false, contentType: false, data: postData, complete: function(req){ alert('good'); }, error: function(req, err){ alert('message:' + err); } }); I expected the receipt_image in views.py is binary of the image file. But It's empty. Because request.FILES["file"] is None. I don't know why it's None. Thanks your for reading my question. Hope you have a good day👍 -
How can I change the design of the login screen supported by Django?
I'm making a website with Django The login part uses the functions supported by Django. The design doesn't look very good So I want to improve the login screen How can I fix it? I don't know how I don't know which code in which file should be modified If you know how to fix let me knwo please Thank you site : http://terecal-hyun.co.kr/accounts/login/?next=/ github: https://github.com/hyunsokstar/django_inflearn2 -
Django gallery for loop
I want to have a carousel at the top of each of my product pages. I want it to iterate over every image in a directory I specify. Something like this <div id="carouselIndicators" class="carousel slide carousel-fade z-depth-1-half my-4" data-ride="carousel"> <ol class="carousel-indicators"> {% for image in directory %} <li data-target="#carouselIndicators" data-slide-to="0" class="active"></li> {% endfor %} </ol> <div class="carousel-inner" role="listbox"> {% for image in directory %} <div class="carousel-item active"> <img class="d-block img-fluid" src="/media/54521383_989180831273370_3472797838423883776_n.jpg"> </div> {% endfor %} </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> What I want to learn: How to iterate over images in a gallery with a for loop. Is there a better model field for uploading multiple images? eg. galleries Is there a way I can view said images in the Django admin panel? Rather than just the file name. -
How to prevent a Django view that calls an external api from being flooded when it is called by a GET request?
I am writing a Django application with a view that is passed GET parameters. This view contacts an external API to get information, and passes the consolidated information to a template. The external API call is costly and limited. I am concerned that in a production environment, an attacker could write a script to repeatedly load the page with different parameters, (as I'm caching requests, so repeated calls with same parameters are fine), to exhaust my ability to use the external API. I am trying to ensure that only humans can load my view (or specifically, reach the point of the external API call), or, at least, that a robot can't load it hundreds of times. The most elegant solution would be some code in the view before the API call that could validate the user somehow. If the user failed the validation, they could be referred to another view or to a different template with a failure message. I am trying to do this as elegantly as possible and not be sloppy, however, so I'm looking for advice on best practice. Initially, I intuitively wanted to use reCAPTCHA, however, it seems that this is generally used for forms. Adding … -
Docker-compose running local but not remote
I have the following: Dockerfile # Pull base image FROM python:3.7.3-slim # Set environement variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set working directory WORKDIR /code/ # Update system RUN apt update && apt-get -y update RUN apt -y install mysql-client RUN apt -y install python-dev RUN apt -y install gcc RUN apt -y install default-libmysqlclient-dev # Install dependencies RUN pip install pipenv COPY Pipfile Pipfile.lock /code/ RUN pipenv install --system # Copy project COPY . /code/ # Port to expose EXPOSE 8000 # Command to run the webserver CMD ["gunicorn", "gotrakk.wsgi:application", "--bind", "0.0.0.0:8000"] docker-compose.prod.yml version: '3.7' services: web: build: . image: 734309331381.dkr.ecr.us-west-2.amazonaws.com/keeptrakk:latest command: gunicorn gotrakk.wsgi:application --bind 0.0.0.0:8000 ports: - "8000:8000" volumes: - .:/code env_file: - environment.txt expose: - "8000" nginx: build: ./nginx image: 734309331381.dkr.ecr.us-west-2.amazonaws.com/nginx:latest ports: - 80:80 - 443:443 depends_on: - web This runs fine when I run local with $(aws ecr get-login --no-include-email --region us-west-2) docker-compose -f docker-compose.prod.yml build docker-compose -f docker-compose.prod.yml push docker-compose -f docker-compose.prod.yml up If I log on to my amazon machine and run the container with eval $(docker-machine env keeptrakk) docker-compose -f docker-compose.prod.yml pull docker-compose -f docker-compose.prod.yml up I get the following ModuleNotFoundError Recreating gotrakk_web_1 ... done Recreating gotrakk_nginx_1 ... done Attaching to … -
Is django python a good/reliable framework for a high performance website?
I intend to build a user interactive website where users can interact with other users via forums, chat, and have algorithms that recommened things to users based on their profile and i'm wondering whether django is powerful enough to deal with high demands? Will django be ideal for server demands that are beyond typical? -
TypeError at /accounts/login/ __init__() takes 1 positional argument but 2 were given
I am using the latest version of django and python 3, When I log in I get the below error message. TypeError at /accounts/login/ init() takes 1 positional argument but 2 were given -
How do I represent items of a L-matrix to store comparison of every item in a collection to every other item?
I am building a Prioritization Matrix/Criteria Matrix[1] within an application and would like to represent Criteria as a Django Model. Now according to the requirements, I need to able able to assign a relative value for each Criteria as compared to every other Criteria in the application. What would be the best way for me to express this relationship ? Essentially, I need to be able to say something like: criteria_1 = Criteria(label='Usefulness', ...) criteria_2 = Criteria(label='Cost', ...) ... ... ... something ... ... ... get_relative_importance(criteria_1, criteria_2) == criteria_2 get_relative_importance(criteria_2, criteria_1) == criteria_2 [1] You can think of it as an L-Matrix like the first image on this page