使用 AJAX jQuery 的 Django 依赖下拉列表在模板中不起作用
Djago dependent dropdown list using AJAX jQuery not working in Template
我正在做一个依赖于 Django 的表单,它适用于我的创建视图,但不适用于更新视图。我认为问题是 jQuery cdn 库,我认为它与 bootstrap cdn 冲突。 AJax 调用不会触发。知道在 Django 中是否有更简单的方法来处理依赖表单?如果您有解决方案,我很乐意寻求您的帮助
我遵循了 Vitor Freitas 提供的示例
谢谢西奥
模型视图:
class Profession(models.Model):
name = models.CharField(max_length=30)
profession_icon = models.ImageField(_("profession icon"), upload_to='profession_icon/%Y/%m/%d/', height_field=None, width_field=None, max_length=None, blank=True, validators=[validate_image_file_extension])
def __str__(self):
return self.name
class Professioncategory(models.Model):
profession = models.ForeignKey(Profession, on_delete=models.CASCADE)
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Skills(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
active = models.BooleanField(_('Active'), default=True)
profession = models.ForeignKey(Profession, on_delete=models.SET_NULL, null=True)
professioncategory = models.ForeignKey(Professioncategory, on_delete=models.SET_NULL, null=True)
posted_on = models.DateTimeField(_('Registrerad'), auto_now_add=True)
updated_on = models.DateTimeField(_('last updated'), auto_now=True)
years_of_exp = models.CharField(_('years of experiance'), max_length=20, choices=YEARS_OF_EXP, null=True, blank=True)
def __str__(self):
return self.user.email
def get_absolute_url(self):
return reverse("users:detail", kwargs={"user_id": self.user.id})
def geticon(self):
return self.profession.profession_icon
Forms.py
class SkillsForm(forms.ModelForm):
class Meta:
model = Skills
fields = ['profession','professioncategory', 'years_of_exp','active']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['professioncategory'].queryset = Professioncategory.objects.none()
if 'profession' in self.data:
try:
profession_id = int(self.data.get('profession'))
self.fields['professioncategory'].queryset = Professioncategory.objects.filter(profession_id=profession_id).order_by('name')
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty professioncategory queryset
elif self.instance.pk:
self.fields['professioncategory'].queryset = self.instance.profession.professioncategory_set.order_by('name')
Views.py
class SkillsCreateView(SuccessMessageMixin,CreateView):
model = Skills
form_class = SkillsForm
success_message = "Skill added"
template_name = 'users/user_skill_add.html'
def form_valid(self, form):
form.instance.user = self.request.user
return super(SkillsCreateView, self).form_valid(form)
def get_success_url(self):
return reverse("users:detail", kwargs={"pk": self.request.user.pk})
user_skills_view = SkillsCreateView.as_view()
class SkillsUpdate(SuccessMessageMixin,UpdateView):
model = Skills
form_class = SkillsForm
success_message = "Skill updated"
template_name = 'users/user_skill_add.html'
def get_success_url(self):
return reverse("users:detail", kwargs={"pk": self.request.user.pk})
user_skills_update_view = SkillsUpdate.as_view()
class SkillsDelete(DeleteView):
model = Skills
template_name = 'users/user_skill_delete.html'
def get_success_url(self):
return reverse("users:detail", kwargs={"pk": self.request.user.pk})
user_skills_delete_view = SkillsDelete.as_view()
AJAX 查看
def load_professions(request):
profession_id = request.GET.get('profession')
professioncategorys = Professioncategory.objects.filter(profession_id=profession_id).order_by('name')
return render(request, 'users/professioncategory_dropdown_list_options.html', {'professioncategorys': professioncategorys})
HTML 来自 AJAX
<option value="">--------</option>
{% for professioncategory in professioncategorys %}
<option value="{{ professioncategory.pk }}">{{ professioncategory.name }}</option>
{% endfor %}
HTML表单中的JS代码
<form method="post" id="SkillsForm" data-professions-url="{% url 'users:ajax_load_professions' %}" novalidate>
{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-primary" type="submit"><i class="mdi mdi-update"></i> {% trans "Update" %} </button>
</form>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3245234342342342342344/m4=" crossorigin="anonymous"></script>
<script>
$("#id_profession").change(function () {
var url = $("#SkillsForm").attr("data-professions-url");
var professionId = $(this).val();
$.ajax({
url: url,
data: {
'profession': professionId
},
success: function (data) {
$("#id_professioncategory").html(data);
}
});
});
</script>
问题已解决,问题是表单中的 def__init__ 方法与 class
不对齐
一个
我正在做一个依赖于 Django 的表单,它适用于我的创建视图,但不适用于更新视图。我认为问题是 jQuery cdn 库,我认为它与 bootstrap cdn 冲突。 AJax 调用不会触发。知道在 Django 中是否有更简单的方法来处理依赖表单?如果您有解决方案,我很乐意寻求您的帮助
我遵循了 Vitor Freitas 提供的示例 谢谢西奥
模型视图:
class Profession(models.Model):
name = models.CharField(max_length=30)
profession_icon = models.ImageField(_("profession icon"), upload_to='profession_icon/%Y/%m/%d/', height_field=None, width_field=None, max_length=None, blank=True, validators=[validate_image_file_extension])
def __str__(self):
return self.name
class Professioncategory(models.Model):
profession = models.ForeignKey(Profession, on_delete=models.CASCADE)
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Skills(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
active = models.BooleanField(_('Active'), default=True)
profession = models.ForeignKey(Profession, on_delete=models.SET_NULL, null=True)
professioncategory = models.ForeignKey(Professioncategory, on_delete=models.SET_NULL, null=True)
posted_on = models.DateTimeField(_('Registrerad'), auto_now_add=True)
updated_on = models.DateTimeField(_('last updated'), auto_now=True)
years_of_exp = models.CharField(_('years of experiance'), max_length=20, choices=YEARS_OF_EXP, null=True, blank=True)
def __str__(self):
return self.user.email
def get_absolute_url(self):
return reverse("users:detail", kwargs={"user_id": self.user.id})
def geticon(self):
return self.profession.profession_icon
Forms.py
class SkillsForm(forms.ModelForm):
class Meta:
model = Skills
fields = ['profession','professioncategory', 'years_of_exp','active']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['professioncategory'].queryset = Professioncategory.objects.none()
if 'profession' in self.data:
try:
profession_id = int(self.data.get('profession'))
self.fields['professioncategory'].queryset = Professioncategory.objects.filter(profession_id=profession_id).order_by('name')
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty professioncategory queryset
elif self.instance.pk:
self.fields['professioncategory'].queryset = self.instance.profession.professioncategory_set.order_by('name')
Views.py
class SkillsCreateView(SuccessMessageMixin,CreateView):
model = Skills
form_class = SkillsForm
success_message = "Skill added"
template_name = 'users/user_skill_add.html'
def form_valid(self, form):
form.instance.user = self.request.user
return super(SkillsCreateView, self).form_valid(form)
def get_success_url(self):
return reverse("users:detail", kwargs={"pk": self.request.user.pk})
user_skills_view = SkillsCreateView.as_view()
class SkillsUpdate(SuccessMessageMixin,UpdateView):
model = Skills
form_class = SkillsForm
success_message = "Skill updated"
template_name = 'users/user_skill_add.html'
def get_success_url(self):
return reverse("users:detail", kwargs={"pk": self.request.user.pk})
user_skills_update_view = SkillsUpdate.as_view()
class SkillsDelete(DeleteView):
model = Skills
template_name = 'users/user_skill_delete.html'
def get_success_url(self):
return reverse("users:detail", kwargs={"pk": self.request.user.pk})
user_skills_delete_view = SkillsDelete.as_view()
AJAX 查看
def load_professions(request):
profession_id = request.GET.get('profession')
professioncategorys = Professioncategory.objects.filter(profession_id=profession_id).order_by('name')
return render(request, 'users/professioncategory_dropdown_list_options.html', {'professioncategorys': professioncategorys})
HTML 来自 AJAX
<option value="">--------</option>
{% for professioncategory in professioncategorys %}
<option value="{{ professioncategory.pk }}">{{ professioncategory.name }}</option>
{% endfor %}
HTML表单中的JS代码
<form method="post" id="SkillsForm" data-professions-url="{% url 'users:ajax_load_professions' %}" novalidate>
{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-primary" type="submit"><i class="mdi mdi-update"></i> {% trans "Update" %} </button>
</form>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3245234342342342342344/m4=" crossorigin="anonymous"></script>
<script>
$("#id_profession").change(function () {
var url = $("#SkillsForm").attr("data-professions-url");
var professionId = $(this).val();
$.ajax({
url: url,
data: {
'profession': professionId
},
success: function (data) {
$("#id_professioncategory").html(data);
}
});
});
</script>
问题已解决,问题是表单中的 def__init__ 方法与 class
不对齐一个