如何根据性别设定宿舍选择?
全局变量
BOYS_HOSTEL_CHOICES = (...)
GIRLS_HOSTEL_CHOICES = (...)
class Student(models.Model):
MALE = 'M'
FEMALE = 'F'
#...
GENDER_CHOICES = (
(MALE, 'Male'),
(FEMALE, 'Female')
)
gender = models.CharField(
max_length = 10,
choices = GENDER_CHOICES,
verbose_name="gender",
)
hostel = models.CharField(
max_length=40,
choices = BOYS_HOSTEL_CHOICES if gender == 'M' # <---
else GIRLS_HOSTEL_CHOICES,
default = 'some hostel'
)发布于 2021-09-08 18:35:09
您不能在模型级别执行此操作,除非您希望将其实现为database constraint。但听起来您只是想限制表单上的选择。
在模型中允许两种选择:
hostel = models.CharField(
max_length=40,
# Combine choices
choices=BOYS_HOSTEL_CHOICES + GIRLS_HOSTEL_CHOICES,
default='some hostel'
)您还可以使用Django's model validation在Python中检查保存时的约束。
如果需要限制呈现的表单中的选择,表单需要知道gender字段的值,然后才能限制hostel字段的选择。
from django import forms
class StudentForm(forms.ModelForm):
# ...
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['hostel'].choices = BOYS_HOSTEL_CHOICES发布于 2021-09-08 19:12:54
如果你不知道旅舍选择的超集,那么你不应该在模型中设置选择属性,因为django模型验证了字段选择。
Make hostel字段作为不带选项属性的CharField
hostel = models.CharField(max_length=40)在这种情况下,您可以创建一个表单或modelform,您可以在其中设置动态选择。
from django import forms
class StudentForm(forms.ModelForm):
default_choices = [your default choices if you want]
hostel = forms.CharField(max_length=40, choices = default_choices)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['hostel'].choices = self.get_dynamic_choice()
def get_dynamic_choice(self):
''' you can set choices BOYS_HOSTEL_CHOICES or GIRLS_HOSTEL_CHOICES'''
return choices但是,如果您希望在选择gender字段时使用dependent下拉方式,则可以通过javascript或Ajax call来实现此功能
编辑:
如果你不想写javascript或ajax代码,那么你可以使用django-autocomplete-light包。
您可以在hostel字段中转发所选值gender,并在视图中进行访问,您可以在其中为hostel表单字段设置动态选择。您还可以在hostel字段值中进行搜索。这个包也支持queryset。
在forms.py中,
from django import forms
class StudentForm(forms.ModelForm):
default_choices = [your default choices if you want]
hostel = forms.ChoiceField(max_length=40,
choices = default_choices,
widget=autocomplete.ListSelect2(url='hostel_autocomplete', forward=['gender'],))在urls.py中,
urlpatterns = [
path('hostel_autocomplete/', HostelAutocompleteView.as_view(), name='hostel_autocomplete'),
]在views.py中,
from dal import autocomplete
class HostelAutocompleteView(autocomplete.Select2ListView):
def get_list(self):
if not self.request.user.is_authenticated:
return []
# you get select gender value
gender = self.forwarded.get('gender', None)
if gender == 'M':
# your BOYS_HOSTEL_CHOICE_LIST
choice_list = ['A hostel','B hostel']
elif gender == 'F':
# your GIRL_HOSTEL_CHOICE_LIST
choice_list = ['C hostel', 'D hostel']
else:
choice_list = []
return choice_listhttps://stackoverflow.com/questions/69069366
复制相似问题