Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sending Django celery task to AWS GPU
I have a question related to designing the backend and frontend of an application that I'm currently working on. Although this might be more suited to AWS, I am asking here first because the community is great and very helpful. I have developed an application that works well locally, but now I want to move it to the cloud. I'm facing some issues while doing so. The application is standalone and requires GPU for the celery task. The task is initiated when the user uploads an image, and once it's done, everything is saved and the GPU machine is turned off. However, the application needs to run continuously without requiring the GPU. The user should be able to login and see the dashboard and upload job process data anytime. How can I achieve this? Should I separate my application into two parts? I have researched and found that many people suggest using AWS API, but before doing so, I need to know how to make a setup for it. Has anyone done this combination of Django and AWS before? If not, what are you using for your ML inferences in production? My appliction is working well in laptop. how to … -
Django OSError: [Errno 22] Invalid argument in \\.venv\\Lib\\site-packages\\admin_tools
I have cloned a Django project from Gitlab repository and I get this error when I try to run the server. OSError: [Errno 22] Invalid argument: 'C:\\Users\\irina\\project\\.venv\\Lib\\site-packages\\admin_tools\\theming\\templates\\admin:admin\\base.html' Dependencies are installed via poetry. I think the error is due to the encoding. How can this be fixed? I'm working on Windows 11. -
Django Celery not able to fetch data from particular DB schema
We are facing the issue fetching the data from particular schema's table which is available and the data fetching issue occurs intermediately after few hours of restart of supervisorctl where celery worker is defined. Below is the code mentioned: with schema_context("public"): try: client = Client.objects.get(subdomain=hostname) except ObjectDoesNotExist: client = Client.objects.using("paid").get(subdomain=hostname) Also i have set the connection to particular schema using schema_context function. We have rabbitmq as middleware and we have 3 different queues set and this problem occurs in all queues. we are using libraries celery==4.4.7 django-celery==3.3.0 -
Why can't we view Google Drive public file for longer without getting 403 Forbidden Error?
I am working on a Django project where I allow user to upload their images on google drive with public access and then I display all the uploaded images user-wise. Everything done, I can create folder, and then uploading file in it and getting the file-id. But on viewing that image, I have stucked badly. I have used so many ways not to get a 403 Forbidden Error but still no success! https://drive.google.com/file/d/{file-id}/preview https://drive.google.com/uc?id={file-id}&export=download https://drive.google.com/uc?export=view&id={file-id} File (which is just an image) I can view only few times but then I starts getting this annoying 403 forbidden error. I am really frustrated with this error, please help. -
how to solve 'Error Dict' object is not callable error [closed]
views.py from django.contrib import messages from django.shortcuts import render, redirect from clgapp.forms import StudentForm def student_form(request): if request.method == 'POST': form = StudentForm(request.POST) if form.is_valid(): form.save() messages.success(request, "order confirmed") return render(request,'student_form.html',{'form': form}) else: form.errors() else: form = StudentForm() return render(request, 'student_form.html', {'form': form})` -
django.server logs are not shown in CloudWatch - Using Zappa
My django application is running on AWS Lambda with zappa. I recently added the following to configure logs. LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": { "require_debug_false": { "()": "django.utils.log.RequireDebugFalse", }, "require_debug_true": { "()": "django.utils.log.RequireDebugTrue", }, "filter_user_id": {"()": "<path_to>.UserIdFilter"}, }, "formatters": { "django.server": { "format": "[%(asctime)s] %(message)s user_id:%(user_id)s ", } }, "handlers": { "console": { "level": "INFO", "filters": ["require_debug_true"], "class": "logging.StreamHandler", }, "django.server": { "level": "INFO", "class": "logging.StreamHandler", "formatter": "django.server", }, }, "loggers": { "django": { "handlers": ["console"], "level": "INFO", }, "django.server": { "handlers": ["django.server"], "filters": ["filter_user_id"], "level": "INFO", "propagate": False, }, }, } This is working well when I run this on docker / local server. But when I deployed this to AWS Lambda it is not showing the corresponding logs in the Cloudwatch. Could anyone help? Thanks in advance. -
Creating and Sending PDF file directly to printer without print preview in react and django?
here is any chance to Creat Pdf file and Send PDF file directly to printer without open print preview?? currently! i am able to create pdf and save it in my local.And im also able to print once pdf file is created by opening pdf. Here what im looking for: Generate pdf first and save it to my local and it should be print to my printer once pdf file is created without opening print preview window. what i tried: currently i am able to generate pdf and print them as well by open pdf file form my local. here is my sample code for pdf functionality: model.py: class OrderTransactionPDF(models.Model): pdf_file = models.FileField(blank=True, null=True, validators=[FileExtensionValidator( allowed_extensions=['pdf'])]) transaction_time = models.DateTimeField(default=datetime.datetime.utcnow()) view.py: @csrf_exempt def search_pdf(request): if request.method == "GET": from_date = request.GET.get('from_date') to_date = request.GET.get('to_date') pdf_url_list = [] from_date = datetime.strptime(from_date, '%Y-%m-%d') to_date = datetime.strptime(to_date, '%Y-%m-%d') from_date = datetime.combine(from_date.date(), time(0, 0, 0, tzinfo=pytz.timezone('UTC'))) to_date = datetime.combine(to_date.date(), time(23, 59, 59, tzinfo=pytz.timezone('UTC'))) order_transaction_pdfs = OrderTransactionPDF.objects.filter( transaction_time__range=[from_date, to_date] ).order_by('-transaction_time') for pdf in order_transaction_pdfs: pdf_url_list.append({ 'pdf_url': pdf.pdf_file.url, 'transaction_time': pdf.transaction_time }) return JsonResponse({'pdf_url_list': pdf_url_list}, safe=False) urls.py: path('generate_pdf', generate_pdf), js code: const handleViewOrder = async () => { try { const response = await fetch('/generate_pdf', { method: 'POST', … -
Is there a way to add formset in django-admin without using inline?
I have a model called Employee which is defined as follows: class Employee(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField("Name", max_length=255) address = models.CharField("Address", max_length=255) department = models.ForeignKey(Department, on_delete=models.SET_NULL) team = models.ForeignKey(Team, on_delete=models.SET_NULL) position = models.ForeignKey(Position, on_delete=models.SET_NULL) Is there a way to add multiple name and address of employee for the same department, team and position in django-admin form? I want something like formset including fields name and address for the model Employee where you can enter the department, team and postion and just add the formsets multiple times like how you would do for inlines. I have not tried anything as of yet. -
Duplicate entries in admin view due to M2M field
class User(AbstractBaseUser): organizations = models.ManyToManyField(Organization) facilities = models.ManyToManyField(Facility) class Organization(models.Model): ..fields here class Facility(models.Model): ..fields here Whenever I enter multiple entries for organization the user value is duplicated that many times in the admin view list, but not for facility. -
Django forms not rendering CharFields
In my Django form, only CharFields are exclusively not showing up. Other fields work just fine (e.g. the EmailField and a TurnstileField using django-turnstile). I cannot figure out why. I followed the Django docs and tried to build a form. Code is as follows: auth.html {% block body %} <form action="https://artimaths.com/auth/{{ action }}/" method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {% endblock %} views.py from django.core.exceptions import ValidationError from django.http import HttpResponse, HttpResponseRedirect from django.core.mail import send_mail from django.template import loader from .models import Member from .forms import SignupForm, LoginForm from modules import context import hashlib import re def signage(request, action): t = loader.get_template("auth.html") if action != "register" and action != "login" and action != "logout": return HttpResponse(STATUS_DICT[str(400)] + str(400)) if action == "register": req_context["form"] = SignupForm req_context["form_class"] = SignupForm elif action == "login": req_context["form"] = LoginForm req_context["form_class"] = LoginForm if req_context["status"] is not 200: return HttpResponse(STATUS_DICT[str(req_context["status"]) + req_context["status"]]) return HttpResponse(t.render(req_context, request)) forms.py from django import forms from turnstile.fields import TurnstileField from .models import Member class SignupForm(forms.Form): username = forms.CharField(label="Username"), password = forms.CharField(label="Password"), email = forms.EmailField(label="Email") terms = forms.BooleanField(label="I agree with the Terms of Service and Privacy Policy of Artimaths") captcha = TurnstileField(theme="dark", size="compact") class Meta: … -
How to make multiple post requests with one button handler in React?
I am trying to generated PDF for my application.Pdf functionality is working well.I have two PDF functionality for post request which is seperate right now.Those two PDF post functionality is setting up two indivisual button handler. Ex1: const handleViewOrder = async () => { const response = await fetch('/generate_pdf', { method: 'POST', headers: { 'Content-Type': 'application/json', }, }); } Ex2: const handleProductSellsPdf = async () => { const response = await fetch('/**generate_item_pdf**', { method: 'POST', headers: { 'Content-Type': 'application/json', }, }); what im trying now that,combine those Ex1 and Ex2 in one button handler and generate pdf once i click button. backend code is working fine. problem is that i dont know how to do it in in react/java script. any suggestion please this is my code of pdf generate functionality for diffrent button handler in react : const handleViewOrder = async () => { try { const response = await fetch('/generate_pdf', { method: 'POST', headers: { 'Content-Type': 'application/json', }, }); const responseData = await response.json(); const pdfURL = responseData.pdf_url; localStorage.setItem("pdf_url",pdfURL) window.open(pdfURL, '_blank'); if (!response.ok) { throw new Error('Network response was not ok'); } } catch (error) { console.error('Error fetching data:', error); } }; const handleProductSellsPdf = async () => … -
How to set a (Django) celery beat cron schedule from string value
I am using Django with celery beat. I would like to configure the cron schedule via env var (string value of the cron). We are currently setting the cron schedule like this, using celery.schedules.crontab: CELERY_BEAT_SCHEDULE = { "task_name": { "task": "app.tasks.task_function", "schedule": crontab(minute=0, hour='1,3,5,13,15,17,19,21,23'), }, } I would like to configure the schedule by passing a crontab in string format, like this: CELERY_BEAT_SCHEDULE = { "task_name": { "task": "app.tasks.task_function", "schedule": '0 15 10 ? * *', }, } However, I cannot find any documentation for how I can do this. The naive attempt above does not work. I could parse the cron string into minute/hour/day etc values, and then pass them into crontab with the relevant kwargs, but that feels quite messy. It seems there should be an elegant way to do this. -
Django Form inital values don't work on render
I have a model `Transaction' and ModelForm to create one : class Transaction(models.Model): """ Invoice model. Represents a basic income/outcome transaction. """ title = models.CharField(max_length=32, verbose_name="Title") category = models.ForeignKey(Category, related_name="transactions", on_delete=models.CASCADE, null=True, blank=True) operation = models.CharField(max_length=8, choices=OPERATION_TYPE, verbose_name="operation") value = models.DecimalField(max_digits=14, decimal_places=2, verbose_name="value") currency = models.CharField(max_length=3, choices=CURRENCY_CHOICE, verbose_name="currency") comment = models.CharField(max_length=255, null=True, blank=True) date_created = models.DateField(auto_now_add=True, blank=True, null=True) class Meta: verbose_name_plural = "Transactions" ordering = ["-date_created"] class NewInvoiceForm(forms.ModelForm): category = TreeNodeChoiceField(queryset=Category.objects.all()) class Meta: model = Transaction fields = ("title", "category", "operation", "value", "currency") help_texts = { "operation": _("Money spent/received. For expenses use a negative value.") } I have a Preference model linked with each user to store settings : class Config(models.Model): """ Represents user's preferences. """ user = models.OneToOneField(CustomUser, related_name="config", on_delete=models.CASCADE) currency = models.CharField(max_length=3, choices=CURRENCY_CHOICE, default=DEFAULT_SETTINGS["currency"]) language = models.CharField(max_length=56, choices=LANGUAGE_CHOICE, default=DEFAULT_SETTINGS["language"]) class Meta: verbose_name = "config" verbose_name_plural = "configs" I'm trying to get user's currency from Config model as initial value for Transaction creation form. But initial value never renders. My view : def create_transaction_view(request): if request.method == "POST": form = NewInvoiceForm( request.POST, instance=request.user ) if form.is_valid(): new_invoice = Transaction(**form.cleaned_data) # retrieving user's currency preference for further converting if income is different from base currency user_currency = request.user.config.currency # performing … -
Discretization of Multiple Time Series [closed]
I'm working on discretizing multiple time series for a project. Here's what I've done so far: I concatenated the train signals like this: [1,2,3,5] and [7,3,6,7] into [1,2,3,5,7,3,6,7]. Then, I trained a K-means ML model with the single, combined signal. Finally, I clustered all the signals with the trained model. I'm not sure if this is the right approach. I chose to concatenate the signals because the k-mean (from scikit-learn) allows inserting only a single array, so I didn't know how to feed it with multiple time series. Has anyone done something similar, or does anyone have suggestions for a better discretization method? -
Computing AUC and ROC curve with micro and macro - average on multi-class data in Scikit-Learn
I am computing and plotting AUC and ROC curves for multi-class data for the output of 3 different classifier. I want to see the difference in using micro and macro average on plotting ROC curves in a multi-class setting. I am following the code provided on scikit-lean in OvR (one versus rest) scenario. However, the macro-average ROC curves do not look right, sice some are not starting from (0,0) position. Below, graph shows the performance of Random Forest trained on 3 different augmented datasets macro-average ROC (NOT right) Whereas, the same classifier with ROC plotted using micro-average do not show the same problem. micro-average ROC curve (starts from Zero) I Have also other examples from other datasets using different classifiers (NB and DT) as the following one: macro-average ROC curve (NOT right) For plotting the curves with micro and macro average I used the following code, where: model_proba = contains aggregated predicted probabilities from a 10-CV classes = sorted(list(np.unique(y_test))) print('Sorted:',classes) n_classes = len(np.unique(y_test)) y_test_binarize = label_binarize(y_test, classes=classes) print('Binarized:',y_test_binarize) #y_test_binarize = label_binarize(y_test, classes=np.arange(classes)) scores = {} for model_name, model_proba in d_probabilities.items(): #iterating over 3 probabilities of 3 models y_pred = model_proba scores[model_name] = model_proba fpr ,tpr ,roc_auc ,thresholds = dict(), dict(), … -
Django - Moving some logic from viewsets to a model or model method in viewsets
I have a small educational project of a social network. There's a Recipes and ShoppingCart models. Besides other functionalities, RecipeViewSet allows users to download a file with the ingredients of recipes previously added to the shoppingcart. This part of the RecipeViewSet looks like this: @action( detail=False, methods=['GET'], permission_classes=[IsAuthenticated] ) def download_shopping_cart(self, request): user = self.request.user if not user.shoppingcarts.exists(): raise ValidationError('The shopping cart is empty.') return FileResponse( get_shopping_list( user_cart=user.shoppingcarts.all() ), as_attachment=True, filename='shopping list ' + dt.now().strftime('%d-%m-%Y') + '.txt', ) The function that forms the list of ingredients for downloading looks like this: def get_shopping_list(user_cart): ingredient_name = 'recipe__recipe_ingredients__ingredient__name' ingredient_unit = ( 'recipe__recipe_ingredients__ingredient__measurement_unit' ) ingredient_amount = 'recipe__recipe_ingredients__amount' amount_sum = 'recipe__recipe_ingredients__amount__sum' ingredients = user_cart.select_related('recipe').values( ingredient_name, ingredient_unit ).annotate(Sum(ingredient_amount)).order_by(ingredient_name) recipes = [f'"{recipe.recipe.name}"' for recipe in user_cart] ingredients_list = [ (f'{number}. {ingredient[ingredient_name].capitalize()} ' f'({ingredient[ingredient_unit]}) - ' f'{ingredient[amount_sum]}') for number, ingredient in enumerate(ingredients, 1) ] return '\n'.join(['Recipes:', *recipes, 'To buy:', *ingredients_list]) I want to move some of the logic (the first half of the function) that is not directly related to forming the text out of the get_shopping_list function and transfer it to a model. Therefore, my questions are, which model is better to move it to, ShoppingCart or Recipe and why? And how can this be implemented? -
Adding restriction on who can access form submission information on Wagtail CMS
I have a form page in my web application that is using Django and Wagtail. Is there a way to have a way to restrict or manage which Wagtail users can access the form submission data? Thank you So far I can't find anything that will help me answer my question rather than adding permission in the code base -
Django UserCreationForm Meta fields
I created customized usercreationform class RegisterForm(UserCreationForm): class Meta: model = Users #personal User model fields = ( "username", "first_name", "last_name", "email", "adresse", "phonenumber", ) The simple question is if it works without "password1", "password2" in fields? class RegisterForm(UserCreationForm): class Meta: model = Users #personal User model fields = ( "username", "first_name", "last_name", "email", "adresse", "phonenumber", "password1", "password2", ) if both work, what is the difference between two? -
When trying to access files throug sftp request takes too long and hangs the server
I am using a server to store my files, and I have employed storages.backends.sftpstorage.SFTPStorage to manage URLs, downloads, and uploads. However, I occasionally encounter the following issue when I try to get files from server, causing the entire server to hang and become temporarily unavailable. My error log. My sftp configuration SFTP_STORAGE_HOST = "host" SFTP_STORAGE_ROOT = "/Files" SFTP_STORAGE_UID = 1000 SFTP_STORAGE_PARAMS = { "username": "username", "password": "password", "port": 5522, "timeout": 4, "banner_timeout": 1, "auth_timeout": 1, "channel_timeout": 4, } My view to access files: def get(self, request, name=None, *args, **kwargs): """Only for SFTP users.""" SFS = SFTPStorage() if SFS.exists(name): file = SFS._read(name) type, encoding = mimetypes.guess_type(name) response = HttpResponse(file, content_type=type) response["Content-Disposition"] = 'attachment; filename="{filename}'.format(filename=name) return response raise Http404 I tried to set timeouts, but they didn't help much. -
How to Modify Base Class to Dynamically Instantiate Appropriate Subclass Without Causing Recursion?
I am refactoring a Python class structure where I previously instantiated subclasses directly, but now I want to shift to a design where I only call a base generator class, and this base class internally decides and returns the appropriate subclass instance. However, I'm encountering a recursion problem with this new approach. My code is: class BaseGenerator: def __new__(cls, *args, **kwargs): if cls is BaseGenerator: subclass = cls._determine_subclass(*args, **kwargs) return subclass(*args, **kwargs) else: return super().__new__(cls) @staticmethod def _determine_subclass(*args, **kwargs): # Logic to determine the appropriate subclass # ... class ChildGenerator1(BaseGenerator): pass class ChildGenerator2(BaseGenerator): pass class ChildGenerator3(BaseGenerator): pass Initially, I had a structure with one base generator class (BaseGenerator) and several subclasses (ChildGenerator1, ChildGenerator2, ChildGenerator3). I used to instantiate these subclasses directly like this: generator = ChildGenerator1(...) Now, I want to only use the BaseGenerator to decide and instantiate the correct subclass. I tried implementing this logic in the new method of BaseGenerator, but this leads to a recursion issue now I'm calling the generator like this: generator = BaseGenerator(...) The problem is that when BaseGenerator redirects to a subclass, it somehow causes a recursion issue. How can I modify this approach to dynamically instantiate the correct subclass from BaseGenerator without … -
Use non standard locale code in Django i18n
Can we use a non-standard locale code in Django ? I want to use es-lat because in the film industry, the distinction is made between Spanish (es from Spain) and Latin American Spanish. So far it seems to work with this settings LANGUAGE_CODE = "fr" TIME_ZONE = "UTC" LANGUAGES = [ ("fr", _("French")), ("es", _("Spanish")), ("es-lat", _("Latin American Spanish")), ("en", _("English")), ] But this piece of code in the templates treat es-lat as es. {% get_current_language as CURRENT_LANGUAGE %} {% get_available_languages as AVAILABLE_LANGUAGES %} {% get_language_info_list for AVAILABLE_LANGUAGES as languages %} {{ languages }} # [{'bidi': False, 'code': 'fr', 'name': 'French', 'name_local': 'français', 'name_translated': 'Francés'}, {'bidi': False, 'code': 'es', 'name': 'Spanish', 'name_local': 'español', 'name_translated': 'Español'}, {'bidi': False, 'code': 'es', 'name': 'Spanish', 'name_local': 'español', 'name_translated': 'Español'}, {'bidi': False, 'code': 'en', 'name': 'English', 'name_local': 'English', 'name_translated': 'Inglés'}] -
I am running myapp\urls.py and getting an error
an error is returned the traceback is django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I was expecting myapp\urls.py to run successfully -
Error when trying to run Python / Django project on Docker: "Server Do53:127.0.0.11@53 answered The DNS operation timed out."
I am attempting to run a Python / Django project within Docker. After running docker compose up, things start off alright but then crash out: ... web-1 | [2024-01-09 14:45:03 +0000] [158] [INFO] Booting worker with pid: 158 web-1 | [2024-01-09 14:45:03 +0000] [159] [INFO] Booting worker with pid: 159 web-1 | [2024-01-09 14:45:07 +0000] [133] [ERROR] Exception in worker process web-1 | Traceback (most recent call last): web-1 | File "/usr/local/lib/python3.9/site-packages/eventlet/support/greendns.py", line 491, in getaliases web-1 | return resolver.getaliases(host) web-1 | File "/usr/local/lib/python3.9/site-packages/eventlet/support/greendns.py", line 422, in getaliases web-1 | ans = self._resolver.query(hostname, dns.rdatatype.CNAME) web-1 | File "/usr/local/lib/python3.9/site-packages/dns/resolver.py", line 1364, in query web-1 | return self.resolve( web-1 | File "/usr/local/lib/python3.9/site-packages/dns/resolver.py", line 1321, in resolve web-1 | timeout = self._compute_timeout(start, lifetime, resolution.errors) web-1 | File "/usr/local/lib/python3.9/site-packages/dns/resolver.py", line 1075, in _compute_timeout web-1 | raise LifetimeTimeout(timeout=duration, errors=errors) web-1 | dns.resolver.LifetimeTimeout: The resolution lifetime expired after 5.402 seconds: Server Do53:127.0.0.11@53 answered The DNS operation timed out.; Server Do53:127.0.0.11@53 answered The DNS operation timed out.; Server Do53:127.0.0.11@53 answered The DNS operation timed out. I do not understand the meaning of the final error: dns.resolver.LifetimeTimeout: The resolution lifetime expired after 5.402 seconds: Server Do53:127.0.0.11@53 answered The DNS operation timed out. I am running Docker v24.0.7 on … -
How does scikit's RFECV class compute cv_results_?
From my understanding of sklearn.feature_selection.RFECV (Recursive Feature Elimination Cross Validation), you provide an algorithm which is trained on the entire dataset and creates a feature importance ranking using attributes coef_ or feature_importances_. Now with all features included, this algorithm is evaluated by cross validation. Then the feature ranked at the bottom is removed and the model is retrained on the dataset and creates a new ranking, once again assessed by cross validation. This continues until all but one feature remain (or as specified by min_features_to_select), and the final number of features chosen depends on what yielded the highest CV score. (Source) The CV score for each number of features is stored in rfecv.cv_results_["mean_test_score"], and I've been facing trouble trying to replicate these scores without using scikit's built in method. This is what I have tried to obtain the score for n-1 features, where n is the total number of features. from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import StratifiedKFold from sklearn.model_selection import cross_validate from sklearn.feature_selection import RFECV alg = DecisionTreeClassifier(random_state = 0) cv_split = StratifiedKFold(5) # train is a pandas dataframe, x_var and y_var are both lists containing variable strings X = train[x_var] y = np.ravel(train[y_var]) alg.fit(X, y) lowest_ranked_feature = np.argmin(alg.feature_importances_) … -
Database: best way to *flag a specific link* within a many-to-many relationship?
Take for example a classical student and teacher many-to-many relationship: Table "student": id, name Table "teacher": id, name Table "student_teacher": id, student_id, teacher_id, relation_quality I need to add the concept that a student has a "referent teacher": in other words, to "flag" one relation with teachers as specific, for every student. I see three possible methods: add a one-to-many relation between teacher and students add one-to-one relationship between student and student_teacher add field "is_referent" to "student_teacher", setting it to True when appropriate With option 1, the link table student_teacher is "bypassed", which in my case would require some 'constraint' against setting a teacher as referent without any relation between student and teacher through the many-to-many path. Generating SQL queries to get the corresponding "relation_quality" does not appear too hard (we would have the two required FKs at hand), but I am not sure that it would not complicate my existing Django templates; With option 2 (which I am currently using), the 'constraint' to ensure is again that a student cannot connect to a 'referent' through an entry of the link table to which she/he is not related (i.e. a link used for another student). Maybe more importantly, it "looks more …