Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF loses CSRF token with PUT method
I have a regular ModelViewSetin my project, and it works perfectly with GET and POST requests, but it fails with PUT, returning this error: { "detail": "CSRF Failed: CSRF token missing or incorrect." } This is my urls.py: from django.urls import path,re_path,include from django.utils.text import slugify,camel_case_to_spaces from PaymentsManagerApp import views, models from rest_framework import routers APP_NAME = 'PaymentsManagerApp' router = routers.DefaultRouter() router.register(r'payments', views.PaymentViewSet) payments_list = views.PaymentViewSet.as_view({ 'get':'list', 'post':'create' }) def urlpattern_from_route(route): if "regex" in route and route['regex']: path_method = re_path else: path_method = path return path_method(route['path'],route['view'].as_view(),name=route['name'] if "name" in route else None) routes_views = list(map(urlpattern_from_route,routes)) route_services = [ payment_detail = views.PaymentViewSet.as_view({ 'get':'retrieve', 'put':'update', 'patch':'partial_update', 'delete':'destroy' }) route_services = [ path('payments/', payments_list, name='rest_payments_list'), path('payments/<int:pk>/', payment_detail, name='rest_payment_detail'), ] urlpatterns = routes_views + route_services This is my views.py: import os import json from datetime import datetime, timedelta from django.shortcuts import render from PaymentsManagerApp import urls, models, serializers from FrontEndApp import urls as Fronturls from django.shortcuts import render,redirect from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.contenttypes.models import ContentType from django.views.generic import View from django.contrib.auth.models import Permission from GeneralApp.utils import get_catalogs from django.contrib.staticfiles import finders from django.utils.text import slugify,camel_case_to_spaces from rest_framework import viewsets, permissions from rest_framework.response import Response from django_filters.rest_framework import DjangoFilterBackend from rest_framework.response import Response from … -
Checking a users permissions in django template
Still having problems, I saw the other posts. and the post here: https://docs.djangoproject.com/el/1.11/topics/auth/default/#authentication-data-in-templates So I am doing this: {% for trn in trainee %} <tr> <td>{{ trn.first_name }} {{ trn.last_name }}</td> <td>{{ trn.institution }}</td> <td>{{ trn.contact_phone }}</td> <td>{{ trn.contact_email }}</td> <td>{{ trn.trained_date }}</td> {% if perms.django_apo.training.delete_trainee %} <td> BUTTON </td> {% else %} <td> NA </td> {% endif %} </tr> {% endfor %} This is what the permissions look like for said person: Yet, it comes up with NA everytime. What am I missing? -
Write to a field in Wagtail using API?
I have a simple Wagtail application that has a field that I would need to update Wagtail Admin (Not using admin, via REST API?) Reading the field using API is documented and supported. However, I would like to update the field (json_text, see simplified example below) using API of some sort. It says in the documentation that the API is read only. I have searched around but there are hints of people making custom "write" API's. Any ideas, examples? I am stuck! NB:I am quite new to Wagtail and Django :-) from django.db import models from wagtail.core.models import Page from wagtail.admin.edit_handlers import FieldPanel from wagtail.api import APIField class HomePage(Page): json_text = models.TextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('json_text'), ] # Export fields over the API api_fields = [ APIField('json_text'), ] -
Does Django Cache the database's DNS info?
Django seemingly not doing a DNS lookup when connecting to postgres I have a route53 weighted CNAME record to load balance our read reps, however when i adjust the weights and test it out with dig, ensuring only one of the two read replica ips are being returned by the DNS, Django continues using the database ip from before the DNS swap. Does Django cache the ip of its database to avoid DNS lookups? I expected it to lookup the database each time it connected with a conn_max_age of 0. -
Django info and debug logs ignored, despite configuration
So I am trying to set up logging in a Django program. I set up the logging configurations in settings.py: DEBUG = True LOGGING_CONFIG = None LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'custom': { 'format': '%(asctime)s %(levelname)-8s %(name)-15s %(message)s' } }, 'handlers': { 'console': { 'level': 'NOTSET', 'class': 'logging.StreamHandler', 'formatter': 'custom' } }, 'loggers': { '': { 'handlers': ['console'], } } } import logging.config logging.config.dictConfig(LOGGING) And then I do the following: import logging logger = logging.getLogger(__name__) logger.info("INFO") logger.debug("DEBUG") logger.warn("WARN") logger.critical("CRITICAL") logger.error("ERROR") But I only get the following output: 2019-05-21 14:08:31,877 WARNING dashboards.charts WARN 2019-05-21 14:08:31,877 CRITICAL dashboards.charts CRITICAL 2019-05-21 14:08:31,877 ERROR dashboards.charts ERROR I tried changing the level to DEBUG or info, but that didn't change anything. The formatter works correctly, so I don't know why the level won't work. -
Using a task queue in django without leaking kwargs
I want to create a webpage using django which, when requested, presents a form asking for all kinds of user input including the user password. When submitted, a concurrent task should be started, which takes the user input as arguments and does all kinds of calculations. Note that the task has to be started concurrent, since the calculations can take a while and I want to inform the user immediately that his task has been accepted - I want to keep him up to date about his task in another view. the plaintext user password is part of the task arguments. It has to be, since the calculations involve encryption operations which rely on the password. Now I would just use celery and django_celery_results as result backend for this goal (and already started using it), when I noticed: Whoa... django_celery_results stores the plaintext password as part of the task kwargs in the database. That's not cool. Also the whole RabbitMQ messaging of the plaintext password seems a bit unsecure to me, after reading the celery security documentation. And who knows in which logs celery writes the passwords. To sum it up: celery and other task qeues not seem to be … -
migrations.AlterField choices's orders are being altered. Can I delete this?
Unfortunately, I'm running into some problems migrating Django migrations files since I have way too many models for, let's say, this extremely specific database; therefore, I have 6 migrations files. I have this many for the simple reason of "there are too many models." I'm trying to deduce the reason for being unable to migrate, and I believe it to be 1) (the pointer given to me) stack overflow and 2) memory. This is the code in the migrations file that I want to delete: operations = [ migrations.AlterField( model_name='pnote1', name='status', field=models.CharField(choices=[('5', 'test5'), ('4', 'test4'), ('3', 'test3'), ('6', 'test6'), ('1', 'test1'), ('2', 'test2')], default='1', max_length=1), ), There are 100's of these AlterFields. I'm wondering if I can delete them without harming the database; it just seemed redundant to have these AlterFields, even though nothing was altered. The models (inherited from an abstract model) have this as: option = models.CharField(max_length=1, choices=TYPE, default='1') The order of the choices I originally had were 1-6, not this jumble. And in each migration file, the number of migrations.AlterField just keep increasing for some odd reason. So again, can I delete this without harming the database? -
JSONEncoder issue running APScheduler on Heroku
I installed APScheduler this morning to automate some email task, was previously using the Heroku scheduler. Trying to run the same script I am getting this error. Looks like the issue is coming from json.JSONEncoder heroku[email_clock.1]: State changed from crashed to starting heroku[email_clock.1]: Starting process with command `python customer/send_email.py` heroku[email_clock.1]: State changed from starting to up heroku[email_clock.1]: State changed from up to crashed heroku[email_clock.1]: Process exited with status 1 app[email_clock.1]: Traceback (most recent call last): app[email_clock.1]: File "customer/send_email.py", line 5, in <module> app[email_clock.1]: from customer.management.commands.Send_PDF import Command app[email_clock.1]: File "/app/customer/management/commands/Send_PDF.py", line 4, in <module> app[email_clock.1]: from django.http import HttpResponse app[email_clock.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/http/__init__.py", line 5, in <module> app[email_clock.1]: from django.http.response import ( app[email_clock.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/http/response.py", line 15, in <module> app[email_clock.1]: from django.core.serializers.json import DjangoJSONEncoder app[email_clock.1]: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/serializers/json.py", line 76, in <module> app[email_clock.1]: class DjangoJSONEncoder(json.JSONEncoder): app[email_clock.1]: AttributeError: module 'json' has no attribute 'JSONEncoder' I don't know where this error is coming from? -
im getting this AttributeError, help me solve it
im getting this attribute error , i don not know why im trying to import views from django.contrib.auth , and i wanna use their authentication method from django.contrib import admin from django.urls import path from django.conf.urls import url,include from django.contrib.auth import views urlpatterns = [ url(r'', include('blog.urls')), url(r'^accounts/login/$', views.login, name='login'), url(r'^accounts/logout/$', views.logout, name='logout', kwargs= {'next_page':'/' }), path('admin/', admin.site.urls), ] url(r'^accounts/login/$', views.login, name='login'), AttributeError: module 'django.contrib.auth.views' has no attribute 'login' -
Invalid paths in urls.py
When I run my server I receive an error saying that all my url paths are invalid. I checked spelling, syntax, and even copy and pasted to no avail. I just want it to run. I attempted to correct my spelling, Syntax, everything. I'm running a simple Django server on a Raspberry Pi 3 B from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), path('suggest/', views.OwO, name="OwO"), ] I also tried from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), path('suggest', views.OwO, name="OwO"), ] -
Django - cannot unpack non-iterable ManyRelatedManager object
so I'm trying to display a list of items from a table that don't appear in another table. But I keep getting errors such as "cannot unpack non-iterable ManyRelatedManager object" I've tried many variations of django filter and exclude but there is always an error of either the aforementioned or depending on other things I have tried: User object has no attribute profile or Cannot unpack non-iterable int object Models: class Item(models.Model): item_name = models.CharField(max_length=200) def __str__(self): return self.item_name class Meta: verbose_name = "Item" verbose_name_plural = "Items" class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user") items = models.ManyToManyField(Item) class Meta: verbose_name = "Profile" verbose_name_plural = "Profiles" Views: python @login_required def item_view(request): if request.method == 'GET': user_obj = request.user.user items = Item.objects.filter(user_obj.items) context_dict = {'items': items} return render(request, 'site/items.html', context_dict) else: return HttpResponseNotFound() items.html: {% for i in items%} <li><input type="checkbox" data-pk="{{i.pk}}" name="{{i.item_name}}" value="{{i.pk}}" onchange="processChange(this)"> {{i.item_name}}<br> </li> {% endfor %} The goal is for items.html to display all the items that are not in the users profile. Everything I seem to try doesn't seem to work so any help is greatly appreciated. -
Saleor template exception
After a fresh install of Saleor, I start up with runserver and I get the following errors It's running on Python 3.7.3 in a virtual environment. I tried changing from localhost to an ip address and changed the port. DEBUG django.template Exception while resolving variable 'name' in template 'unknown'. [PID:1879:Thread-1] Traceback (most recent call last): File "/home/pi/Public/Python/Saleor/salvenv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/pi/Public/Python/Saleor/salvenv/lib/python3.7/site-packages/django/core/handlers/base.py", line 100, in _get_response resolver_match = resolver.resolve(request.path_info) File "/home/pi/Public/Python/Saleor/salvenv/lib/python3.7/site-packages/django/urls/resolvers.py", line 566, in resolve raise Resolver404({'tried': tried, 'path': new_path}) django.urls.exceptions.Resolver404: {'tried': [[ (dashboard:dashboard) '^dashboard/'>], [], [], [], [ (social:social) ''>, [^/]+)/$' [name='begin']>], [ (social:social) ''>, [^/]+)/$' [name='complete']>], [ (social:social) ''>, [^/]+)/$' [name='disconnect']>], [ (social:social) ''>, [^/]+)/(?P\d+)/$' [name='disconnect_individual']>], [ (None:None) 'en/'>], [ (djdt:djdt) '^__debug__/'>], [.*)$'>], [.*)$'>]], 'path': ''} During handling of the above exception, another exception occurred: ...It goes on with more exceptions inside django/template/base.py -
What is causing my input to not be saved into my django model database?
I'm trying to create a quiz website using Django. I have created a modelform in which input boxes appear on the website alongside a submit button. Inputting text into it and submitting it works just fine and sends a POST request aswell, according to cmd. However, it doesn't seem to save the inputs into the model, which is what i am trying to achieve. views.py from django.http import HttpResponse from django.shortcuts import render, redirect from .models import Question, InputText from .forms import AnswerForm # Only shows relevant view def kvizpost(request): if request.method == 'POST': form = AnswerForm(request.POST) if form.is_valid(): text = form.cleaned_data() text.save() return redirect('kviz:kviz') else: form = AnswerForm() return render(request, 'vprasanja/kviz.html', {'form' : form}) forms.py from django import forms from kvizapp.models import InputText class AnswerForm(forms.ModelForm): class Meta: model = InputText fields = ('vnesi',) models.py from django.db import models # Only shows relevant model class InputText(models.Model): vnesi = models.CharField(max_length=100) kviz.html {% block body %} <form action = "/kviz/" method="post"> {% csrf_token %} {{ form.as_p }} <br> <input type="submit" value="Vnos"> </form> </body> {% endblock %} -
"ImportError: No module named urls" encountered when trying to upgrade Django
I'm trying to upgrade Django from 1.8 to 1.11. However, I'm running in to this error: Traceback (most recent call last): File "manage.py", line 16, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 327, in execute self.check() File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 256, in check for pattern in self.url_patterns: File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 407, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 400, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named urls I first run docker-compose -f docker-compose.yml -f docker-compose.tests.yml build, which builds successfully, followed by docker-compose run --rm util python manage.py makemigrations. However, after the latter command, I run in to the above error. I've searched extensively for possible solutions to … -
Django not working with supervisor, getting [Errno 88] Socket operation on non-socket
I have made a server using Django REST framework and Django channels but I am unable to configure supervisor to run with it. My supervisor config is as follow: [program:frnd_django] socket=tcp://localhost:8000 directory=/home/coldbrewtech/frnd/backend/dating-app-backend/django-server/cbproj/ environment=DJANGO_SETTINGS_MODULE=cbproj.dev_settings command=/home/coldbrewtech/frnd/backend/env/bin/daphne -u /run/daphne/daphne%(process_num)d.sock --fd 0 --access-log - --proxy-headers cbproj.asgi:application stdout_logfile=/home/coldbrewtech/frnd/backend/dating-app-backend/django-server/cbproj/logs/django_out.log stderr_logfile=/home/coldbrewtech/frnd/backend/dating-app-backend/django-server/cbproj/logs/django_err.log numprocs=4 process_name=asgi%(process_num)d autostart=true autorestart=true user=root startsecs=10 stopwaitsecs=600 stopasgroup=true stopsignal=KILL And the error that I am getting is as follow: 2019-05-21 18:03:50,111 INFO Starting server at fd:fileno=0, unix:/run/daphne/daphne3.sock 2019-05-21 18:03:50,121 INFO HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2019-05-21 18:03:50,125 INFO Configuring endpoint fd:fileno=0 2019-05-21 18:03:50,130 INFO Starting server at fd:fileno=0, unix:/run/daphne/daphne1.sock 2019-05-21 18:03:50,131 INFO Starting server at fd:fileno=0, unix:/run/daphne/daphne0.sock 2019-05-21 18:03:50,132 INFO HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2019-05-21 18:03:50,133 INFO Configuring endpoint fd:fileno=0 2019-05-21 18:03:50,134 INFO HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2019-05-21 18:03:50,145 INFO Configuring endpoint fd:fileno=0 2019-05-21 18:03:50,154 INFO Starting server at fd:fileno=0, unix:/run/daphne/daphne2.sock 2019-05-21 18:03:50,158 CRITICAL Listen failure: [Errno 88] Socket operation on non-socket 2019-05-21 18:03:50,159 INFO HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2019-05-21 18:03:50,160 INFO Configuring endpoint fd:fileno=0 2019-05-21 18:03:50,163 CRITICAL Listen failure: [Errno 88] Socket operation on non-socket 2019-05-21 18:03:50,160 INFO … -
Is there any way to use bulk_create with model formsets?
I am currently using model formsets in my project. The problem I find is that the app may have to show more than 50 forms on the same page, so saving them using the .save() method would generate more than 50 queries (one query for each form I'm going to save). Since all forms have the same structure, it would be ideal to be able to save them with bulk_create, in such a way that only one query is generated, however the modelformset does not support bulk_create. Is there any way to save all the answers of the forms with only one query? The only thing that I can think of, is after validating the forms with formset.is_valid(), recover the request.POST and from there save with bulk_create. Is there a better alternative? -
How to set url for the uploaded file in FileSystemStorage(location)
i want to set the correct url of my file which is provided in the location of filesystemstorage views.py if request.method=='POST' and request.FILES.get('myfile', None): myfile=request.FILES['myfile'] print(myfile.name.split('.')) image_name_banner = image_name +'-' + 'banner' + '.' +myfile.name.split('.')[-1] print(image_name_banner) myfile.name = image_name_banner fs=FileSystemStorage(location='media/events/images') print(fs) filename=fs.save(myfile.name,myfile) print(filename) print(fs.url) uploadedfileurl=fs.path(filename) u_banner=uploadedfileurl print(u_banner) the u_banner is printing the default url as media/filename.jpg -
What does "as_" in django query means?
I am wondering what "as_" in django query means. I have 1 query: User.objects.filter(username = "some_username").as_manager.something but in User model there is no "as_manager". Then in some other model called "Manager" I got "something" which is exactly what is returned. Is it some kind of deep django knowledge that "as_" can guide me to other model? Or is it "as_manager" somewhere which I cannot spotted. I only add that User model extends from django AbstractUser. -
How to change that django checks other boolean field instead of is_staff for admin panel authentication?
I have custom "AUTH_USER_MODEL" as follows: class User(AbstractUser): is_institute_admin = models.BooleanField(default=False) def has_perm(self, perm, obj=None): app_label = perm.split('.')[0] if self.is_institute_admin: return app_label == 'Profiler' if self.is_superuser: return app_label == 'Accountant' def has_module_perms(self, app_label): if self.is_institute_admin: return app_label == 'Profiler' if self.is_superuser: return app_label == 'Accountant' I want that when user logs in to django admin panel, authentication must check is_institute_admin instead of its by default is_staff. I added and registered in settings.py a custom authentication file as below: class CustomBackend: def authenticate(self, request, username=None, password=None): try: user = User.objects.get(username=username) print('user value =', user, password) password_valid = check_password(password=password, encoded=user.password) if password_valid: if user.is_superuser or user.is_institute_admin: print('returning user') return user return None else: print('password not matched') return None except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None As for debugging, I added some print statements and it prints till print('returning user') but authentication fails. Thanks for help in advance! -
Embed plotly:dash figure inside django template
Looking forward to finding out some possible way to use plotly dash table or other figures in existing Django app template. I have been digging into this problem for the last 36 hours. As i understand dash ends up serving in its own server . Theres barely much documentation and easy to understand examples that supporst my needs. All i could find is the following eads method however this method helps run plotly:dash inside Django with completely separate url. Its not like i have an existing template and i can add the dash figure inside there . django-plotly-dash is a library I was looking into i went through the entire documentation and tried ,yself however i always end up getting errors like 'No reverse match at' or like 'not a valid namspace ' and so on. Just one example showing how i can integrate dash figures inside Django template. -
How to pass user name as variable into function within form
I would like to pass a username [object] into a function as a variable. This function is being called upon within a form. I have tried to initialize the request object within the form to be able to call the user and pass it into the parameter of the function. The issue is that it is not initialized before the function is called. class ManagerForm(forms.Form): names = get_employee_names(username_test) # the username_test object is what I would like to pass manager = forms.ChoiceField(choices=names, widget=forms.RadioSelect) def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") # initializing request object super(ManagerForm, self).__init__(*args, **kwargs) self.username_test = self.request.user The code works when I pass in a string such as 'username' so this suggests that the order of operations is incorrect when I try to pass the request.user object. The Error I get: NameError: name 'username_test' is not defined -
How can you display either a video or image file in a Django Template depending on what type the uploaded file is?
I am trying to display a file from a foreign key set of a model instance. The file can either be videos or pictures and is uploaded by users (think similar to Instagram). How can I display the file as <video> or <img> properly depending on the file type that was uploaded? I am currently using <video> or <img> tags in html to show the file and they both work but only if the file is of the appropriate type. If the file is of the other type the incorrect tag will show a black box on the site. {% if result.resultfile_set.all %} {% for resultfile in result.resultfile_set.all %} <video controls> <source src="{{ resultfile.file.url }}"> </video> <img src="{{ resultfile.file.url }}" /> <p>Caption: {{ resultfile.caption }}</p> {% endfor %} {% endif %} Expected results are that if the file that has been uploaded by the user is a video file, display it as such; or if the file is an image file, display it as image. Instead I am currently only able to display both file types every time where one of them displays properly and the other displays as a black box -
How can I use Reactjs with Django keeping SEO?
I've been working on frontend with jQuery with Django for backend. I was so frustrated to keep using jQuery as I can work in a better environment with Reactjs, so I tried to integrate Reactjs with Django by calling index.html on React side in urls.py in Django side. It worked well, but the problem is the setup is too poor for SEO as Reactjs works with client side rendering. I already researched about Nextjs, but it needs a separate server for server side rendering. I simple want to run one server for frontend and backend. Is there any option that I can try in that case? -
How can I display the Git information - last commit , branch etc on a web page?
I need to show the current git branch so I know which branch has been deployed Also, It would be great if I could also show information about the EC2 instance such as its name. -
Filtering Data Based On Foreign Key - Django
I am having an issue dynamically populating form data based on the previous selected field. In my case I have two models one which contains different types of memberships associated to different clubs. Then I have another model which handles registrations for individual clubs. My problem - when the end-user is ready to sign up the form renders (I already filter out members based on the club they originally selected) but I need to filter the price based on the membership selected (foreign key) of player model. Below is my model for the membership types: Model to store clubs available memberships so members can select and pay on registration page class ClubMemberships(models.Model): club_id = models.ForeignKey(ClubInfo, on_delete=models.CASCADE) title = models.CharField(max_length=30, default='') price = models.DecimalField(default=0.00, max_digits=6, decimal_places=2) description = models.TextField() def __str__(self): return self.title Here is the model for the registration: Model to store player information to be used for membership registration class Player(models.Model): club_id = models.ForeignKey(ClubInfo, on_delete=models.CASCADE) membership_title = models.ForeignKey(ClubMemberships, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) dob = models.DateField(max_length=8) email = models.EmailField(max_length=50) phone = models.CharField(max_length=12) mobile = models.CharField(max_length=15) emergency_contact_name = models.CharField(max_length=40) emergency_contact_mobile = models.CharField(max_length=15) address1 = models.CharField(max_length=30) address2 = models.CharField(max_length=30, default='') address3 = models.CharField(max_length=30, default='') town …