使用 PK 而不是用户名的选择字段的 ModelForm

ModelForm for choicefield with PK instead of usernames

我有一个由 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)

模型 collaborateurs 是一个呈现用户名的选择字段。

我希望此字段呈现 PK,所以我尝试创建自己的表单但无法弄清楚。

forms.py

 from django import forms 
 from .models import Hotel

class HotelForm(forms.Form):
   collaborateurs = forms.ModelChoiceField(queryset=collaborateurs.objects.all())

谢谢

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

在某些 "templates" 文件夹中创建 "widgets" 文件夹和 "pk-select.html"。

widgets/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/django/forms/templates/django/forms/widgets/select_option.html

{{ widget.label }}在本例中显示用户名,所以我修改了这部分。

我希望这就是你要找的,如果我的理解有误,请随时问我。