我正在使用 htmx 使用以下代码触发 Django ModelForm 中的字段。一切都像第一次那样工作,但在那之后,当您更改选项选择字段时,什么都没有发生,也没有任何触发器。我必须重置并返回到 url 'listing' 才能再次响应。我希望代码在我最终提交之前每次更改选项选择字段时触发结果。任何帮助都将不胜感激。
class Listing(model.Model):
option=models.ForeignKey(Option,on_delete=models.CASCADE)
package=models.ForeignKey(Package,on_delete=models.CASCADE,blank=True,null=True)
number=models.ForeignKey(Number,on_delete=models.CASCADE,blank=True,null=True)
period=models.ForeignKey(Period,on_delete=models.CASCADE,blank=True,null=True)
title=models.CharField(max_length=20)
class ListingForm(ModelForm):
class Meta:
model=Listing
fields='__all__'
class ListingCreateView(CreateView):
model=Listing
form_class=ListingForm
template_name='listing_form.html'
success_url='/forms/listing/'
def option(request):
option=request.GET.get('option')
form=ListingForm
context={'option':option,'form':form}
return render(request,'partial_option.html',context)
urlpatterns=[
path('',ListingCreateView.as_view(),name='listing-create'),
path('option/',option,name='option'),
]
listing_form.html
{% load widget_tweaks %}
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/htmx.org@1.6.1"></script>
</head>
<body>
<h1>Listing Form</h1>
<form method="post">
{% csrf_token %}
<div>
{{ form.option.label_tag }}
{% render_field form.option hx-get="/forms/option"
hx-trigger="change" hx-target="#option" hx-swap="outerHTML" %}
</div>
<div id="option"></div>
<input type="submit" value="Send">
</form>
<script>
document.body.addEventListener('htmx:configRequest', (event) =>
{
event.detail.headers['X-CSRFToken']='{{csrf_token}}';
})
</script>
</body>
</html>
partial_option.html:
{% if option %}
{% if option =='1' %}
<p>You have chosen option 1</p>
{% elif option == '2' %}
<p>You have chosen option 2</p>
{{ form.package.label_tag }}
{{ form.package }}
{% elif option == '3' %}
<p>You have chosen option 3</p>
{{ form.number.label_tag }}
{{ form.number }}
{{form.period.label_tag }}
{{ form.period }}
{% endif %}
{% else %}
<p>You have no option</p>
{% endif %}
{{ form.title.label_tag }}
{{ form.title }}