Обновление раздела "Заметки" в django с помощью ajax
Я изучил документацию, посмотрел видео и задал еще один вопрос на stack overflow, но просто не могу понять, как использовать ajax в моем проекте django. По сути, у меня есть список менеджеров территорий, которые возвращаются из цикла for (вот models.py, views.py и detail.html, показывающие это):
models.py
class TM(models.Model): #Change this to territory manager and delete database and recreate
Name = models.CharField(max_length = 200,null=True)
Cell = models.CharField(max_length= 200, null=True)
EmailAddress = models.EmailField(null=True)
Notes = models.CharField(max_length=500, null=True)
Distributor = models.CharField(max_length=200,null=True)
State = models.CharField(max_length=200,null=True)
Brand = models.CharField(max_length=200,null=True)
def __str__(self):
try:
if self.Distributor is not NullBooleanField:
return self.Name + ' - ' + self.Distributor + ' - ' + self.State
except TypeError:
return self.Name
views.py
def detail(request):
try:
if request.method == 'POST':
state = request.POST['state']
brand = request.POST['brand']
territory_manager = TM.objects.filter(State__icontains=state).filter(Brand__icontains=brand)
return render(request,'homepage/detail.html', {'state': state, 'territory_manager':territory_manager})
else:
state = request.POST['state']
brand = request.POST['brand']
return render(request,'homepage/detail.html', f"No Results for {state} or {brand}")
except TM.DoesNotExist:
raise Http404("Info Does Not Exist")
table in detail.html
<table class= "content-table">
<thead>
<tr>
<th>Name</th>
<th>Distributor</th>
<th>State</th>
<th>Brand</th>
<th>Cell</th>
<th>Email</th>
<th>Notes</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
{% for tm in territory_manager %}
<td style="white-space:nowrap;">{{ tm.Name }}</td>
<td style="white-space:nowrap;">{{ tm.Distributor }}</td>
<td style="white-space:nowrap;">{{ tm.State }}</td>
<td style="white-space:nowrap;">{{ tm.Brand }}</td>
<td style="white-space:nowrap;">{{ tm.Cell }}</td>
<td style="white-space:nowrap;">{{ tm.Email }}</td>
<td id='notes' contenteditable="True">{{ tm.Notes }}</td>
<td><button id="note_submit" type="button">Update</button></td>
</tr>
{% endfor %}
</tr>
</tbody>
</table>
Загружается страница с именами менеджеров территории, электронной почтой, телефоном и разделом заметок. Я сделал раздел заметок редактируемым и хочу использовать ajax, чтобы когда кто-то редактирует раздел заметок и нажимает кнопку обновления, обновленная заметка сохранялась в базе данных и отображалась пользователю. Я пытался собрать воедино несколько различных ответов SO, но безрезультатно. Вот что у меня есть:
script placed at the bottom of my detail.html
<script>
$(document).ready(function () {
$(document).on("click",'.notes_submit', function() {
$.ajax({
type: "POST",
data: {action: 'note_update', note: document.getElementById("notes").addEventListener('click', Update)},
success: function(data){
$("#notes").html("<strong>"+data.note+"</strong>");
}
});
});
});
</script>
functions in views.py
def post(self,request, *args, **kwargs):
if self.request.is_ajax():
return self.ajax(request)
def ajax(self, request):
response_dict= {
'success': True,
}
action = request.POST.get('action','')
if action == 'note_submit':
note_id = request.POST.get('id','')
if hasattr(self, action):
response_dict = getattr(self, action)(request)
note = TM.objects.get(Note='note_id')
response_dict = {
'note_name':note.name
}
return render(simplejson.dumps(response_dict),
mimetype='application/json')
Любое направление приветствуется. Спасибо!
Вы опустили параметр url в вызове ajax. В этом случае запрос отправляется на текущую страницу. В вашем случае это будет детальное представление, которое не обрабатывает ajax-запрос.
И замените EventListener в вашем варианте данных на содержимое заметок.
$.ajax({
url: // PUT THE URL TO YOUR AJAX HANDLING VIEW HERE //,
type: "POST",
data: {action: 'note_update', note: document.getElementById("notes").textContent;},
success: function(data){
$("#notes").html("<strong>"+data.note+"</strong>");
}
});