我正在尝试使用 AJAX 渲染 Django 表单:
这是我的文件:
模型.py
class models_projects(models.Model):
id = models.CharField(primary_key=True, max_length=50)
reference = models.CharField(max_length=50)
model = models.CharField(max_length=50)
class Meta:
db_table = 'table_projects'
表格.py
class forms_projects(forms.ModelForm):
id = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={"placeholder":"id", "class":"form-control"}), label="id")
reference = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={"placeholder":"reference", "class":"form-control"}), label="reference")
model = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={"placeholder":"model", "class":"form-control"}), label="model")
class Meta:
model = models_projects
exclude = ("user",)
查看.py
def update_project_mobile(request):
project_id = request.POST.get('project_num')
if request.user.is_authenticated:
record = models_projects.objects.get(id = project_id)
projects_form = forms_projects(request.POST or None, instance=record)
if projects_form.is_valid():
projects_form.save()
return render(request, 'projects_mobile.html', {'projects_form':projects_form})
else:
messages.success(request, "You Must Be Logged In...")
return redirect('home')
模板.html
<select name="project_num" id="project_num">
<option value="2"> "2" </option>
</select>
<div id="projects_container" ></div> <!-- This is where projects_mobile.html is rendered -->
<script>
function load_projects (){
$.ajaxSetup(
{
data: {project_num: $('#project_num').val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
});
$.ajax({
type: "POST",
url: "../update_project_mobile/",
//dataType: 'json',
success: function (data) {
$("#projects_container").html(data);
}
});
}
</script>
url.py
...
path('update_project_mobile/', views.update_project_mobile,name='update_project_mobile'),
...
projects_mobile.html
<body>
{{ projects_form }}
</body>
表单渲染良好,
projects_mobile.html
的内容在<div id="projects_container" ></div>
内显示良好,但表单字段内没有数据,仅显示占位符。
数据库非常简单,有一个 ID 为“2”的条目,因此它不是来自数据库搜索
我错过了什么?
刚刚在 AJAX 部分将
type: "POST"
更改为 type: "GET"
,现在可以使用了