Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to populate choices in a modelchoicefield with a field from another model filtered by logged in user
I'm trying to made a modelform with a modelchoicewidget which inherits its choices from another model than the model the modelform is connected to, and this selection is to be filtered by the current logged in user. The example below illustrates my intentions - let's say I have two different models where one model allows the user to register meal types (breakfast, dinner etc), and the other model allows the user to create specific meals based on those meal types, with the connecting variable being the title of the meal type. models.py: class Mealtypes(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200, default='') description = models.TextField(default='') class Specificmeals(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) meal_name = models.CharField(max_length=200, default='') mealtype = models.CharField(max_length=200, default='') fruit = models.BooleanField(default=False) meat = models.BooleanField(default=False) dairy = models.BooleanField(default=False) forms.py from django import forms from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Mealtypes, Specificmeals class MealAdder(ModelForm): class Meta: model = Specificmeals fields = [ 'meal_name', 'mealtype', 'fruit', 'meat', 'dairy', ] widgets = { 'text': forms.Textarea(attrs={"style": "height:10em;" "width:60em;"}), 'mealtype': forms.ModelChoiceField(queryset=Mealtypes.title.filter(author='author')), 'fruit': forms.CheckboxInput(attrs={"style": "margin-left:350px;"}), 'meat': forms.CheckboxInput(attrs={"style": "margin-left:350px;"}), 'dairy': forms.CheckboxInput(attrs={"style": "margin-left:350px;"}), } I'm trying to play around with the ModelChoiceField to make it query the mealtypes from the Mealtypes model filtered … -
Read from file output to html template in django
How would the solution linked below be written in views.py to read from multiple files and output those various fields? I can make this work for one but if I try copy pasting f = open('path/text.txt', 'r') file_content = f.read() f.close() context = {'file_content': file_content} and changing the letters slightly to have unique versions it seems to break it...I am passing in unique variations not reusing "f" ex: h = open(BASE_DIR, 'path/tofile') file_content = h.read() h.close() context = {'file_contenth': file_contenth} I then pass in to the return return render(request, pathtohtml, {'file_content': file_content}, {'file_contenth': file_contenth} and that "breaks" it. I've tried a few variations of passing those variables in to no avail I used the solution found here Django: Display contents of txt file on the website -
Reverse for 'extranet.views.uutiset_paasivu' not found. 'extranet.views.uutiset_paasivu' is not a valid view function or pattern name
I'm trying update django project from django1.4/python 2.7 to django2.2/python3.7. Now I'm confused with the traceback after pythan manage.py runserver (and after going to page /uutiset/): Internal Server Error: /search/ Traceback (most recent call last): File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\miettinj\osakeekstra\extranet\views.py", line 78, in search { 'query_string': query_string, 'dokut': found_entries }) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\template\base.py", line 171, in render return self._render(context) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\template\base.py", line 937, in render bit = node.render_annotated(context) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\template\base.py", line 904, in render_annotated return self.render(context) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\template\base.py", line 937, in render bit = node.render_annotated(context) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\template\base.py", line 904, in render_annotated return self.render(context) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\template\defaulttags.py", line 443, in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\urls\base.py", line 90, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\urls\resolvers.py", line 660, in … -
django authentication with ldap3
I am testing django_python3_ldap library and using the same ldap server that I found in the tutorial (https://ldap3.readthedocs.io/en/latest/tutorial_intro.html), but there is something which I didn't get right to stablish the connection. Does anyone know what is wrong with these settings configuration? This is the error: "LDAP bind failed: LDAPInvalidCredentialsResult - 49 - invalidCredentials - None - None - bindResponse - None" This is my code in settings.py: AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "django_python3_ldap.auth.LDAPBackend", ] # The URL of the LDAP server. LDAP_AUTH_URL = "ldap://ipa.demo1.freeipa.org" # Initiate TLS on connection. LDAP_AUTH_USE_TLS = False # The LDAP search base for looking up users. LDAP_AUTH_SEARCH_BASE = "uid=admin,cn=users,cn=accounts,dc=demo1,dc=freeipa,dc=org" #"dc=demo1,dc=freeipa,dc=org" # The LDAP class that represents a user. LDAP_AUTH_OBJECT_CLASS = "*" # User model fields mapped to the LDAP # attributes that represent them. LDAP_AUTH_USER_FIELDS = { "username": "sAMAccountName", #"username", "first_name": "givenName", "last_name": "sn", "email": "mail", } # A tuple of django model fields used to uniquely identify a user. LDAP_AUTH_USER_LOOKUP_FIELDS = ("username",) # Path to a callable that takes a dict of {model_field_name: value}, # returning a dict of clean model data. # Use this to customize how data loaded from LDAP is saved to the User model. LDAP_AUTH_CLEAN_USER_DATA = "django_python3_ldap.utils.clean_user_data" # Path to a … -
How to properly delete an instance of a model in Django
I am trying to delete an instance of an event from my calendar. I then want Django to redirect to the calendar page upon deletion of the event. In my views.py, I have defined an event_delete function: def event_delete(request, event_id=None): Event.objects.get(pk=event_id).delete() return HttpResponseRedirect(reverse("cal:calendar")) In my urls.py I have defined a url for deletion: from django.conf.urls import url from . import views app_name = "cal" urlpatterns = [ url(r"^index/$", views.index, name="index"), url(r"^calendar/$", views.CalendarView.as_view(), name="calendar"), url(r"^event/new/$", views.event, name="event_new"), url(r"^event/edit/(?P<event_id>\d+)/$", views.event, name="event_edit"), url(r"^event/delete/$", views.event_delete, name="event_delete"), ] and in my event.html, I have defined an a tag that takes in event_delete: <a class="btn cancel-button buttons login_btn" href="{% url 'cal:event_delete' %}" value="Delete" style="font-family:Optima;">Delete Event</a> When I try to delete an event, it redirects me back to the calendar page but I still see the event. If I try again, it gives me the error DoesNotExist at /event/delete/ Event matching query does not exist. When I check in my admin however, I still see the instance of the event. Please advice as to how I can resolve this. -
Django migrations not working with multiple apps
I have created a project with django which has 2 apps. Each of them has a models.py that I will show below. The problem occurs when I try to launch: python manage.py makemigratios I get the following error: Traceback (most recent call last): File "/home/pablo/.local/share/virtualenvs/portfolio-cTVCjELO/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: no existe la relación «weatherapi_weatherstation» LINE 1: ...gitude", "weatherapi_weatherstation"."token" FROM "weatherap... ... return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: no existe la relación «weatherapi_weatherstation» LINE 1: ...gitude", "weatherapi_weatherstation"."token" FROM "weatherap... ^ The above exception was the direct cause of the following exception: They are two very simple models and everything seems to be correct but it is impossible to launch makemigrations. I have also tried to drop the DB but it is still the same. Settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'portfolio', 'USER': 'pablo', 'PASSWORD': '1234', 'HOST': 'localhost', 'PORT': '5432', } } Models 1: from uuid import uuid1 from django.db import models def generate_uid(): return uuid1().hex # Create your models here. class WeatherStation(models.Model): uid = models.CharField(max_length=32, db_index=True, unique=True, default=generate_uid) name = models.CharField(max_length=256, default="No name") created_at = models.DateTimeField(auto_now_add=True) latitude = models.FloatField() longitude = models.FloatField() token = models.CharField(max_length=40, unique=True,) def __str__(self): return self.name class WeatherRecord(models.Model): created_at = models.DateTimeField(auto_now_add=True) temperature … -
How to filter books by number of editions Django?
models.py class Category(models.Model): image = models.ImageField(upload_to='book_images/category_images') title = models.CharField('Назва', max_length=128) slug = models.CharField(blank=True, max_length=128) class Book(models.Model): image = models.ImageField('Зображення', blank=False, upload_to='book_images') title = models.CharField('Назва', max_length=128) price = models.DecimalField('Ціна', max_digits=6, decimal_places=2) author = models.ForeignKey(Author, on_delete=CASCADE, verbose_name='Автор') edition = models.ForeignKey(Edition, on_delete=CASCADE, verbose_name='Видавництво') category = models.ForeignKey(Category, on_delete=CASCADE, verbose_name='Категорія') I want to display top 3 editions by count of their books. How can I do that? -
failing to create app for django with visual studio
i am failing to create app for Django. i am getting this error "[Errno 2] No such file or directory". i tried the following code:python manage.py startapp cloud.I am still failing. I would appreciate any help. Regards -
django.db.utils.ProgrammingError: set_session cannot be used inside a transaction
I am trying to save objects in DB [obj.save()] with the help of ORMs. But it throws the following error: django.db.utils.ProgrammingError: set_session cannot be used inside a transaction Does any ideas about this error? I am using Django & PostgresDB -
Particular Query from Queryset in Django
I have a model in Django called Accounts which has id, name, email, and balance fields. I want to retrieve the particular dataset when one visits the detail page. Say when I click on the details page I send through a string "name" which contains the name of the user the account is owned by. I am trying to obtain the particular query but to no avail. This is what the Queryset returns on Accounts.objects.all() ==> <QuerySet [<Account: UserA>, <Account: UserB>, <Account: UserC>, <Account: UserD>, <Account: UserE>, <Account: UserF>, <Account: UserG>, <Account: UserH>, <Account: UserI>, <Account: UserJ>]> I have tried Accounts.objects.values().get(id=id) but that provides a dictionary of id, user_id, and balance. I want to access the email of the user as well. I tried Accounts.objects.get(username=name) but it returns the error too many values to unpack. A way to do is Accounts.objects.all()[id] which is cheap and not dynamic since if we delete some users then it wont work. What am I missing here? or what is going wrong here? -
Django: submit only one form created with for loop
In my code I'm using a class CreateView with a ListView. I'm also using a for loop to show all the possible dates available (that are created in the StaffDuty models). My user should be able to just book a single date. My problem is that I'm not able to save a single appointment, I have to compile all the form showed in my list to be able to submit. How can I solve this? models.py class UserAppointment(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) staff = models.ForeignKey(StaffDuty, on_delete=models.CASCADE) event = models.ForeignKey(Event, on_delete=models.CASCADE) event_name = models.CharField(max_length=255) date_appointment = models.DateField(null=True) def __str__(self): return self.event.name | str(self.staff.date_work) def get_absolute_url(self): return reverse('home') views.py class UserAppointmentAddView(CreateView): model = UserAppointment form_class = UserAppointmentForm template_name = "reservation.html" def form_valid(self, form): form.instance.user = self.request.user.userinformation def get_context_data(self, **kwargs): kwargs['object_list'] = StaffDuty.objects.order_by('id') return super(UserAppointmentAddView, self).get_context_data(**kwargs) html <div class="container"> <form method="post"> {% csrf_token %} {% for appointment in object_list %} <span>{{ form.staff }}</span> <span>{{ form.event }}</span> <span>{{ form.morning_hour }}</span> <span>{{ form.afternoon_hour }}</span> <div class="primary-btn"> <input type="submit" value="submit" class="btn btn-primary"> </div> </div> {% endfor %} -
How to inspect query generated by generic CreateView
I have a generic CreateView and it doesn't work as intended. In my db I have a table with composite primary key of two fields. When I try to create more then one instances of this table I get error message 'Order details with this Order already exists.'. Seems like query generated by CreateView is trying to update existing row, but I want it to create new one. It's all my assumptions and I wonder how can I check the exact query generated by Django's ORM. I suppose it's trying to update, not insert. How do I check that? Thanks. If needed, here's the view and model. class OrderDetailsCreateView(LoginRequiredMixin, CreateView): model = OrderDetails template_name = 'orders/orderdetails_create.html' form_class = OrderDetailCreateOrUpdateForm def get_form_kwargs(self, **kwargs): form_kwargs = super(OrderDetailsCreateView, self).get_form_kwargs(**kwargs) emp = get_current_users_employee(self.request.user) last_order = Orders.objects.filter(employee=emp, id=self.kwargs['pk'])[0] last_order_details = OrderDetails.objects.filter(order=last_order).values('product_id') already_selected_products = last_order_details form_kwargs['already_selected_products'] = already_selected_products form_kwargs['emp'] = emp return form_kwargs def form_valid(self, form): return super(OrderDetailsCreateView, self).form_valid(form) class OrderDetails(models.Model): order = models.OneToOneField('Orders', models.DO_NOTHING) product = models.ForeignKey('products.Products', models.DO_NOTHING) unit_price = models.FloatField() quantity = models.SmallIntegerField() discount = models.FloatField() class Meta: managed = False db_table = 'order_details' constraints = [ models.UniqueConstraint(fields=['order', 'product'], name='order-product') ] def get_absolute_url(self): return u'/orders/%d' % self.order.pk -
Running multiple django projects using docker and nginx
I am trying to do the following. I have 3 django projects (NOT apps) (can be more). Proj1: On port 8000, Proj2: 8001, and Proj3:8002 This is what I am trying to achieve: User visits : localhost:8000 All urls under Pr1: Respond User visits: localhost:8000/Pr2 All urls under Pr2: Respond User visits: localhost:8000/Pr3 All urls under Pr3: Respond Goal: Proj 1 is run with Docker and Nginx. Now I have 2 new projects to integrate. Every new sub project should be reached using only one main port (8000). But internally the request is directed towards the correct port of sub-project. Why this goal: Achieve micro-service style structure. Sub projects (2 & 3) can be reached only after authentication through Proj1. What have I tried: Honestly no clear idea where to start. Added new projects to docker-compose...they all work when visited by their own port(localhost:8001/Prj1) .. With nginx, tried adding a new server. No effect: server { listen 4445; location / { proxy_pass http://web_socket:8080; proxy_redirect off; } } -
building an e-learning web site with ontology OWL and Django
i'm actually working on a new project about creating an e-learning platform using ontologies for my final project graduation, i'm absolutely a blank page with the domain! i've started by creating my ontology with the protege editor and actually im trying to display my data on my web site programmed with the django framework which is really difficult ! i have searched about many sites and i did not found anything about owl programming with python and also django ! is there someone who can give me some kind of advice on how to build this web app using ontologies ? -
Return daily sales value for the current month in Django
With the model below, I want to create a function that returns the details of daily sales for the current month. The details will be the total number of sales for each day and sum of sales for each day. I've tried using ExtractDay and annotate but I'm not getting the desired output or maybe I'm not doing it right class Stamping(models.Model): created = models.DateTimeField(auto_now_add=True) class Meta: abstract = True class Order(Stamping): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=300, unique=True) price = models.FloatField() quantity = models.IntegerField() In my location, the date is Tuesday, 2 November 2021. So the output should look like this <QuerySet [{'day': 1, 'count': 9, 'total': 100.0}, {'day': 2, 'count': 7, 'total': 80.0}]> And after today, I should also {'day': 3, 'count': 15, 'total': 200.0} and it keeps going till the end of the month then I'll start getting only the data for that month too -
How to use firebase authentication in django rest?
I have my user model like this. class User(AbstractUser): phone = models CharField(max_length=10, unique=True) name = models.CharField(max_length=50) The flow is: User on the mobile enters the name and phone and then signup. The users gets registered in the database. While login user only use phone number to login via firebase. Then how the django server will login this particular user ? -
Multiple ajax calls to populate fixed cell html table in django
———sorry for long question—— please share ajax-js-query-django code for the below requirement —-thanks a lot in advance… I have a functionality to achieve - its like giving a buyer ‘make your box’ kind of functionality - say a buyer lands in our ecom page with assorted items displayed along with radio-button having say 1. box-of-2 2. box-of-4 3. Box-of-6 So buyer selects box-of-2 and same page displays html box with just 2 cells. And below that all the items which can be clicked and this box-of-2 will be populated - say if buyer click item1 - then item1 gets placed in 1st cell of html table and then if he clicks on item2 then item2 gets placed in 2nd cell of html table. Now if buyer clicks on item3 - item3 gets placed in 1st cell of html table overwriting the item1 - so this way only two items will be in the html table. Now finally this box-of-2 is one commodity which can be added to cart by clicking on the add-to-cart button. Anyone can suggest some code snippets to achieve this with showing Empty box-of-n (html table) based on radio-button buyer selects Since the same page has all … -
How to add multiple model while registering new user?
I am using Django all-auth and Django rest-auth in my project. When registering new user i am sending user Info, personal info and location info data. Now I want to create those model after creating user model as well. How do i achieve that. -
How to do a subtraction in a html page on a pyhton variable?
I have this model: class Canva(models.Model): name = models.charfield(... year = models.IntegerField(... In my html page, When I use {{ canva.year }}, it shows me the year correctly. how can I see the year before, I tried {{ canva.year-1 }} or {{ canva.year }}-1 and it doesn't seem to work. -
Javascript not showing up on template in django
I do not understand why my javascript files are not being applied on my templates. Here is my base.html: <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Project</title> <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'assets/css/main.css' %}"> </head> <body> <div> {% include "navbar.html" %} {% block content %} {% endblock content %} </div> {% include "scripts.html" %} </body> </html> Here is my scripts.html: {% load static %} <script src="{% static 'js/main.js' %}"></script> <script src="{% static 'assets/js/jquery.min.js' %}"></script> <script src="{% static 'assets/js/jquery.dropotron.min.js' %}"></script> <script src="{% static 'assets/js/browser.min.js' %}"></script> <script src="{% static 'assets/js/breakpoints.min.js' %}"></script> <script src="{% static 'assets/js/util.js' %}"></script> <script src="{% static 'assets/js/main.js' %}"></script> However, they don't seem to affect the template. For example, the dropdown menu is in a weird format if I run the server. Another weird thing happening is that Main.js keeps being printed on the console. I believe this was initially because of the main.js file which had: console.log("Main.js"); However, even though I change it to the following: console.log("Something new for the console"); I still get Main.js printed out on the console. Moreover, if I put console.log("something") for my other javascript … -
Django - StatReloader not updating when change html file
I'm running into an issue I havn't had before. When I run python manage.py runserver I get default message: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). November 02, 2021 - 12:57:41 Django version 3.2.8, using settings 'core.settings' Starting development server at http://0.0.0.0:8000/ If I change some html and save changes, the changes are not shown in the browser. I have to quit the localserver and restart runserver to see the changes. This problem just appears out of nowhere - does anyone know how to fix or is there a package to fix this issue? -
Cyclical operations in Django Rest Framework
In my frontend application I have a panel which shows 6 the most popular products on my site. Searching for the most popular products each request by the number of views can be costly. I think that a good way to improve it will be to create a table in my data base which will store 6 the most popular products and the table will be refreshed for example every one minute. What should I looking for to do so cyclical operation on my django backend? -
remotely served Django service, does not return response for PATCH requests
I have deployed a Django rest framework service with multiple APIs on my Ubuntu 20.04 server with Gunicorn, everything works fine, but PATCH requests from outside the server do not receive a response, although the application receives the request and fully processes it. I have even tested it with Django runserver and the problem remains and has nothing to do with Gunicorn. Steps to reproduce: On the server we create a new Django application: ssh to_my@server python3 -m pip install django django-admin mytest cd mytest python3 manage.py runserver 0.0.0.0:9999 On the server trying to send requests to the application: ssh to_my@server curl --request GET localhost:9999/ # this works fine and we can see the response curl --request PATCH localhost:9999/ # this works fine too On another machine try these: # on my local machine curl --request GET IP:9999/ # this works fine curl --request PATCH IP:9999/ # **** this will get a `curl: (56) Recv failure: Connection reset by peer` after some times The response never arrives although in the console you can see that the request is fully received and Django has no problem: Invalid HTTP_HOST header: '207.154.246.122:9999'. You may need to add '207.154.246.122' to ALLOWED_HOSTS. Bad Request: / … -
How to hide field from Json response
I would like to hide from public api simple Serializer field (created without any model). How I can solve this? same_result = serializers.SerializerMethodField() -
Dropdown dependent problems with saving in the form part
I have a problem with dropdown dependent. in the frontend it works perfectly and filters me optimally but in the backend I have problems saving. Choose a valid option. The choice made does not appear among those available. This error is due to the fact that in form.py I cannot find 'gruppo_single' in self.data because it was excluded from the form to be dynamically passed from the view during the post. Can anyone help me with this problem? my models class Gruppi(models.Model): nome_gruppo = models.CharField(max_length=100) class Esercizi(models.Model): nome_esercizio = models.CharField(max_length=100) gruppo = models.ForeignKey(Gruppi,on_delete = models.CASCADE, related_name = 'gruppo') class Schede(models.Model): nome_scheda = models.CharField(max_length=100) data_inizio = models.DateField() data_fine = models.DateField() utente = models.ForeignKey(User, on_delete = models.CASCADE,related_name = 'utente') class DatiGruppi(models.Model): giorni_settimana_scelta = [ ("LUNEDI","Lunedì"), ("MARTEDI","Martedì"), ("MERCOLEDI","Mercoledì"), ("GIOVEDI","Giovedì"), ("VENERDI","Venerdì"), ("SABATO","Sabato"), ("DOMENICA","Domenica") ] giorni_settimana = MultiSelectField(choices = giorni_settimana_scelta,default = '-') dati_gruppo = models.ForeignKey(Gruppi,on_delete = models.CASCADE, related_name = 'dati_gruppo') gruppi_scheda = models.ForeignKey(Schede,on_delete = models.CASCADE, related_name = 'gruppi_scheda') class DatiEsercizi(models.Model): serie = models.IntegerField() ripetizione = models.IntegerField() peso = models.DecimalField(max_digits = 4,decimal_places = 1,blank = True,null = True) dati_esercizio = models.ForeignKey(Esercizi,on_delete = models.CASCADE,related_name = 'dati_esercizio') gruppo_single = models.ForeignKey(DatiGruppi, on_delete = models.CASCADE, related_name = 'gruppo_single') view for creating groups and exercises def creazione(request, nome): scheda = get_object_or_404(Schede, …