Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't connect postgresql in a docker (receiving fastshut down request)
I am running a django/postgresql in docker when run docker-compose -f local.yml up" postgresql service will start and then it will be shut-down with LOG:listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" then "database system was shut down". I have read it is receiving a postmaster fast shutdown request but I don't know how to solve this. I have tried to changed ports and other postgresql env variables and postgresql build images in docker-compose without success. Here is my .ylm for docker-compose version: '3' volumes: postgres_data_local: {} postgres_backup_local: {} services: django: build: context: . dockerfile: ./compose/local/django/Dockerfile depends_on: - postgres - redis volumes: - .:/app env_file: .env ports: - "8000:8000" command: /start.sh postgres: image: postgres:10.1-alpine build: context: . dockerfile: ./compose/production/postgres/Dockerfile volumes: - postgres_data_local:/var/lib/postgresql/data - postgres_backup_local:/backups env_file: .env redis: image: redis:3.0 ports: - '6379:6379' My .env file is somehow like # PostgreSQL conf POSTGRES_PASSWORD=p3wrd POSTGRES_USER=postgres POSTGRES_DB=postgres POSTGRES_HOST=127.0.0.1 //have tried localhost, 0.0.0.0 etc POSTGRES_PORT=5432 DATABASE_URL= postgresql://postgres:p3wrd@127.0.0.1:5432/postgres # General settings READ_DOT_ENV_FILE=True SETTINGS_MODULE=config.settings.test SECRET_KEY=Sup3rS3cr3tP@22word DEBUG=True ALLOWED_HOSTS=* # URL for Redis REDIS_URL=redis://127.0.0.1:6379 See the console here -
django admin with websocket
I am new to django. I want my admin panel to automatically update itself whenever new model instances are created without refreshing the page. I found that this can be implemented using websocket(django channels), But I do not know how to do with the django admin. Any help/suggestions/directions are much appreciated!! -
TypeError: object of type 'NewsLetterUser' has no len()
I've created an instance of email but when I'm gonna save as Publish a newsletter that time throwing this error. But if save into Draft this time is okay. My NewsletterUser model return Nonetype value when i created an instance of this into views. My code is below. After create Newletter's objects name of newsletter and when i'm gonna access it by newsletter.email then show it newsltters.NewsLetterUser.None My app name is newsltters. **models.py** class NewsLetterUser(models.Model): email = models.EmailField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email class NewsLetter(models.Model): EMAIL_STATUS_CHOICE = ( ("Draft", "Draft"), ("Published", "Published"), ) subject = models.CharField(max_length=299) content = models.TextField() email = models.ManyToManyField(NewsLetterUser) status = models.CharField(max_length=11, choices=EMAIL_STATUS_CHOICE) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.subject **forms.py** class NewsLetterCreationForm(forms.ModelForm): class Meta: model = NewsLetter fields = ['subject', 'content', 'email', 'status'] def clean_email(self): email = self.cleaned_data.get('email') return email **views.py** i didn't get any value into email . def control_newsletter(request): form = NewsLetterCreationForm(request.POST or None) if form.is_valid(): instance = form.save() newsletter = NewsLetter.objects.get(id=instance.id) if newsletter.status == "Published": subject = newsletter.subject content = newsletter.content from_email = settings.EMAIL_HOST_USER for email in newsletter.email.all(): to_email = [email] send_mail(subject, content, from_email, to_email, fail_silently=True) messages.success(request, "NewsLetter has benn sent in your selected email\n" "alert alert-warning alert-dismissible") … -
extending User causes authentication error
I am developing a SPA( single page application) webpage using react in the frontend and django in the backend.I am using django-rest-auth alongside django-allauth to post the data from the frontend to the backend. However, when i extended User to add more fields, a problem with user authentication has been raised... when i hit up http://127.0.0.1:8000/rest-auth/login/ and enter the admin credentials, unsurprisingly the token is being generated but this isn't the case when i enter the user credentials, it shows this error : { "non_field_errors": [ "Unable to log in with provided credentials." ] } My Customer Class: class Customer(User): account_no = models.PositiveIntegerField( unique=True, validators=[ MinValueValidator(10000000), MaxValueValidator(99999999) ], null=True ) some_extra_fields... Note: I am only using the username and the password to login. urls.py path('api/users/', include('customer.api.urls')), path('rest-auth/', include('rest_auth.urls')), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('rest-auth/registration/', include('rest_auth.registration.urls')), settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ), } CORS_ORIGIN_ALLOW_ALL = True ACCOUNT_EMAIL_VERIFICATION = 'none' ACCOUNT_AUTHENTICATION_METHOD = "username" ACCOUNT_EMAIL_REQUIRED = False -
In Django saving a (translated) slug and making it unique doesn't work
I use Django 1.11 and the parler plugin for translation. Every time I save a slug, I wish to test if it already exists truncate the slug add number test again, if the new slug exists and so on This way, I wish to create a unique slug on saving. models.py: from parler.models import TranslatableModel from django.utils.translation import gettext_lazy as _ class Event(TranslatableModel): translations = TranslatedFields( event_title=models.CharField(_("event title"), max_length=512), slug=models.SlugField(_("slug"), help_text=_("Used in the URL of the event page.")), description=RichTextUploadingField(blank=True), meta={'unique_together': (('language_code', 'slug'),)}, ) def save_translation(self, translation, *args, **kwargs): """Create a unique slug of 45 Characters + a dash and 4 digits.""" translation.slug = translation.slug[:50] if Event.objects.active_translations(slug=translation.slug).exists(): # This is true on the first test for no apparent reason. i = 0 while Event.objects.active_translations(slug=translation.slug).exists(): translation.slug = translation.slug[:44]+'-'+str(i) i += 1 super(Event, self).save_translation(translation, *args, **kwargs) This code dosen't work. It always add a number to the slug, no matter what, even if I enter a completely new slug. -
How to test code that creates Celery tasks?
I've read Testing with Celery but I'm still a bit confused. I want to test code that generates a Celery task by running the task manually and explicitly, something like: def test_something(self): do_something_that_generates_a_celery_task() assert_state_before_task_runs() run_task() assert_state_after_task_runs() I don't want to entirely mock up the creation of the task but at the same time I don't care about testing the task being picked up by a Celery worker. I'm assuming Celery works. The actual context in which I'm trying to do this is a Django application where there's some code that takes too long to run in a request, so, it's delegated to background jobs. -
PyCharm inspection not working properly with Django multiple settings per domain
I have a Django project that implements core functionalities and admin panel (not django's one, but a custom as an app). Since my goal is to access from two separated domains to them (api.example.com and panel.example.com), I split settings like that: settings.py settings_core.py settings_panel.py At the bottom of settings.py I determine which specific setting to load reading an environment variable: PROJECT_DOMAIN = os.environ.get('PROJECT_DOMAIN') if PROJECT_DOMAIN == 'core': from settings_core import * elif PROJECT_DOMAIN == 'panel': from settings_panel import * It works. Each specific settings file ha inside the urlconf definition: ROOT_URLCONF = 'myproject.urls_core' Now, the problem is with PyCharm: inspection of urls in reverse function and in url template tag suggests urls only from core_urls, not from panel_urls. Why? Any suggests? Thank you -
I am not able to custom style my password fields in registration form in django
I am trying to add bootstrap on my User registration form and the problem I am getting is that All the fields are styled except the password and password confirmation fields. Here is my code: My forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class mysignupform(UserCreationForm): email = forms.EmailField(required = True,widget=forms.EmailInput(attrs={'class':'form-control'})) class Meta: model = User fields = ['username','first_name','last_name','email','password1','password2'] widgets= { 'username':forms.TextInput(attrs={'class':'form-control'}), 'first_name':forms.TextInput(attrs={'class':'form-control'}), 'last_name':forms.TextInput(attrs={'class':'form-control'}), 'password1':forms.PasswordInput(attrs={'class':'form-control'}), 'password2':forms.PasswordInput(attrs={'class':'form-control'}), } def save(self,commit=True): user = super(mysignupform,self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user -
How to run a python code via Django templates?
I want to execute code below when the is submitted (project on Django): from os import system, listdir, remove link = 'https://www.youtube.com/watch?v=ME9yO1KEVoo' def download(): ## Downloading a video from YouTube using youtube-dl system("youtube-dl -o download {}".format(link)) def convert(): ## Converting downloaded video to mp3 format via ffmpeg.exe(same directory) listOfFiles = listdir('.') for i in listOfFiles: if i.startswith("download"): name = i system("ffmpeg -i {} download.mp3".format(name)) def main(): download() convert() main() I have tried to put this code into views.py: class download(TemplateView): def main(request): if request.method == 'POST': link = 'https://www.youtube.com/watch?v=ME9yO1KEVoo' system("youtube-dl -o download {}".format(link)) listOfFiles = listdir('.') for i in listOfFiles: if i.startswith("download"): name = i system("ffmpeg -i {} download.mp3".format(name)) return redirect ('loader/wait.html') urls.py: path('wait/', views.download.as_view(), name='wait') and the html form which is submitted to run views.download.as_view(): <form action='{% url 'wait' %}' method="POST">{% csrf_token %} <input type="submit" value="Yes" /> </form> -
django-redis connection error inside docker
djano views.py import redis import jwt from access import utils import os redis_url = os.environ['REDIS_URI'] R = redis.StrictRedis(redis_url) def set(request): R.set('foo', 'bar') return JsonResponse({"code":200,"msg":"success"}) docker-compose version: "3" services: rango: container_name: rango build: ./ command: python backend/manage.py runserver 0.0.0.0:8000 # command: npm start --prefix frontend/rango-frontend/ working_dir: /usr/src/rango environment: REDIS_URI: redis://redis_db:6379 ports: - "8000:8000" tty: true links: - elasticsearch - node - redis #elastic search elasticsearch: image: docker.elastic.co/elasticsearch/elasticsearch:6.5.0 ports: - "9200:9200" #node node: image: node:10.13.0 #redis redis: image: redis environment: - ALLOW_EMPTY_PASSWORD=yes ports: - "6379:6379" here i am connecting redis from django inside docker. it is giving me exceptions connexctions refused. Please have a look into my code and shared screenshot below -
Merge multiple text fields in DJANGO into one text field and then serialize
I have a model Activity, which has a field data that contains JSON string: class Activity(models.Model): date_added = models.DateTimeField(auto_now_add=True) start_date = models.DateTimeField(default=datetime.datetime.now) data = models.TextField() # stores activity's JSON in text format, not as Python object number = models.IntegerField(default=0) I would like to create an API endpoint that would expose data fields of all Activity objects as one big JSON string,so my other app could receive all data in one request. So I thought I would create another model that would hold such merged JSON: class Activities(models.Model): #"data" field contains all Activity model JSONs as one big JSON string that can be easily # serialized and received by Bokeh app in single request, as opposed to Bokeh app making requests to single activities data = models.TextField(default='') Questions: What is the best way to merge same text fields of multiple objects into one that can be safely serialized by Django Rest Framework? Is this even a good practice? Or are there better ways to achieve the same? As a side note, I am not using Postgres, so cannot use JSON model field. -
Enable/Disable Django form fields based on ChoiceField selection?
I have a ChoiceField with 2 options and another CharField for key. I need the key field to only be editable or visible when the ChoiceField is set to private. My form in forms.py looks like this: class CBNewForm(forms.Form): CHOICES = (('public', 'Public',), ('private', 'Private',)) title = forms.CharField() category = forms.ChoiceField(choices=[(x,x) for x in CBData.getAllcategory()]) visibility = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) key = forms.CharField(required=False) def __init__(self, *args, **kwargs): super(CBNewForm, self).__init__(*args, **kwargs) self.initial['visibility'] = 'public' So I need the 'key' to only be visible/editable if the visibility = 'private'. I've looked at the comments here and they suggest that this needs to be done in javascript so I'm hoping someone can show me how to add javascript to my .html files and excatly what i'd need. -
Django + Python: Will type automatically detected right?
I wonder if I have to convert discount_value into a decimal (to make sure). It seems when I test it with print discount_value it's type is automatically detected as a decimal. However, I had cases before, where it was detected as a float and didn't work anymore. def calculate_discounted_value(self, ticket_price_gross): [...] elif self.percentage: discount_value = Decimal(ticket_price_gross * self.percentage) discount_value = quantize(discount_value, '1') print(ticket_price_gross - discount_value, "PERCENTAGE") def quantize(amount, decimals): """ Decimal numbers can be represented exactly. In contrast, numbers like 1.1 and 2.2 do not have exact representations in binary floating point. End users typically would not expect 1.1 + 2.2 to display as 3.3000000000000003 as it does with binary floating point. With this function we get better control about rounding. Therefore: amount should be come in as decimal. """ #amount_as_decimal = Decimal(amount) amount_as_decimal = amount quantized_amount = amount_as_decimal.quantize( Decimal(decimals), rounding=ROUND_HALF_UP ) return quantized_amount -
Looping throgh json jinja2 python
I have a json fron an API like this: my views.py looks like this: def index(request): movieData = requests.get('https://api.themoviedb.org/3/search/movie?query=Ishtar&api_key=....').json() return render(request, 'dashboard/index.html', {'movieData': movieData}) My html looks like this: {% for item in movieData %} <lu> <li> {{ item.results.id }} </li> </lu> {% endfor %} However the loop is not working, it's not getting the data, this is how it looks: Can someone give me hand please? I'm learning. Many thanks -
Counting the number of items in many-to-many field in django
I have a room object, class Room(Base): name = models.CharField(db_index=True, unique=True, max_length=255) members = models.ManyToManyField(User, blank=True) last_activity = models.DateTimeField(default=timezone.now) I'm trying to find the number of members in this room. Neither of these work, room.members.count() room.members.all.count() How do I count the number of members. -
Django queryset evaluation
Let say i have queryset like follow. queryset1 = Staff.objects.filter(user_id=self.request.user.id).values_list("department_id", flat=True) if i am trying to pass queryset 1 to new queryset like below queryset_form_1 = Department.objects.filter(pk__in=list(queryset1)) queryset_form_2 = Department.objects.filter(pk__in=queryset1) as i mentioned above if i eval the queryset1 with list(queryset1) it fetch the expected result but if i try like in queryset_form_2 it fetch all records what mistake i made? -
Out of Nodejs and Django What should I learn to build a web project which involves web crawling (spidering)? check description
I know how to make a web crawler in raw python and I am would work on a project which involves crawling web, spidering basically. I was confused between what to learn node or django so that I can work on this project. Since I know how to make a web crawler in python learning django makes more sense to me but can we do same thing with node? I would really love to learn node. can any experienced developer help me to pick the framework for this project. Thanks. -
Python Django length of form field input is 1 even when it's empty
I'm working on a project using Python(3.6) and Django(2.1) in which I need to implement the search functionality. I have two fields for search what and where. The user can enter multiple values for both of these fields and separate them by a ,, then I need to check the length of both fields after splitting it by ,. When a field is empty it's length should be 0 but in my case, it shows that the length is 1 even when the field is empty. Here's my code: From forms.py: class FetchDataForm(forms.Form): what = forms.CharField(max_length=256, required=True) where = forms.CharField(max_length=256, required=False) class Meta: fields = ('what', 'where') From templates/search.html: <form method="POST" action="{% url 'udata:fetch-data' %}"> {% csrf_token %} <div class="form-row"> <div class="form-group col-md-5"> <label for="inputEmail4" style="font-size: x-large">What:</label> <br><span class="help" style="font-size: smaller; padding-top: 0%;"> keywords, or company</span> {% if dd.what %} <input type="text" name="what" value="{{ dd.what }}" class="form-control" id="inputEmail4"> {% else %} <input type="text" name="what" class="form-control" id="inputEmail4"> {% endif %} </div> <div class="form-group col-md-5"> <label for="inputEmail4" style="font-size: x-large">Where:</label> <br><span class="help" style="font-size: smaller; padding-top: 0%;">City, State or Zip code</span> {% if dd.where %} <input type="text" name="where" value="{{ dd.where }}" class="form-control" id="inputPassword4"> {% else %} <input type="text" name="where" value="" class="form-control" id="inputPassword4"> {% endif … -
Avoiding duplicate queries in Django admin for __str__() with a foreign key
In one model I want to reference my user's first and last name as the str() which is a foreign key to the User model. def __str__(self): return f"{self.user.first_name} {self.user.last_name}" My issue is, in some of the models on Django Admin, there are hundreds of queries which will obvious go to thousands with more users. What is the best practice around avoiding this? In some of my custom views there are duplicates here, but it's not as big of a deal as it is with the admin panel. -
Foreign key not being recognized
I've created two models. When I run makemigrations, I'm getting the following error: ERRORS: userorders.UserCartItem: (fields.E336) The model is used as an intermediate model by 'userorders.UserCart.items', but it does not have a foreign key to 'UserCart' or 'UserService'. models.py class UserCartItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) #name of rep cart = models.ForeignKey("UserCart", on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) line_item_total = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return str(self.id) class UserCart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) items = models.ManyToManyField(UserService, through=UserCartItem) items_total = models.DecimalField(max_digits=50, decimal_places=2, default=25.00) #dollar value of all items in cart def __str__(self): return str(self.id) Any thoughts on what the problem is? I've defined the foreign key on UserCartItem as UserCart, but it looks like it's not being recognized. I should point out that I understand that when you identify another model as a foreign key and the foreign key model is below the model that you are working in, you have to put the foreign key model in quotation marks, hence why did this: models.ForeignKey(**"UserCart"**, on_delete=models.CASCADE) thanks! -
create_superuser() missing 3 required positional arguments
I'm trying to extend customUser registration with the documentation. I've just added 3 more fields to my models and I get this error when I used "py manage.py createsuperuser": picture with the error This code worked before to add those fields ("regiones, comunas and tipo_vivienda") MODEL.PY from django.db import models from django.contrib.auth.models import AbstractUser, UserManager from django.core.validators import RegexValidator # Create your models here. class CustomUserManager(UserManager): def create_user(self, run, email, fechaNac, nombre, apellido, telefono, regiones, comunas, tipo_vivienda, password=None): if not run: raise ValueError("Usuario debe ingresar su run") user = self.model( run = run, email = self.normalize_email(email), fechaNac = fechaNac, nombre = nombre, apellido = apellido, telefono = telefono, regiones = regiones, comunas = comunas, tipo_vivienda = tipo_vivienda, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, run, email, fechaNac, nombre, apellido, telefono, regiones, comunas, tipo_vivienda, password): user = self.create_user( run, password=password, email=email, fechaNac=fechaNac, nombre=nombre, apellido=apellido, telefono=telefono, regiones = regiones, comunas = comunas, tipo_vivienda = tipo_vivienda, ) user.is_admin = True user.save(using=self._db) return user class CustomUser(AbstractUser): run = models.CharField(max_length=9, unique=True) email = models.EmailField(max_length=30, unique=True, verbose_name='Direccion de correo') #obtener email con get_email_field_name() fechaNac = models.DateField() nombre = models.CharField(max_length=15) #get_full_name()??? apellido = models.CharField(max_length=15) telefono = models.CharField(max_length=9) regiones = models.CharField(max_length=40) comunas = models.CharField(max_length=40) tipo_viviendas = ((1,'Casa con … -
CSV not saving in django db
I am trying to upload a CSV file to Django, below depicted code is well and no errors popping up but post submit the CSV, data is not being stored in Django db. when I look at the admin page no details present. models.py from django.db import models class Shiftrotainfo(models.Model): first_name=models.CharField(max_length=50) last_name=models.CharField(max_length=50) whichShift = models.CharField(max_length=50) def __str__(self): return f'{self.first_name} {self.last_name}' views.py from django.shortcuts import render from django.http import HttpResponse import csv,io from django.contrib import messages from .models import Shiftrotainfo def home(request): return HttpResponse('<h1>Shift Rota</h1>') def upload_rota(request): template = "shiftrota/rota_upload.html" prompt = { 'order':'order of the CSV name followed by week shift details' } if request.method == "GET": return render(request,template, prompt) csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request,'This is not a CSV file') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): _,created = Shiftrotainfo.objects.update_or_create( first_name=column[0], last_name=column[1], whichShift=column[2] ) context ={} return render(request, template, context) here rota_upload.html {% if messages %} {% for message in messages %} <div {% if message.tags %} class="{{ message.tags }}" {% endif %}> <strong>{{ message|safe }}</strong> </div> {% endfor %} {% else %} {{order}} <form method="post" enctype="multipart/form-data">{% csrf_token %} <label>Upload File</label> <input type="file" name="file"> <p>Only Accepts CSV Files</p> <button type="save">Upload</button> </form> {% … -
DRY in model to capture all values
Is there a cleaner way to get the "ALL" values instead of hardcoding them all? For example, if I added a new value here, I'd need to manually add in that item as well: class EntitySharedLinkPermission(models.Model): OFF = None COMPANY_VIEW = "Company View" COMPANY_EDIT = "Company Edit" PUBLIC_VIEW = "Public View" PUBLIC_EDIT = "Public Edit" ALL_PERMISSIONS = [ EntitySharedLinkPermission.OFF, EntitySharedLinkPermission.COMPANY_VIEW, EntitySharedLinkPermission.COMPANY_EDIT, EntitySharedLinkPermission.PUBLIC_VIEW, EntitySharedLinkPermission.PUBLIC_EDIT ] -
Having NULL as a primary key value
I would like to have an entity as follows: class EntitySharedLinkPermission(models.Model): OFF = None COMPANY_VIEW = "Company View" COMPANY_EDIT = "Company Edit" PUBLIC_VIEW = "Public View" PUBLIC_EDIT = "Public Edit" name = models.CharField(max_length=12, primary_key=True) class Meta: db_table = 'entity_shared_link_permission' However, I cannot have NULL as a primary key value here. What should I do here instead? One idea was to just remove the primary key on this table and have a unique key instead (no PK in the table) to get around this, but surely there must be a better solution. -
Django Multiple classes in Model.py
I am new to Django and Python. I am trying to create a database of babysitters and one of the objects which can have multiple fields is Education. My first Babysitter has 2 qualifications which produces an error an will not display. Error Message Model.py from django.shortcuts import render, get_object_or_404, get_list_or_404 from .models import Babysitter, Education, Work, Reference # Create your views here. def all_babysitters(request): babysitters = Babysitter.objects.all() return render(request, "babysitters.html", {"babysitters": babysitters}) def babysitter_profile(request, id): """A view that displays the profile page of a registered babysitter""" babysitter = get_object_or_404(Babysitter, id=id) reference = get_object_or_404(Reference) education = Education.objects.all() return render(request, "babysitter_profile.html", {'babysitter': babysitter, 'education': education, 'reference': reference} ) views.py from django.db import models from datetime import datetime # Create your models here. class Babysitter(models.Model): list_display = ('firstName', 'lastName', 'minderType') firstName = models.CharField(max_length=50, blank=True, null=True) lastName = models.CharField(max_length=50, blank=True, null=True) minderType = models.CharField(max_length=50, blank=True, null=True) image = models.ImageField(upload_to='images') phone = models.CharField(max_length=20, blank=True, null=True) email = models.CharField(max_length=50, blank=True, null=True) address1 = models.CharField(max_length=100, null=True) address2 = models.CharField(max_length=100, null=True) city = models.CharField(max_length=20, null=True) county = models.CharField(max_length=100, null=True) eircode = models.CharField(max_length=7, null=True) biography = models.TextField(max_length=280,blank=True) def __str__(self): return self.firstName + ' ' + self.lastName class Education(models.Model): babysitter = models.ForeignKey(Babysitter) school = models.CharField(max_length=50) qualification = models.CharField(max_length=50) fieldOfStudy …