Hi, I have saved a django field using javascript before and it has worked perfectly. However, I have never done this when trying to loop through filtered data in my HTML. This causes an error at this line in my javascript:
Console:
Uncaught SyntaxError: unexpected token: identifier:
Line: let autosaveTimer;
Does anyone have any guidance about how I can remedy this? The code works perfectly when I don’t loop through data in my HTML. All code is below.
from django.db import models
from django.contrib.auth.models import AbstractUser
#from localflavor.us.models import USStateField
# Create your models here.
class User(AbstractUser):
"""User can be Employee or Customer"""
#state = USStateField()
phone_number = models.CharField(max_length=20, blank=True, null=True)
class Business(models.Model):
business = models.CharField(max_length=50)
class BusinessOwner(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True )
business = models.ForeignKey(Business, on_delete=models.CASCADE, null=True)
class Customer(models.Model):
""" Customer-specific information """
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True )
business = models.ForeignKey(Business, on_delete=models.CASCADE, null=True)
class Note(models.Model):
JOB_STATUS =(
("Q", "Quote"),
("R", "Review"),
("W", "Working"),
("C", "Complete"),
)
#user_emp = models.ForeignKey('Employee', on_delete=models.CASCADE, null=True, related_name='notes')
user_cust = models.ForeignKey('Customer', on_delete=models.CASCADE, null=True, related_name='notes')
cust_notes = models.CharField(max_length=1000, blank=True, null=True)
job_status = models.CharField(max_length=10, blank=True,null=True, choices = JOB_STATUS ) #add.update(review = 'R') to change field.
job_name = models.CharField(max_length=500, blank=True, null=True)
note_by = models.CharField(max_length=500, blank=True, null=True)
note_created_at = models.DateTimeField(auto_now_add=True)
note_updated_at = models.DateTimeField(auto_now=True, null=True)
class Employee(models.Model):
""" Employee-specific information """
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
business = models.ForeignKey(Business, on_delete=models.CASCADE, null=True, blank=True)
def customerDashboard(request, id):
"""View for user to see Customer Page"""
user = User.objects.get(id=id)
note = Note.objects.filter(user_cust=id) #for loop use filter.
context = {
'user': user,
'note': note,
}
return render(request,'employees/customer_dashboard.html', context)
<div class="h-25 d-inline-block d-flex justify-content-center align-items-center">
<div class="col">
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Job Name</th>
<th scope="col">Job Notes</th>
<th scope="col">Note By</th>
<th scope="col">Note Created</th>
<th scope="col">Note Updated</th>
<th scope="col">Job Status</th>
<th scope="col">Delete Note</th>
</tr>
</thead>
{% for x in note %}
<tbody>
<tr>
<th>
{{ x.job_name }} <p></p>
</th>
<td>
<form action=" method='post' ">
{%csrf_token%}
<textarea name="cust_notes" maxlength="1000" required="" id="cust_notes"
class="form-control" value="">{{ x.cust_notes }}
</textarea>
</form>
</td>
<td>
{{ x.note_by }} <p></p>
</td>
<td>
{{ x.note_created_at }} <p></p>
</td>
<td>
{{ x.note_updated_at }} <p></p>
</td>
<td>
{{x.job_status }} <p></p>
</td>
<td>
<a href="{% url "del-customer-note" user.customer.id %}">
<button class="btn btn-sm btn-primary">
{% bs_icon 'trash3-fill' size='1.5em' %}
</button>
</a>
</td>
</tr>
</tbody>
{%endfor%}
</table>
</div>
</div>
<script>
const customerNoteInput = document.querySelector('#cust_notes');
const notesEndpointURL = '/customers/notes/'
const customerId = {{note.user_cust_id}}
let autosaveTimer;
customerNoteInput.addEventListener('input', () => {
clearTimeout(autosaveTimer);
autosaveTimer = setTimeout(autosaveNote, 2000);
})
function autosaveNote() {
let noteText = customerNoteInput.value
let data = {
'user_cust_id': customerId,
'cust_notes': noteText,
}
// Fetch API
fetch(notesEndpointURL, {
method: 'post',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': '{{csrf_token}}',
},
body: JSON.stringify(data)
})
.then(response => {
if (response.status == 200) {
console.log('Success! Response was 200!')
}
return response.json()
})
.then(data => {
console.log(data)
})
.catch(error => {
console.error('Error: ', error)
})
console.log('Note autosaved:', customerNoteInput.value);
}
</script>
def customer_note_endpoint(request):
if request.method == 'POST':
# When receiving json from Fetch API or "ajax", you get the data from request.body
# To convert that json data into Python, import json and wrap request.body with json.loads
data = json.loads(request.body)
user_cust_id = int(data['user_cust_id'])
customer_note_text = data['cust_notes']
print('Note text:', customer_note_text)
# Get user
note = Note.objects.get(user_cust_id=user_cust_id)
# Update their note text
print('Old note text:', note.cust_notes)
note.cust_notes = customer_note_text
note.save()
print('New note text:', note.cust_notes)
# Save to the database
note.save()
return JsonResponse({'message': 'Post successful!'})
return JsonResponse({'message': 'Invalid method'}, status=405)