Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: taking user input from html, processing it and showing output in the same page
I am quite new in Django and stuck at specific point. I want to take user input from html that goes into database, process it with specific python script and return result to the same html page. I want Users to enter score in "exam_score" line, then process that input with specific python script and then to output result to "uni_name_1_result". For now, python script that just prints 'Hello world' is enough, just want to understand the mythology of how it can be done. Would appreciate any help. models.py from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. class User(models.Model): first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) email = models.EmailField(max_length=254,unique=True) exam_score = models.FloatField(null=True, validators=[MinValueValidator(0.0),MaxValueValidator(700)]) uni_name_1 = models.CharField(max_length=254) uni_name_1_result = models.CharField(max_length=254) forms.py from django import forms from django.core import validators from ielts_app.models import User class NewUserForm(forms.ModelForm): # validations can be set here class Meta(): model = User fields = '__all__' views.py from django.shortcuts import render # from ielts_app import forms from ielts_app.forms import NewUserForm # from django.http import HttpResponseRedirect def index(request): return render(request,'ielts_app/index.html') def users(request): form = NewUserForm() if request.method == 'POST': form = NewUserForm(request.POST) if form.is_valid(): variable:form.cleaned_data form.save(commit=True) # to save forum data (user data), commit=True … -
DRF: access serializer fields outside meta
So, i need to get the "like" status on posts, and need my serialzier to return attr "liked" bool. I am trying to get the current post being serialized, pass it into a query which will either return true or false. -
Saving data from different forms to different table using one view Django
I have five different Models and each model have different fields.I have created five form for the respective models.Please refer the below code.I am getting used_for from url and I am using used_for for identifying which form has been triggered to save the data.Its working for me I just wanted to know is this a good way to this or is there any another way.I dont want to create fie different views to save the data views.py def contract_details(request,used_for): if request.method == "POST": if used_for == "contractmanager": form = ContractForm(request.POST) elif used_for == "contractlineitem": form = ContractLineItemForm(request.POST) elif used_for == "billingtype": form = BillingTypeForm(request.POST) else: messages.info(request,"Invalid Form") return redirect("useradmin:revenue_manager") if form.is_valid(): form.save() messages.success(request,"Contract Saved Successfully.") return redirect("useradmin:revenue_manager") urls.py urlpatterns = [ path("add",views.add_admin,name = "add_admin"), path("view",views.view_admin,name = "view_admin"), path("timezone/", views.add_timezone, name = "timezone"), path("timezone/delete/<int:id>/", views.delete_timezone, name = "deletetime"), path("language/", views.add_language, name = "language"), path("language/delete/<int:id>/", views.delete_language, name = "deletelanguage"), path("organization/", views.add_organization, name = "organization"), path("organization/delete/<int:id>/", views.delete_organization, name = "deleteorganization"), path("revenue-manager/", views.revenue_manager, name = "revenue_manager"), path("revenue-manager/bulk-add/<str:data>", views.data_upload, name = "bulk_add"), path("revenue-manager/export-data/", views.export, name = "export_data"), path("add-contract/<str:used_for>/", views.contract_manager, name = "add_contract"), ] -
DJANGO: Group by two fields and aggregate a method's return value
How to group records by two fields, and then take the sum of a method's return value? I have the following model: class Invoice(models.Model): client = models.ForeignKey(Client, on_delete=models.DO_NOTHING) date = models.DateField() quantity = models.IntegerField() price = models.DecimalField(max_digits=18, default=2) def total_amount(self): return self.quantity * self.price I want to group records of Invoice by year of date, and client, and take the sum of total_amount for each year for each client. The output should look something like this: top_companies = {"2021": {"Company 1": 22000.0, "Company 2": 20000.0}, "2020": {"Company 2": 40000.0, "Company 1": 10000.0}} -
save() takes 1 positional argument but 2 were given
I am trying to register as a seller ( is_seller=True). But I am getting this issue of save() function cant take two positional arguments. I tried passing *args and **kwargs as well, but it is still not working. My models: class CustomUser(AbstractUser): # username = models.CharField(max_length=255,) first_name = models.CharField(max_length=255, verbose_name="First name") last_name = models.CharField(max_length=255, verbose_name="Last name") email = models.EmailField(unique=True) is_seller = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] objects = CustomUserManager() def __str__(self): return self.email My serializers: class SellerRegisterSerializer(serializers.ModelSerializer): seller = serializers.PrimaryKeyRelatedField(read_only=True,) phone_num = serializers.CharField(required=False) class Meta: model = User fields = ['seller','email', 'phone_num', 'first_name', 'last_name', 'password'] def get_cleaned_data(self): data = super(SellerRegisterSerializer, self).get_cleaned_data() extra_data = { 'phone_num': self.validated_data.get('phone_num', ''), } data.update(extra_data) return data def save(self, request,*args, **kwargs): user = super(SellerRegisterSerializer, self).save(request) user.is_seller = True user.save() seller = Seller(seller=user, phone_num=self.cleaned_data.get('phone_num')) seller.save(*args, **kwargs) return user My view: class SellerRegisterView(RegisterView): serializer_class = SellerRegisterSerializer My urls: path("api/seller/register/",SellerRegisterView.as_view(), name='api-registerseller'), -
how to apply serial number in model.py in python django
we have a table that contains row and column we need one more column that will show serial number of row. It mean when user will update the table the serial number will update automatically. -
django reduce number of database queries on bulk-update
so I have functions like this in my reusable manager class. @query_debugger def update_object_positions(self, data: list, overwrite_objects): """ Updates object positions for the given array of overwrite objects. Removes unchanged data from the current list of objects and puts it back in after sorting the list. Expects a list of serialized object-data, consisting of the id and the changed-position of the respective objects. """ if overwrite_objects.count() < 2: # we don't update positional values for objects if none or # only one of the same is found, because it doesn't make # any sense to do the same. Objects only change their positions to be # shifted among each other. model_name_plural = self.model._meta.verbose_name_plural.title() raise exceptions.ValidationError(detail=f'less than two {model_name_plural} found') collected_data = {obj['id']: obj['position'] for obj in data} changed_objects = overwrite_objects.filter(id__in=collected_data.keys()) for obj in changed_objects: obj.position = collected_data[obj.id] rotated = self.perform_rotate(changed_objects, overwrite_objects) self.overwrite_object_positions(rotated) @query_debugger def overwrite_object_positions(self, data: list): """ Overwrites object-positions, enclosed within a transaction. Rolls-back if any error arises. We need a transaction here because all of our positional objects have a deferring unique constraint over their positions. """ cleaned = [obj for obj in data if not hasattr(obj, 'is_default') or not obj.is_default] self.model.objects.bulk_update(cleaned, ['position']) for instance in cleaned: # … -
can a django login api be created without using django auth model
Can a django login rest api be created completely from scratch, build with custom model and not inbuilt. I've been trying but cannot understand how to create it. -
Django Rest Framework: Send full foreign key objects in GET response but accept only foreign ids in POST payload, without two serializers?
Say I've two models: class Singer((models.Model): name = models.CharField(max_length=200) class Song(models.Model): title = models.CharField(max_length=200) singer = models.ForeignKey(Singer) And two serializers like: class SingerSerializer(serializers.ModelSerializer): class Meta: model = Singer fields = '__all__' class SongSerializer(serializers.ModelSerializer): singer = SingerSerializer() class Meta: model = Singer fields = '__all__' I've defined the serializers as above because I need the full foreign key object in the GET response for songs: { "singer": { "id": 1, "name": "foo" }, "id": 1, "title": "foo la la" } Is there a way to allow POST/PATCH payloads to only send in the id of the foreign object and not the entire object, without writing a different serializer? I'd like the PATCH payload to be so: { "singer": 1, "id": 1, "title": "foo la la" } -
TypeError: cannot serialize '_io.BufferedRandom' object While trying to upload file in Django
I am trying to upload some files in Django but sometimes when the file size increases it gives the following error: TypeError: cannot serialize '_io.BufferedRandom' object In the current case I am trying to upload a file(size ~3Mb) but it's still showing the error. I tried to check in the network that if the file has been uploaded or not but it shows: I am unable to understand what changes I need to make in order to resolve this -
Loading an object inside an object in a Django template
So I have an object that has a foreign key of another object. Whenever I load that object into a template and access said object, I get an error. <td><a href="{% url 'agente' 'Mark' %}" target="_blank">{{ ticket.get_agente }}</a></td> int() argument must be a string, a bytes-like object or a number, not 'Agente' I even tried adding a get_id after getting the object but displays the same error. Seems like the fact that it's an object inside an object confuses Django. -
Zappa is not invoking the right Virtual env correctly while deploy
I am trying to deploy a Django app with Zappa using. I have created virtualenv using pyenv. Following commands confirms the correct virtualenv ▶ pyenv which zappa /Users/****/.pyenv/versions/zappa/bin/zappa ▶ pyenv which python /Users/****/.pyenv/versions/zappa/bin/python But when I am trying to deploy the application using zappa deploy dev following error is thrown ▶ zappa deploy dev (pip 18.1 (/Users/****/.pyenv/versions/3.6.9/envs/zappa/lib/python3.6/site-packages), Requirement.parse('pip>=20.1'), {'pip-tools'}) Calling deploy for stage dev.. Oh no! An error occurred! :( ============== Traceback (most recent call last): File "/Users/****/.pyenv/versions/3.6.9/envs/zappa/lib/python3.6/site-packages/zappa/cli.py", line 2778, in handle sys.exit(cli.handle()) File "/Users/****/.pyenv/versions/3.6.9/envs/zappa/lib/python3.6/site-packages/zappa/cli.py", line 512, in handle self.dispatch_command(self.command, stage) File "/Users/****/.pyenv/versions/3.6.9/envs/zappa/lib/python3.6/site-packages/zappa/cli.py", line 549, in dispatch_command self.deploy(self.vargs['zip']) File "/Users/****/.pyenv/versions/3.6.9/envs/zappa/lib/python3.6/site-packages/zappa/cli.py", line 723, in deploy self.create_package() File "/Users/****/.pyenv/versions/3.6.9/envs/zappa/lib/python3.6/site-packages/zappa/cli.py", line 2264, in create_package disable_progress=self.disable_progress File "/Users/****/.pyenv/versions/3.6.9/envs/zappa/lib/python3.6/site-packages/zappa/core.py", line 627, in create_lambda_zip copytree(site_packages, temp_package_path, metadata=False, symlinks=False, ignore=shutil.ignore_patterns(*excludes)) File "/Users/****/.pyenv/versions/3.6.9/envs/zappa/lib/python3.6/site-packages/zappa/utilities.py", line 54, in copytree lst = os.listdir(src) FileNotFoundError: [Errno 2] No such file or directory: '/Users/****/mydir/zappa/env/lib/python3.6/site-packages' ============== You can see the line at which error is thrown is different where virtualenv is installed. I don't know why Zappa deploy is looking for the site-packages here. -
How to add a filter in django for every request?
I want to add a security filter so that every request to my django app will go through the filter first and then let the request go through if the token from the header is valid. How can I accomplish that in django? Thanks. -
Is VS code better than pycharm when starting out with Django?
I am trying to understand the best platform for a free code editor -
GET 'today' data in Django-Filter/DRF
I'm trying to get the today or yesterday data from the current day using django-filter/DRF. class SampleFilter(filters.FilterSet): start_date = DateTimeFilter(field_name='timestamp', lookup_expr='gte') end_date = DateTimeFilter(field_name='timestamp', lookup_expr='lte') class Meta: model = Sample fields = [] on my django-rest api url. when I get the data start_date=${start}&end_date=${end} for the dates of today, it returns zero data even it have in the database. "GET /api/v1/rainfall/?start_date=2021-02-02&end_date=2021-02-02 HTTP/1.1" 200 2" it is 200 success but it returns nothing. What's wrong in my code? please help. thanks! -
how to redirect “print” command and the output of the script to Django3 template?
Views.py def configure(request): all_devices = Devices.objects.all() if request.method == "POST": for i in all_devices: platform = "cisco_ios" ssh_connection = ConnectHandler( device_type=platform, ip=i.IpAdd, username=i.username, password=i.password, ) output = ssh_connection.send_command("show ip arp\n") print(output) return render(request, "configure.html", {"output": all_devices}) ======================================================================== output from the console / terminal: February 03, 2021 - 07:57:28 Django version 3.1.5, using settings 'project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Protocol Address Age (min) Hardware Addr Type Interface Internet 192.168.15.177 3 000c.298a.429a ARPA FastEthernet0/0 Internet 192.168.15.184 - ca01.129a.0000 ARPA FastEthernet0/0 Protocol Address Age (min) Hardware Addr Type Interface Internet 192.168.15.177 3 000c.298a.429a ARPA FastEthernet0/0 Internet 192.168.15.185 - ca02.1227.0000 ARPA FastEthernet0/0 Protocol Address Age (min) Hardware Addr Type Interface Internet 192.168.15.1 0 0050.56c0.0008 ARPA Ethernet0/0 Internet 192.168.15.2 3 0050.56ef.adc2 ARPA Ethernet0/0 Internet 192.168.15.164 100 000c.298c.2625 ARPA Ethernet0/0 Internet 192.168.15.177 3 000c.298a.429a ARPA Ethernet0/0 Internet 192.168.15.186 - aabb.cc00.3000 ARPA Ethernet0/0 [03/Feb/2021 07:57:32] "POST /configure/ HTTP/1.1" 200 1454 configure.html == Templates {% extends "base.html" %} {% load static %} {% block content %} {% csrf_token%} {{form}} {{output}} {% endblock content %} {% block result %} {% endblock result %} I'm getting: <QuerySet [<Devices: Reflect>, <Devices: Reflect2>, <Devices: Reflect-SW>]> Thank You. -
Create HTML/JS matrix in django template
I have a view which returns this data in dictionary form: {('ACCOUNTS', 'Staff'): 8, ('ACCOUNTS', 'TOA'): 3, ('HR', 'Officer'): 4, ('HR', 'Staff'): 1} I need to convert this dictionary to a matrix in django template. something like this: please note the dictionary could be any longer. -
Why am I getting django.db.models error telling me I have no attribute for TextChoices in Django (3.1.6) and Python(3.8)?
thanks so much for reading. I've got this running on my computer no problem. It's working on my VS on Windows 10. But this error keeps coming up, it looks like TextChoices is no longer usable? AttributeError: module 'django.db.models' has no attribute 'TextChoices' I'm putting it u0p on PythonAnywhere, Python 3.8, and Django 3.1.6 I am still new at this, so please forgive me1 My issue is with the TextChoices, here is the full error: Traceback (most recent call last): File "/home/sandorf/project/listings/models.py", line 6, in <module> class Listings(models.Model): File "/home/sandorf/project/listings/models.py", line 7, in Listings class Country(models.TextChoices): AttributeError: module 'django.db.models' has no attribute 'TextChoices' This is my models.py in the app directory from django.db import models from django.utils.timezone import now from datetime import datetime # Create your models here. class Listings(models.Model): class Country(models.TextChoices): USA = "USA" CHINA = "China" CANADA = "Canada" INDIA = "India" UK = "UK" EUROPE = "Europe" MIDDLE_EAST = "Middle East" OTHER = "Other" class Topic(models.TextChoices): STATISTICS = "Statistics" VACCINE = "Vaccine" NEW_STRAINS = "New Strains" LOCKDOWN = "Lockdown" COVID_NEWS = "Covid News" title = models.CharField(max_length=745) link = models.CharField(max_length=745) summary = models.TextField(Null=False) country = models.CharField( max_length=100, choices=Country.choices, default="Country.OTHER") topic = models.CharField( max_length=100, choices=Topic.choices, default="Topic.COVID_NEWS") list_date = models.DateTimeField(default=now) … -
Display the error_messages under the fields
I'm using this package for my form https://github.com/KuwaitNET/djvue but anyway it's like a general question, I've wrote the following method to validate my phone number field def validate_phone_number(self, value): phone_number = to_python(value) if phone_number and not phone_number.is_valid(): self.fields["phone_number"].error_messages.update({"ph":"Wrong"}) raise ValidationError(_(u'The phone number entered is not valid.')) return value and it works just fine because in my Model: def serve(self, request, *args, **kwargs): if request.method == "POST": data = json.loads(request.body) serializer = ContactUsSerializer(data=data) if serializer.is_valid(): ticket_number = serializer.save() return JsonResponse({"ticket_number": ticket_number}) else: return JsonResponse(serializer.errors) ctx = self.get_context(request, *args, **kwargs) ctx["serializer"] = ContactUsSerializer() request.is_preview = getattr(request, "is_preview", False) return TemplateResponse( request, self.get_template(request, *args, **kwargs), ctx ) and actually when I enter an invalid phone number I'm getting a JsonResponse with the error: 0: "The phone number entered is not valid." which is great, but how can I display the updated error message below the phone_number field?? it looks like despite the errors are being updated the displaying is not, should I use Vue or something to achieve that? knowing that the package I'm using does so: <span class="help-block text-danger" v-for="error in errors" :key="error">{( error )}</span> but I'm not sure how and where they render the error, so I want maybe a pure … -
How to send live video captured from opencv in django to aws kinesis-video-streams putmedia endpoint?
To achieve: capture the live feed of a camera in web browser using OpenCV and send it to AWS Kinesis-video-stream(an aws service) using PUT_MEDIA(end_point). Have referred Amazon AWS Kinesis Video Boto GetMedia/PutMedia and made a few changes to capture from camera. HTML Code to display user stream (video captured from webcam): <html> <body> <video autoplay="true" id="myVideo"></video> </body> </html> ''' **views.py** def get_endpoint_boto(): import boto3 client = boto3.client('kinesisvideo','us-east-2',aws_access_key_id = your_env_access_key_var ,aws_secret_access_key = your_env_secret_key_var) response = client.get_data_endpoint( StreamName=your_stream_name, APIName='PUT_MEDIA' ) print(response) endpoint = response.get('DataEndpoint', None) print("endpoint %s" % endpoint) if endpoint is None: raise Exception("endpoint none") return endpoint def sign(key, msg): return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest() def get_signature_key(key, date_stamp, regionName, serviceName): kDate = sign(('AWS4' + key).encode('utf-8'), date_stamp) kRegion = sign(kDate, regionName) kService = sign(kRegion, serviceName) kSigning = sign(kService, 'aws4_request') return kSigning def get_host_from_endpoint(endpoint): if not endpoint.startswith('https://'): return None retv = endpoint[len('https://'):] return str(retv) def get_region_from_endpoint(endpoint): if not endpoint.startswith('https://'): return None retv = endpoint[len('https://'):].split('.')[2] return str(retv) class gen_request_parameters: def __init__(self): self._data = '' if True: print('True') cap = cv.VideoCapture(0) cap.set(5,60) if not cap.isOpened(): exit() ret, frame = cap.read() request_parameters = cap.read() self._data = request_parameters self._pointer = 0 self._size = len(self._data) def __next__(self): print('next') if self._pointer >= self._size: raise StopIteration left = self._size - self._pointer … -
In a journal app, author adding and requests with django
With the following code, i could make a simple journal app.. but i don't know how to control the relations between authors and editor. The thing i want, The Editor must add a author to own journal. and also, authors write an article only to journal to which he/she added. Also i want, authors can send editors request for authorship. How can i construct such a system? class Journal(models.Model): journal_editor = models.ForeignKey(User,on_delete=models.CASCADE,related_name="journal_editor",default=1) unique_id = models.CharField(max_length=100, editable=False, null=True) journal_title = models.CharField(max_length=250, verbose_name="Dergi Adı", blank=False, null=True) slug = models.SlugField(null=True, unique=True, editable=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name = "Dergi" verbose_name_plural = "Dergiler" ordering = ["-created"] def __str__(self): return "%s" % (self.journal_title) def get_unique_slug(self): x = 0 slug = slugify(unidecode(self.journal_title)) new_slug = slug while Journal.objects.filter(slug=new_slug).exists(): x += 1 new_slug = "%s-%s" % (slug, x) slug = new_slug return slug def save(self, *args,**kwargs): if self.id is None: new_unique_id = str(uuid4()) self.unique_id = new_unique_id self.slug = self.get_unique_slug() else: journal = Journal.objects.get(slug=self.slug) if journal.journal_title != self.journal_title: self.slug = self.get_unique_slug() super(Journal, self).save(*args,**kwargs) class Article_of_Journal(models.Model): author_of_article = models.ForeignKey(User,on_delete=models.CASCADE,default=1,related_name="author_of_article") journal_name = models.ForeignKey(Journal,on_delete=models.CASCADE,default=1,related_name="journal_name") unique_id = models.CharField(max_length=100,editable=False,null=True) article_title = models.CharField(max_length=250,verbose_name="Başlık",blank=False,null=True) article_content = RichTextUploadingField(null=True,blank=False,verbose_name="İçerik") slug = models.SlugField(null=True,unique=True,editable=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name = "Makale" verbose_name_plural … -
How to iterate ManyToMany filed in serializer class
I have this Event model: # models.py class Event(models.Model): name = models.CharField(max_length=200)) user = models.ManyToManyField(User)) This is my ListCreateAPIView class: class EventListView(LoginRequiredMixin, generic.ListView): model = Event This is my ListCreateAPIView class: class Events(generics.ListCreateAPIView): permission_classes = (IsAuthenticated,) queryset = Event.objects.all() serializer_class = EventSerializer This is my serialiser class: #serializers,py class EventSerializer(serializers.ModelSerializer): class Meta: fields = ( ‘id', 'name', 'user', ) model = Event And this is my REST request response: { "count": 2, "next": null, "previous": null, "results": [ { "id": 1, "name": "My event1", "user": [ 1, 4 ], "registered": true // <—- I NEED THIS }, { "id": 2, "name": "Other event", "user": [ 2, 4, 6 ], "registered": false // <—- I NEED THIS } ] } What I am gonna need in REST response is property “registered”, which will contain true or false if current user is registered on particular event or not. My approach was to control if current user is in list of users of event. I tried to get this information in serialiser class this way: #serializers,py class EventSerializer(serializers.ModelSerializer): registered = serializers.SerializerMethodField(‘_user’) def _user(self, obj): request = getattr(self.context, 'request', None) if request.user in self.user: return True else: return False class Meta: fields = ( … -
Django: Parent model contain a list child model like a custom template
I'm a newbie Django. Example: I have a parent model Project, child model Phase like this: class Project(models.Model): project_id = models.AutoField(primary_key=True) name = models.CharField(max_length=300) ... def __str__(self): return self.name class Phase(models.Model): phase_id = models.AutoField(primary_key=True) phase_name = models.CharField(max_length=300, default='') project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True) ... def __str__(self): return self.phase_name Question 1: How can I create a custom template is a list of Phase when user create new Project? New Project A: Phase 1 Phase 2 Question 2: And when user change a custom list of Phase, how can I store list and reuse it with another new Project? List Phase Custom: (edit phase: + Phase 3, + Phase 4, - Phase 2) Phase 1 Phase 3 Phase 4 New Project B: Phase 1 Phase 3 Phase 4 Any link references or document relate it? Thank you! -
How to generate models with another model's primary key as the model name in Django
I am working on a django project where the website will let the user to register for an event and let them check in. models.py contains: class Event(models.Model): eventName = models.CharField(max_length=264, unique=True) # Event Name eventDescription = models.TextField() # About the Event I want the program to generate more models with the eventName attribute row values from Event model. Example: Consider that Event model consists of the following row values: CodeChef | CodeChef annual Event GSOC | Google Summer Of Code Then I want the following models to be automatically generated with some predefined attributes (number of attendees, EventStatus): class CodeChef (models.Model): numAtendees = models.IntegerField(default=0) eventStatus = models.BooleanField(default=False) class GSOC (models.Model): numAtendees = models.IntegerField(default=0) eventStatus = models.BooleanField(default=False) PS: I am a beginner to Django. -
Uncaught TypeError: Cannot read property 'replace' of undefined using PostgreSQL database and django
I am getting the following error when I click on a marker deployed from my PostgreSQL database onto a google map. I am expecting an info modal to pop up and show some information. The information that should show up is being posted to the database from a form on my website via an AJAX call. The marker shows up in the correct position but I get this error when I click it: Uncaught TypeError: Cannot read property 'replace' of undefined Here is my AJAX call that posts the data: const commitNewCafe = function () { let name = document.getElementById("venueName").value; let type = document.getElementById("venueType").value; let address = document.getElementById("venueAddress").value; let latitude = parseFloat(document.getElementById("latitude").innerHTML); let longitude = parseFloat(document.getElementById("longitude").innerHTML); $.ajax({ type: 'POST', url: '/add_cafe/', data: { csrfmiddlewaretoken: document.querySelector('input[name="csrfmiddlewaretoken"]').value, 'venuename': name, 'venuetype': type, 'venueaddress': address, 'latitude': latitude, 'longitude': longitude }, success: function(data) { console.log("Data sent"); } }); } Here is the views.py function that processes it for the database: def add_cafe(request): if request.method == "POST": new_obj = mapCafes() new_obj.cafe_name = request.POST.get('venuename') new_obj.cafe_address = request.POST.get('venueaddress') new_obj.venue_type = request.POST.get('venuetype') new_obj.cafe_long = float(request.POST.get('longitude')) new_obj.cafe_lat = float(request.POST.get('latitude')) new_obj.save() return render(request, 'testingland/addcafe.html') And here is the ajax call that retrieves the data for the marker modal box: $.ajax({ type: …