我是 Django 新手,目前面临将 html 标签数据发布到数据库的问题。
我有一个“PICK CASE”按钮,单击该按钮应从 HTML 标签发送 user_id (隐藏的 html 标签显示:无)和 case_id 并将其发送到“pick_view”视图,并从那里将数据存储在 MySQL 数据库中。
tables.html
<div class="containers pt-5 pb-3 px-4 py-4">
<input type='hidden' name='csrfmiddlewaretoken' value='{{ csrf_token }}' />
<div class="d-none">
<p>User ID: </p><p class="user-id">{{id}}</p>
</div>
<h3>Case Number:</h3><h2 id="number"></h2>
<h4>Description:</h4>
<p class="mb-5" id="display"></p>
<div class="button d-inline-block" style="max-width: 50%;">
<button type="submit" id="pick" class=" pick-button btn btn-outline-primary border-radius-lg p-3">Pick Case</button>
</div>
<div class="d-inline-block float-lg-end" style="max-width: 50%;">
<button class="btn btn-outline-danger border-radius-lg p-3">Close</button>
</div>
</div>
<script>
$("#pick").click(function(){
var user = $('.user-id').text();
var ca = $('#number').text();
ca = $.trim(ca);
$.ajax({
type:"POST",
url:"{% url 'dashboard:pick_case' %}",
data:{
user_id:user,
case_id:ca,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success:function(data){
alert(data);
}
});
});
</script>
Views.py
def pick_view(request):
if request.method == 'POST':
case_id = request.POST.get('case_id')
print(case_id)
status = 2
picked = Transaction()
picked.Case_ID = case_id
picked.Status = status
picked.save()
return HttpResponse("Case Picked Successfuly!")
else:
return HttpResponse("POST ERROR")
urls.py
urlpatterns = [
path('dashboard', views.dashboard_view, name='dashboard_view'),
path('tables', views.case_view, name='case_view'),
path('tables', views.pick_view, name='pick_case'),
]
模型.py
class Transaction(models.Model): ### Case Progress Table
Case_ID = models.ForeignKey(CaseTable, on_delete=models.CASCADE)
Status = models.ForeignKey(Status, on_delete=models.CASCADE)
Date_Time = models.DateTimeField(default=timezone.now)
运行以下代码后
success:function(data){
alert(data);
}
我得到以下输出: 显然,我无法在ajax中传递“user”和“ca”的值。
请帮忙!!
显然你可以使用 JsonResponse 代替 HTTPResponse,它会更加干净,易于读取和操作返回的数据。
def pick_view(request):
context={}
if request.method == 'POST':
try:
case_id = request.POST.get('case_id')
print(case_id)
status = 2
picked = Transaction()
picked.Case_ID = case_id
picked.Status = status
picked.save()
context.update({'response':'Case Picked Successfuly!'})
except Exception as e:
context.update({'response':'POST ERROR : ' + str(e)})
return JsonResponse(data=context)
然后在你的ajax中你可以使用
alert(data.response);
访问返回的数据
此外,在处理错误时请始终使用 try except 块,这样它就不会在运行时破坏您的程序。