使用PK而不是用户名来选择ChoiceField的Modelform



我有一个由 PostView

生成的表单
class HotelCreateView(LoginRequiredMixin, CreateView):
    model = Hotel
    fields = ['hotel', 'code', 'collaborateurs', 'planning' 'payday']
    def form_valid(self, form):
        form.instance.manager_hotel = self.request.user
        return super().form_valid(form)

模型 COMPLOTORETURS 是渲染用户名的选择。

我希望这个字段呈现PK,因此我尝试创建自己的表格,但无法弄清楚。

forms.py

 from django import forms 
 from .models import Hotel
class HotelForm(forms.Form):
   collaborateurs = forms.ModelChoiceField(queryset=collaborateurs.objects.all())

谢谢

我建议您创建一个自定义小部件。

在某些"模板"文件夹中创建一个"小部件"文件夹和" pk-select.html"。

小部件/pk-select.html

<select name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}>
  {% for group_name, group_choices, group_index in widget.optgroups %}
    {% if group_name %}
      <optgroup label="{{ group_name }}">
    {% endif %}
    {% for option in group_choices %}
      <option value="{{ option.value|stringformat:'s' }}"{% include "django/forms/widgets/attrs.html" %}>{{ option.value }}</option>
    {% endfor %}
    {% if group_name %}
      </optgroup>
    {% endif %}
  {% endfor %}
</select>

然后,像这样修改您的" form.py"

form.py

from django.forms import ModelForm
from django.forms.widgets import Select
from .models import Hotel

class PkSelect(Select):
    template_name = 'widgets/pk-select.html'

class HotelCreateForm(ModelForm):
    class Meta:
        model = Hotel
        fields = ['hotel', 'code', 'collaborateurs', 'planning', 'payday']
        widgets = {
            'collaborateurs': PkSelect(attrs={})
        }

接下来,我希望您在" view.py"上进行一些更改

view.py

class HotelCreateView(LoginRequiredMixin, CreateView):
    form_class = HotelCreateForm
    template_name = 'hotel_form.html'
    def form_valid(self, form):
        form.instance.manager_hotel = self.request.user
        return super().form_valid(form)

哪一部分进行了更改,这是" pk-select.html"

中的这一行
<option value="{{ option.value|stringformat:'s' }}"{% include "django/forms/widgets/attrs.html" %}>{{ option.value }}</option>

最初,{{ option.value }}{{ widget.label }},如您在GitHub页面上所见。

https://github.com/django/django/blob/master/master/django/django/forms/templates/django/django/forms/widgets/select_option.html

{{ widget.label }}在这种情况下显示用户名,所以我修改了此部分。

我希望这是您想要的,请随时问我是否理解是否错了。

最新更新