Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Exporting and Importing a foreign key field that has a many-to-many relationship in Django
I've got a complicated relationship between my Django models and I'm trying to get django-import-export to play nicely. class Person(models.Model): name = models.CharField(max_length=64) class Team(models.Model): rep = models.ManyToManyField(Person, related_name="rep") def get_reps(self): return "/".join(sorted([p.name for p in self.reps.all()])) class Account(models.Model): tid = models.IntegerField("Territory ID", primary_key=True) name = models.CharField("Territory Name", max_length=64) sales_team = models.ForeignKey(Team, related_name="sales_team") I'm trying to export (and hopefully later import) the territories with the names of the reps as rendered by the get_reps method. class TerritoryResource(resources.ModelResource): tid = fields.Field(attribute='tid', column_name="Territory ID") name = fields.Field(attribute='name', column_name="Territory Name") sales_team = fields.Field( column_name="Sales Team", widget=widgets.ForeignKeyWidget(Team, "get_reps") ) The export is giving me a blank field. If I don't use the widget I get the Team ID as I'd expect. Is it possible to get my custom name in the export? -
An error in my relation, violates unique constraint
I'm working on a small project using Django, A task can be only in one status, The Error i get : duplicate key value violates unique constraint "task_task_status_id_de4e8cac_uniq" DETAIL: Key (status_id)=(1) already exists. What kind of relationship must I do between the two models? This is my models : class Task(models.Model): status = models.ForeignKey(Status, related_name="tasks", on_delete=models.CASCADE) title = models.CharField(max_length=60, blank=False, null=False) class Status(models.Model): title = models.CharField(blank=False, null=False, max_length=255) slug = models.CharField(blank=False, null=False, max_length=255) order = models.SmallIntegerField(default=0) def __str__(self): return self.title -
Django and Apache Server Configuration
I implemented a Django project with MySQL backend. It runs well using "Python manage.py runserver." Apache seems installed well with no errors. I can access the default apache server. However, I couldn't make the apache web server and Django work together. I followed the link below. https://studygyaan.com/django/how-to-setup-django-applications-with-apache-and-mod-wsgi-on-ubuntu I edited 000-default.conf and djangoproject.conf on the server. Could you give me some advice where I should look into? Version information. Python: 3.8.5 Django: 3.0 Ubnutu: 20.04 When I run "sudo systemctl status apache2" ● apache2.service - The Apache HTTP Server Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled) Active: active (running) since Wed 2021-04-14 17:18:03 UTC; 6 days ago Docs: https://httpd.apache.org/docs/2.4/ Main PID: ****(apache2) Tasks: ** (limit: **) Memory: M CGroup: /system.slice/apache2.service ├─ **** /usr/sbin/apache2 -k start ├─ /usr/sbin/apache2 -k start └─ /usr/sbin/apache2 -k start -
Dynamically added form fields in Django are not added to the form's cleaned_data
Values from fields that are added to an instance of a Django form - but which are not present in the class definition - do not seem to be added to the form's cleaned_data. (There are other threads on this topic, but they do not seem to provide a satisfying answer or solution.) In Django 3.8 there is comment in the __init__ function of the class BaseForm, on line 82 in the script django/forms/forms.py, which reads # The base_fields class attribute is the *class-wide* definition of # fields. Because a particular *instance* of the class might want to # alter self.fields, we create self.fields here by copying base_fields. # Instances should always modify self.fields; they should not modify # self.base_fields. The comment implies that it is indeed intended that the dictionary self.fields be modified with fields that are constructed for a given instance rather than for the whole class. But since the values of these dynamically added fields are not delivered to the self.cleaned_data, it seems as if the forms can not be used for anything. So why do they allow and encourage the use of this possibility? It seems completely pointless if they can not be used. I wrote … -
Foreignkey issue, Key (status_id)=(1) already exists
I'm working on a small project ( Kanban Board ) using Django / Rest Framework, I have two models Status(columns) and Task model, A task can be only in one column since we drag the task from column to column, which means a task can be only in one column. I did an OneToMany relationship by making a Foreign key, but I'm not sure if it's the correct choice because I'm getting an error when I try to add a new task. The Error i get : duplicate key value violates unique constraint "task_task_status_id_de4e8cac_uniq" DETAIL: Key (status_id)=(1) already exists. What kind of relationship must I do between the two models? This is my models : class Task(models.Model): status = models.ForeignKey(Status, related_name="tasks", on_delete=models.CASCADE) title = models.CharField(max_length=60, blank=False, null=False) class Status(models.Model): title = models.CharField(blank=False, null=False, max_length=255) slug = models.CharField(blank=False, null=False, max_length=255) order = models.SmallIntegerField(default=0) def __str__(self): return self.title -
Unique=True in Form not throwing any error
I'm entering a duplicate value (already saved in another instance of the same model) in my form to test the unique=True attribute. form.is_valid() returns 'False', as expected, but I don't receive any prompt in the template. Shouldn't I get prompted something like "obj with this value already exists"? The page simply reloads... What am I missing? forms.py def update_route(request, pk): instance = Route.objects.get(id=pk) if request.method == "POST": form = RouteForm(request.POST) if form.is_valid(): data = form.cleaned_data instance.name = data['name'] instance.priority = data['priority'] instance.url = data['url'] return redirect('campaigns:routes_list') form = RouteForm(instance=instance) context= { 'form': form, } return render(request, "campaigns/route_form.html", context) models.py class Route(models.Model): name = models.CharField(max_length=48) priority = models.SmallIntegerField(choices=PRIORITY_LEVEL, default=0, unique=True) url = models.URLField() Template <form method="post" action=""> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> -
Docker error using pipenv with django app
I'm encountering this error when trying to dockerize a django app as part of a tutorial I'm following. --system is intended to be used for pre-existing Pipfile installation, not installation of specific packages my directory looks like this C:. │ db.sqlite3 │ Dockerfile │ manage.py │ Pipfile │ Pipfile.lock │ ├───config │ asgi.py │ settings.py │ urls.py │ wsgi.py │ __init__.py │ └───pages │ admin.py │ apps.py │ models.py │ tests.py │ urls.py │ views.py │ __init__.py │ └───migrations __init__.py and the contents of my pipfile [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django = "~=3.2.0" [dev-packages] [requires] python_version = "3.9" and dockerfile # Pull base image FROM python:3.9 #set environment vars ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # set work directory WORKDIR /hello # install dependancies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv RUN pipenv install --system # copy project COPY . /hello/ the full error message is \hello>docker build . [+] Building 1.8s (9/10) => [internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 32B 0.0s => [internal] load .dockerignore 0.0s => => transferring context: 2B 0.0s => [internal] load metadata for docker.io/library/python:3.9.4 0.7s => [1/6] FROM docker.io/library/python:3.9.4@sha256:07c51c65ab9c1a156a1fb51eff3ec04feff7b85b2acb7d6cc65148b218d67402 0.0s => [internal] … -
Django REST: Set Object Filter to URL Parameter
I'm a noob when it comes to Django and REST, so please bear with me. I am trying to set a filter variable to equal a url paramater. The URL parameter is simple: foo.com/api/physicians/2 The way I'd like it work work is to set the URL parameter to the lookup field, like so: class DepartmentsAndPhysiciansViewset(viewsets.ModelViewSet): lookup_field = 'department_id' serializer_class = DepartmentsAndPhysiciansSerializer queryset = Physicians.objects.filter(department_id=lookup_field) But that returns: ValueError: Field 'id' expected a number but got 'department id'. So I set the department id manually like so: class DepartmentsAndPhysiciansViewset(viewsets.ModelViewSet): lookup_field = 'department_id' serializer_class = DepartmentsAndPhysiciansSerializer queryset = Physicians.objects.filter(department_id=5) And it works. Obviously I can't hardcode the department id, it needs to come from a URL parameter. Is there any way to set the URL parameter to be equal to the lookup field (department id)? Thanks! -
How to use annotate to Count items from a Django QuerySet
I am modeling Applications and the ways they are installed on user's devices as follows: class WindowsUserApplications(models.Model): application_name = models.CharField(max_length=60, null=False, unique=True) category = models.ForeignKey('ApplicationCategory', null=False, default=10, on_delete=models.SET_DEFAULT) class WindowsUserInstalls(models.Model): device_name = models.CharField(max_length=15, null=False) version = models.CharField(max_length=30, null=False) application = models.ForeignKey('WindowsUserApplications', related_name='windows_user_applications', null=False, on_delete=models.CASCADE) And then, on the view I want to get a list of the installed applications like this: def user_inventory(request, *args, **kwargs): user_applications = WindowsUserInstalls.objects.annotate(Count('application')) template = 'webapp/user_inventory.html' context = { 'user_applications' : user_applications, } return render(request, template, context) However, I keep getting repeated lines for the installed apps and all of them with an install count of 1, instead of getting them summarized. I have tried other approaches such as adding .values('application') to the query, with no luck. Thanks in advance for any hints. -
django grandparent parent child relationship
I have Django rest frame work with below model class Grandparent(models.Model): grandparent_name = CharField(max_length=20) class Parent(models.Model): grandparent = ForeignKey(Grandparent) parent_name = CharField(max_length=20) class Child(models.Model): parent = ForeignKey(Parent) grandparent = ForeignKey(Grandparent) child_name = CharField(max_length=20) All 3 models are registered in admin.py. When adding a entry into child model from django admin site, dropdowns for parent and grandparent are independent. In other words, I could select a grandparent and parent, that aren't bound as in "Parent" table. Here is what I want to achieve: When a grandparent is selected, parent field should show only a dropdown list that have the selected grandparent per "Parent" model. How could I achieve this? -
how to use Django template if condition inside Django Template?
{% if len(verifiedJobs) > 0 %} {% for v in verifiedJobs %} companyname:::{{v.companyname}}<br> jobDescription::::{{v.jobDescription}}<br> salary:::{{v.salary}}<br> {% endfor %} {% endif %} this is my code and it is not working it is giving errors about my if condition. -
Output Dates in Celery Crontab Schedule to Django Template
I'm using Celery for my Django project and I've scheduled some crontab tasks to send emails out to users at certain times. I need to output a schedule in an HTML/Django template that shows the dates that users can expect the emails to go out on. My crontab schedule looks like this for Celery: import os from celery import Celery from celery.schedules import crontab app = Celery("myapp") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print("Request: {0!r}".format(self.request)) first_monday_april_to_july = crontab( minute=15, hour=6, day_of_week="monday", day_of_month="1-7", month_of_year="4,5,6,7" ) august_every_monday_first_two_weeks = crontab( minute=15, hour=6, day_of_week="monday", day_of_month="1-14", month_of_year="8" ) august_weekdays_second_two_weeks = crontab( minute=15, hour=6, day_of_week="mon-fri", day_of_month="15-31", month_of_year="8" ) app.conf.beat_schedule = { "report1": { "task": "email_report", "schedule": first_monday_april_to_july, }, "report2": { "task": "email_report", "schedule": august_every_monday_first_two_weeks, }, "report3": { "task": "email_report", "schedule": august_weekdays_second_two_weeks, } I was hoping to be able to grab all of the dates that the emails will be sent on from these tasks and save them into a list in the view and then send it to the template to be displayed in a table. Is something like this possible? I'm not having any luck finding a way to do this so far. -
Django - Button that will change a field in a model
I am building a scrum application where there are Sprint and User Story objects. I want the user to be able to click a button on the Sprint detail template and for a BooleanField in the model to be changed from False to True, marking the Sprint as complete. I have tried to think but not sure how I can about this? Here is my models.py: from django.db import models from django.contrib.auth.models import User, Group class Sprint(models.Model): LENGTH_CHOICES = (('1_week', '1 Week'), ('2_weeks', '2 Weeks'), ('3_weeks', '3 Weeks')) name = models.CharField(max_length=200) created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sprints", null=True) project = models.ForeignKey(Group, on_delete=models.CASCADE, related_name="sprints", null=True) start_date = models.DateField(auto_now = False, auto_now_add = False) end_date = models.DateField(auto_now = False, auto_now_add = False) duration = models.CharField(max_length = 10, choices = LENGTH_CHOICES) complete = models.BooleanField(null = True, default = False) retrospective = models.CharField(max_length=10000, null=True) def __str__(self): return self.name class UserStory(models.Model): STATUS_CHOICES = (('To Do', 'To Do'),('In Progress', 'In Progress'), ('In Review', 'In Review'), ('Complete', 'Complete')) STORY_POINTS = ((0, 0), (1, 1), (2, 2), (3, 3), (5, 5), (8, 8), (13, 13), (20, 20), (40, 40), (100, 100)) name = models.CharField(max_length=300) sprint = models.ForeignKey(Sprint, on_delete=models.CASCADE, related_name="userstories", null=True) description = models.CharField(max_length=300) status = models.CharField(max_length = 11, choices … -
Backend subscribe system
Hello my dear great programmers. I am new to this case, and I have one question. I wrote an online registration system for the course, and came out a few problems. like thisPlease help a beginner programmer. I have created a multi-page html website, and it has sections like my courses, available courses, available courses page has different courses, and there is a subscribe button, I want when I click on subscribe button, it will show up on my courses website. Can you please help me to solve this problem -
How do I make each individual a user from a model?
This is probably simple but for me it has proved to be a headache. I'd like to make each teacher from TeacherData model to be a user using the first_name as the username and email as the password. Here are my models. School model class School(models.Model): name = models.CharField(max_length=100,null=True,blank=True) User model class User(AbstractUser): school = models.ForeignKey(School, on_delete=models.DO_NOTHING, null=True, blank=True) is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) Teacher's model class TeacherData(models.Model): school = models.ForeignKey(School,on_delete=models.CASCADE) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email = models.EmailField() If there's anything else required let me know and I'll add it. -
Setting fieldsets with non-model fields with Django ModelForm
I have a modelForm and modelAdmin that both inherit the same Django models. I want to add a field to the form that will not occupy a field in the model, but will be used elsewhere. That's all and well, I can simply add a new field to the form. However, my fieldsets for the modelAdmin class that I use for the add/change views do not accept any entry that is not a model field. How should I work around this? -
Italic on first 2 words of datatable table
I'm making an academic bibliography table on my django website.On the second collumn of my datatable the first two words need to be on itallic! How can i go about this? -
Unable to render images in caraousel from database in django?
I am trying to render images from my database to carousel in Django. I have a model which contains url fields to store images url but when I use them in (template.html) my carousel img src, it only renders 1st image but not others even though I have three images url stored in database. To understand it better here is my code. models.py from django.db import models # Create your models here. class CaraouselData(models.Model): title = models.CharField(max_length=100, null=False) description = models.TextField(max_length=200, null=True) image = models.URLField(null = False, default=True) def __str__(self): return self.title views.py def home(request): caraousel_data = CaraouselData.objects.all() return render(request, 'index.html', context={ 'caraousel_data': caraousel_data, }) template.js {% block content %} {# Caraousel Data Section#} <div class="container-fluid p-0"> <div id="carouselExampleCaptions" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1" aria-label="Slide 2"></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="2" aria-label="Slide 3"></button> </div> {# images fetching from models #} <div class="carousel-inner"> {% for item in caraousel_data %} <div class="carousel-item {% if forloop.counter0 == 0 %} active" {% endif %}> <img src="{{ item.image }}" width="600" height="670" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> <h5>{{ item.title }}</h5> <p>{{ item.description }}</p> </div> </div> {% endfor %} {% endblock %} -
Django add product quantity through <input type="number">
I am trying to build an e-commerce website and learn more about Django. I am experiencing problem understanding how to add product quantity through and when you press add to cart button to send this amount to the cart. Could you please explain it to me? Here is the code that I have: SHOP API ADD TO CART def api_add_to_cart(request): data = json.loads(request.body) jsonresponse = {'success': True} product_id = data['product_id'] update = data['update'] quantity = data['quantity'] cart = Cart(request) product = get_object_or_404(Product, pk=product_id) if not update: cart.add(product=product, quantity=1, update_quantity=False) else: cart.add(product=product, quantity=quantity, update_quantity=True) return JsonResponse(jsonresponse) SHOP PAGE VUE.JS INLINE SCRIPT <script> var productapp = new Vue({ el:'#productapp', delimiters:['[[', ']]'], store: store, data() { return { } }, mounted() { console.log('Mounted'); }, methods: { addToCart(product_id) { console.log('Product_id:', product_id); var data = { 'product_id': product_id, 'update': false, 'quantity': 1 }; fetch('/api/add_to_cart/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' }, credentials: 'same-origin', body: JSON.stringify(data), }) .then((response) => { console.log(response) store.commit('increment', 1) function cartMessage() { document.getElementsByClassName('cart__message').style.display = 'flex'; } cartMessage(); }) .catch(function (error) { console.log('Error 2'); }) } } }) </script> I more or less understand that it has something to do with fetching name of the input and passing … -
Prevent Websocket DoS attack with nginx
I've noticed that someone could easily crash my website using a simple javascript while loop that continuously sends stuff like so: while(true) { websocket.send(JSON.stringify({})); } I'm using nginx which passes ws-requests to daphne which in turn talks to django-channels. This is the relevant configuration part: location /ws/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; limit_conn addr 10; proxy_pass http://daphne; } Is there any easy way to prevent this? An upper limit for the datastream would be super. The websocket connection is used for things that may send several messages within a few (hundred?) milliseconds (WebRTC and game related stuff). -
Django: how to keep track of order for items of a model
I have a model: class Recipe(models.Model): name=models.CharField() class Ingredients(models.Model): name=models.CharField() class RecipeIngredients(models.Model): recipe=models.ForeignField(Recipe) ingredients = models.ForeignField(Ingredients) I am creating RecipeIngredients, but i want to show them in a sequence Sometime i have to add an ingredient inbetween. So in such cases how to keep the order while getting them -
Django - Manually Deleting an App from the Database
So I'm working on a Django project, in which I've done some significant refactoring to data models. I'm currently working on a local developer build, and by far the easiest way to migrate these changes has been to delete and re-make the database. I obviously can't do that to the production database, but the original models have already been migrated there. Since I can't delete the ENTIRE database, I want to go in and manually delete all the tables and migrations related to this module then run a new initial migration. This module isn't in use yet on production, and even if it were the data is synced from another service so it's recoverable. I've dug into the way Django does migrations a bit, so I know there's some tables Django uses that aren't directly related to my models. My question is do I need to change anything to make this work besides deleting the model tables (i.e. appname_modelname) and clearing the relevant row(s) from the django_migrations table? I know it's kind of a janky way to do what I want, but actually getting the migrations to run for my refactoring would be a huge hassle and this workaround should … -
KeyError: 'torch', memory error ERROR: ServiceError - Failed to deploy application.: AWS elastic beanstalk, django
I am trying to deploy my django app on AWS elastic beanstalk but I am facing the following error. 2021-04-20 18:00:43 INFO Environment update is starting. 2021-04-20 18:00:46 INFO Deploying new version to instance(s). 2021-04-20 18:00:57 ERROR Instance deployment failed to install application dependencies. The deployment failed. 2021-04-20 18:00:57 ERROR Instance deployment failed. For details, see 'eb-engine.log'. 2021-04-20 18:01:01 ERROR [Instance: i-0eee746bc342a71cd] Command failed on instance. Return code: 1 Output: Engine execution has encountered an error.. 2021-04-20 18:01:01 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2021-04-20 18:01:01 ERROR Unsuccessful command execution on instance id(s) 'i-0eee746bc342a71cd'. Aborting the operation. 2021-04-20 18:01:01 ERROR Failed to deploy application. My eb-engine.log Downloading https://download.pytorch.org/whl/cpu/torchvision-0.6.1%2Bcpu-cp37-cp37m-linux_x86_64.whl (5.7 MB) Collecting torch==1.8.1+cpu 2021/04/20 18:00:57.931655 [ERROR] An error occurred during execution of command [app-deploy] - [InstallDependency]. Stop running the command. Error: fail to install dependencies with requirements.txt file with error Command /bin/sh -c /var/app/venv/staging-LQM1lest/bin/pip install -r requirements.txt failed with error exit status 2. Stderr:ERROR: Exception: Traceback (most recent call last): File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/resolvelib/resolvers.py", line 171, in _merge_into_criterion crit = self.state.criteria[name] KeyError: 'torch' . . . . File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/msgpack/fallback.py", line 671, in _unpack ret[key] = self._unpack(EX_CONSTRUCT) File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/msgpack/fallback.py", line 684, in _unpack return bytes(obj) MemoryError My requirements.txt … -
Django's Model ContentType id is different between two databases
Basically I am running into a problem with Django's ContentType table behaviour My project and tests run just fine locally, but they don't work in production because it seems a model's contenttype ID is different between the two. My local looks as follow: ContentType.objects.get(app_label='app', model='ticket').id // (prints 347) Prod: ContentType.objects.get(app_label='app', model='ticket').id // (prints 348) and my fixtures look like this [ { "model": "app.attachment", "pk": "dc81fd8d-1729", "fields": { "content_type": 347, "object_id": "04d0d75d-b249e3f", } }, ] so obviously when during my test I happen to do this: // self.ticket_content_type_id = ContentType.objects.get(app_label='app', model='ticket').id self.attachments = Attachment.objects.all() attachment = self.attachments.filter(content_type=self.ticket_content_type_id).first() // returns None Any idea why that offset? What should I do to fix it? What may have caused this in the first place? Thank you in advance! -
Django model form applying user viewing data as the user from form
I have a model form which adds fields (email, latitude etc) and then my views.py attaches the user to the form before it saves. However, when I look at the data in the admin panel, it just assigns my username to all of the entries. If I log in as a different user, I get the same form entries but all with the new username attached. Views.py form = SafezoneForm() if request.method == 'POST': form = SafezoneForm(request.POST) if form.is_valid(): instance = form.save(commit=False) Safezone.userid = request.user #### gets username here and assigns to model instance.save() return redirect('loadingsafezone') context = {'form':form} return render(request, 'V2maparonno_create_safe_zoneV2.html', context) models.py class Safezone(models.Model): userid = models.ForeignKey(User, on_delete=models.CASCADE, null=True) useremail = models.EmailField(max_length=100) name = models.CharField(max_length=100, null=True) latitudecentre = models.FloatField(null=True) longitudecentre = models.FloatField(null=True) latcorner1 = models.FloatField(null=True) latcorner2 = models.FloatField(null=True) latcorner3 = models.FloatField(null=True) latcorner4 = models.FloatField(null=True) longcorner1 = models.FloatField(null=True) longcorner2 = models.FloatField(null=True) longcorner3 = models.FloatField(null=True) longcorner4 = models.FloatField(null=True) def save(self, *args, **kwargs): self.longcorner1 = self.longitudecentre - 0.6 self.longcorner2 = self.longitudecentre + 0.6 self.longcorner3 = self.longitudecentre + 0.6 self.longcorner4 = self.longitudecentre - 0.6 self.latcorner1 = self.latitudecentre - 0.6 self.latcorner2 = self.latitudecentre - 0.6 self.latcorner3 = self.latitudecentre + 0.6 self.latcorner4 = self.latitudecentre + 0.6 super(Safezone, self).save(*args, **kwargs) def __str__(self): return self.userid or …