我有一个由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)
模型合作者是一个呈现用户名的选择字段。
我希望此字段改为呈现 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”
表单.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”进行一些更改
查看.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 页面上看到的。
{{ widget.label }}
在这种情况下显示用户名,所以我修改了这部分。
我希望这就是您正在寻找的内容,如果我的理解有误,请随时询问我。
关于python - 使用 PK 而不是用户名的选择字段的 ModelForm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55013137/