Django는 사용자 정의 양식 매개 변수를 ModelforMSet에 전달합니다
-
06-07-2019 - |
문제
내 문제는 비슷합니다 DJANGO는 CORMENT FORMARETERS를 FormSet으로 전달합니다
이 수업이 있습니다
class Game(models.Model):
home_team = models.ForeignKey(Team, related_name='home_team')
away_team = models.ForeignKey(Team, related_name='away_team')
round = models.ForeignKey(Round)
TEAM_CHOICES = ((1, '1'), (2, 'X'), (3, '2'),)
class Odds(models.Model):
game = models.ForeignKey(Game, unique=False)
team = models.IntegerField(choices = TEAM_CHOICES)
odds = models.FloatField()
class Meta:
verbose_name_plural = "Odds"
unique_together = (
("game", "team"),
)
class Vote(models.Model):
user = models.ForeignKey(User, unique=False)
game = models.ForeignKey(Game)
score = models.ForeignKey(Odds)
class Meta:
unique_together = (
("game", "user"),)
그리고 나는 내 자신의 modelformset_factory를 정의했습니다.
def mymodelformset_factory(ins):
class VoteForm(forms.ModelForm):
score = forms.ModelChoiceField(queryset=Odds.objects.filter(game=ins), widget=forms.RadioSelect(), empty_label=None)
def __init__(self, *args, **kwargs):
super(VoteForm, self).__init__(*args, **kwargs)
class Meta:
model = Vote
exclude = ['user']
return VoteForm
그리고 나는 이것을 사용합니다.
VoteFormSet = modelformset_factory(Vote, form=mymodelformset_factory(v), extra=0)
formset = VoteFormSet(request.POST, queryset=Vote.objects.filter(game__round=round, user=user))
이것은 양식을 표시합니다.
지정된 라운드에서 게임 상자의 드롭 다운 상자 (들)는 지정된 라운드에 3 개의 라디오 버튼을 표시해야하지만 mymodelformset_factory에 매개 변수로 무엇을 전달 해야하는지 모르겠다 .. if v = game.objects.get (pk. = 1) 모든 게임에 대해 pk = 1으로 게임을 표시합니다. 내가 필요한 것은 v = game.objects.get (pk = ""에 관한 확률에 연결된 게임 ")입니다. 내 드리프트를 잡으면 ..
해결책
맞춤형 공장 기능을 변경하고 싶다고 생각합니다. 양식이 아닌 Formset 클래스를 반환해야합니다. 이건 어때:
def make_vote_formset(game_obj, extra=0):
class _VoteForm(forms.ModelForm):
score = forms.ModelChoiceField(
queryset=Odds.objects.filter(game=game_obj),
widget=forms.RadioSelect(),
empty_label=None)
class Meta:
model = Vote
exclude = ['user',]
return modelformset_factory(Vote, form=_VoteForm, extra=extra)
그런 다음 뷰 코드에서 :
current_game = Game.objects.filter(id=current_game_id)
VoteFormSet = make_vote_formset(current_game)
formset = VoteFormSet(
request.POST,
queryset=Vote.objects.filter(game__round=round, user=user))
다른 팁
또 다른 해결책은 BasemodelforMSet을 서브 클래스하고 재정의하는 것입니다 _construct_forms 방법. 기본적으로 baseformset _construct_form 메소드는 하나의 인수만으로 _construct_forms에서 호출됩니다. i :
# django/forms/formsets.py
def _construct_forms(self):
# instantiate all the forms and put them in self.forms
self.forms = []
for i in xrange(self.total_form_count()):
self.forms.append(self._construct_form(i))
그러나 키워드 Args는 여러 가지가있을 수 있습니다.
# django/forms/formsets.py
def _construct_form(self, i, **kwargs):
그래서 여기에 추가 매개 변수를 수신하는 내보기 방법과 형식이 있습니다. 이니 _construct_form에서 :
# view
def edit(request, id):
class ActionsFormSet(BaseModelFormSet):
department = request.user.userdata.department.pk
def _construct_forms(self):
self.forms = []
for i in range(self.total_form_count()):
self.forms.append(self._construct_form(i, dep=self.department))
actions_formset = modelformset_factory(Action, form=ActionForm, extra=0, can_delete=True, formset=ActionsFormSet)
...
# form
class ActionForm(forms.ModelForm):
def __init__(self, dep=0, *args, **kwargs):
super(ActionForm, self).__init__(*args, **kwargs)
self.fields['user'].choices = [(u.pk, u.first_name) for u in User.objects.filter(userdata__department=dep)]
class Meta:
model = Action
exclude = ('req',)
제휴하지 않습니다 StackOverflow