我尝试使用现有模型生成表单。它主要是有效的,但我通过我的网址获取的值显示我的提供商 id ,表单显示提供商名称。如何在表单中继续显示名称,但将提供商 slug 而不是 id 作为该表单中的值?
模型
class Provider(models.Model):
name = models.CharField(unique=True, max_length=256)
slug = AutoSlugField(populate_from='name', always_update='True')
...
形式
class FiltersAndSortingForm(forms.Form):
provider = forms.ModelMultipleChoiceField(queryset=Provider.objects.all().order_by('name'), label='Provider', required=False,)
视图
def resources(request):
if request.GET:
provider = request.GET.getlist('provider', '')
qset_provider = Q()
for x in provider:
qset_provider |= Q(provider=x)
resources = Resource.objects.filter(inactive=0).filter(qset_provider)
form = FiltersAndSortingForm()
else:
form = FiltersAndSortingForm()
resources = Resource.objects.filter(inactive=0)
context = {
'resources': resources,
'form': form,
}
return render(request, 'mainapp/resources.html', context)
resources.html
{% for field in form %}
{{ field.label }}
{{ field }}
{% endfor %}