동적 선택 필드 만들기
장고에서 동적 선택 필드를 만드는 방법을 이해하는 데 어려움을 겪고 있습니다.다음과 같은 모델을 설정했습니다.
class rider(models.Model):
user = models.ForeignKey(User)
waypoint = models.ManyToManyField(Waypoint)
class Waypoint(models.Model):
lat = models.FloatField()
lng = models.FloatField()
제가 하려는 것은 해당 라이더(로그인한 사람)와 연결된 경유지 값인 선택 필드를 만드는 것입니다.
현재 저는 다음과 같이 제 양식으로 그것을 재정의하고 있습니다.
class waypointForm(forms.Form):
def __init__(self, *args, **kwargs):
super(joinTripForm, self).__init__(*args, **kwargs)
self.fields['waypoints'] = forms.ChoiceField(choices=[ (o.id, str(o)) for o in Waypoint.objects.all()])
하지만 모든 중간 지점을 나열하는 것뿐입니다. 특정 탑승자와 관련이 없습니다.아이디어 있어요?감사해요.
사용자를 양식으로 전달하여 경유지를 필터링할 수 있습니다.
class waypointForm(forms.Form):
def __init__(self, user, *args, **kwargs):
super(waypointForm, self).__init__(*args, **kwargs)
self.fields['waypoints'] = forms.ChoiceField(
choices=[(o.id, str(o)) for o in Waypoint.objects.filter(user=user)]
)
양식을 시작하는 동안 보기에서 사용자 전달
form = waypointForm(user)
모형의 경우.
class waypointForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(waypointForm, self).__init__(*args, **kwargs)
self.fields['waypoints'] = forms.ModelChoiceField(
queryset=Waypoint.objects.filter(user=user)
)
class Meta:
model = Waypoint
문제를 해결할 수 있는 내장 솔루션이 있습니다.모델 선택 필드.
일반적으로, 항상 사용해 볼 가치가 있습니다.ModelForm
데이터베이스 개체를 생성/변경해야 하는 경우.95%의 사례에서 작동하며 자체 구현을 생성하는 것보다 훨씬 깨끗합니다.
문제는 당신이 할 때입니다.
def __init__(self, user, *args, **kwargs):
super(waypointForm, self).__init__(*args, **kwargs)
self.fields['waypoints'] = forms.ChoiceField(choices=[ (o.id, str(o)) for o in Waypoint.objects.filter(user=user)])
업데이트 요청에서 이전 값이 손실됩니다!
라이더 인스턴스를 초기화하면서 폼에 전달하는 것은 어떻습니까?
class WaypointForm(forms.Form):
def __init__(self, rider, *args, **kwargs):
super(joinTripForm, self).__init__(*args, **kwargs)
qs = rider.Waypoint_set.all()
self.fields['waypoints'] = forms.ChoiceField(choices=[(o.id, str(o)) for o in qs])
# In view:
rider = request.user
form = WaypointForm(rider)
필드를 양식의 1등급 속성으로 선언하고 선택사항을 동적으로 설정할 수 있습니다.__init__
:
class WaypointForm(forms.Form):
waypoints = forms.ChoiceField(choices=[])
def __init__(self, user, *args, **kwargs):
super().__init__(*args, **kwargs)
waypoint_choices = [(o.id, str(o)) for o in Waypoint.objects.filter(user=user)]
self.fields['waypoints'].choices = waypoint_choices
이 접근 방식은 ModelChoiceField에서도 작동합니다.
모델 양식을 사용하고 있으며 자동 생성된 필드의 선택을 무시하려는 경우 이 방법이 더 좋습니다.
django admin에 동적 선택 필드가 필요한 경우;이것은 django >=2.1에 대해 작동합니다.
class CarAdminForm(forms.ModelForm):
class Meta:
model = Car
def __init__(self, *args, **kwargs):
super(CarForm, self).__init__(*args, **kwargs)
# Now you can make it dynamic.
choices = (
('audi', 'Audi'),
('tesla', 'Tesla')
)
self.fields.get('car_field').choices = choices
car_field = forms.ChoiceField(choices=[])
@admin.register(Car)
class CarAdmin(admin.ModelAdmin):
form = CarAdminForm
이게 도움이 되길 바랍니다.
정상적인 선택 필드가 있는 작업 솔루션 아래에 있습니다. 저의 문제는 각 사용자가 몇 가지 조건을 기반으로 자신만의 사용자 지정 선택 필드 옵션을 가지고 있다는 것입니다.
class SupportForm(BaseForm):
affiliated = ChoiceField(required=False, label='Fieldname', choices=[], widget=Select(attrs={'onchange': 'sysAdminCheck();'}))
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
grid_id = get_user_from_request(self.request)
for l in get_all_choices().filter(user=user_id):
admin = 'y' if l in self.core else 'n'
choice = (('%s_%s' % (l.name, admin)), ('%s' % l.name))
self.affiliated_choices.append(choice)
super(SupportForm, self).__init__(*args, **kwargs)
self.fields['affiliated'].choices = self.affiliated_choice
Breedly와 Liang이 지적한 바와 같이, Ashok의 솔루션은 양식을 게시할 때 선택된 값을 얻지 못하게 할 것입니다.
약간 다르지만 여전히 불완전한 한 가지 해결 방법은 다음과 같습니다.
class waypointForm(forms.Form):
def __init__(self, user, *args, **kwargs):
self.base_fields['waypoints'].choices = self._do_the_choicy_thing()
super(waypointForm, self).__init__(*args, **kwargs)
그러나 이는 몇 가지 동시 문제를 일으킬 수 있습니다.
언급URL : https://stackoverflow.com/questions/3419997/creating-a-dynamic-choice-field
'sourcecode' 카테고리의 다른 글
__future__import print_function에서 사용하면 Python2 스타일의 인쇄가 중단되는 이유는 무엇입니까? (0) | 2023.07.23 |
---|---|
워드프레스에 IPython 노트북 게시하기 (0) | 2023.07.23 |
Python [Errno 98] 주소가 이미 사용 중입니다. (0) | 2023.07.18 |
'http setup.py 설치'와 'http 설치'의 차이점 (0) | 2023.07.18 |
범위 간에 임의의 부동 소수점 배열 생성 (0) | 2023.07.18 |