Как автоматически заполнить форму из базы данных в Django? - PullRequest
0 голосов
/ 23 апреля 2019

У меня есть две формы, и я хочу автоматически заполнить вторую форму в зависимости от одного поля первой формы. Как я могу это сделать ? Нужно ли переопределять некоторые методы?

Форма турнира

class MyModelChoiceField(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return obj.name

class TournamentCreationForm(forms.ModelForm):

    name                = forms.CharField(label='Name', widget=forms.TextInput(attrs={
                                    'class':'form-control',
                                    'placeholder': 'Enter the name of the tournament'}))
    dateStart           = forms.DateField(label='Beginning', widget=forms.DateInput(attrs={
                                    'class':'form-control',
                                    'placeholder': 'Enter the date of the beginning'}))
    dateEnd             = forms.DateField(label='Ending', widget=forms.DateInput(attrs={
                                    'class':'form-control',
                                    'placeholder': 'Enter the date of the end'}))
    nbMaxTeam           = forms.IntegerField(label='Number max of team', widget=forms.NumberInput(attrs={
                                    'class':'form-control',
                                    'placeholder':'Max 24'}))
    nameGymnasium       = forms.CharField(label='Name of the gymnasium', widget=forms.TextInput(attrs={
                                    'class':'form-control',
                                    'placeholder': 'Enter the name of the gymnasium'}))
    addressGymnasium    = forms.CharField(label='Address of the gymnasium', widget=forms.TextInput(attrs={
                                    'class':'form-control',
                                    'placeholder': 'Enter the address of the gymnasium'}))
    sport               = MyModelChoiceField(queryset=Sport.objects.all(), widget=forms.Select(attrs={
                                    'class':'form-control'}))

    class Meta:
        model   = Tournament
        fields  = [
            'name',
            'dateStart',
            'dateEnd',
            'nbMaxTeam',
            'nameGymnasium',
            'addressGymnasium',
            'sport'
        ]

Спортивная форма

class SportEditForm(forms.ModelForm):
    timeMatch           = forms.DecimalField(label='Time for one match', widget=forms.NumberInput(attrs={
                                    'class':'form-control',
                                    'placeholder':'Enter the the time for one match',
                                    'step': 0.1}))
    nbpointpervictory   = forms.IntegerField(label='Points per Victory', widget=forms.NumberInput(attrs={
                                    'class':'form-control',
                                    'placeholder':'Enter the points for a victory'}))
    nbpointperdefeat    = forms.IntegerField(label='Points per Defeat', widget=forms.NumberInput(attrs={
                                    'class':'form-control',
                                    'placeholder':'Enter the points for a defeat'}))
    nbpointperdraw      = forms.IntegerField(label='Points per Draw', widget=forms.NumberInput(attrs={
                                    'class':'form-control',
                                    'placeholder':'Enter the points for a draw'}))
    nbset               = forms.IntegerField(label='Numebr of sets', widget=forms.NumberInput(attrs={
                                    'class':'form-control',
                                    'placeholder':'Enter the number of sets'}))
    nbpointperset       = forms.IntegerField(label='Points per set', widget=forms.NumberInput(attrs={
                                    'class':'form-control',
                                    'placeholder':'Enter the number of points for one set'}))
    class Meta:
        model   = Sport
        fields  = [
            'timeMatch',
            'nbpointpervictory',
            'nbpointperdefeat',
            'nbpointperdraw',
            'nbset',
            'nbpointperset'
        ]

У меня также есть две формы. В своей турнирной форме я должен выбрать вид спорта турнира. На данный момент это нормально, но я бы хотел обновить свои поля формы sport_form в зависимости от выбранного вида спорта.

Вот мой взгляд:

def tournament_creation_view(request, *args, **kwargs): #*args, **kwargs
    form_tournament = TournamentCreationForm(request.POST or None)
    form_sport      = SportEditForm(request.POST or None)
    if form_tournament.is_valid() and form_sport.is_valid():
        instance = form_tournament.save(commit=False)
        instance.user = request.user
        instance.save()

    context = {
        'form_tournament': form_tournament,
        'form_sport': form_sport
    }
    return render(request, "tournament_creation.html", context)

Я думаю, мне нужно переопределить метод, но какой метод и где? В моей турнирной форме у меня есть это поле с именем "спорт", в нем перечислены все виды спорта, которые я уже сохранил в БД. Когда я выбираю один, я хотел бы автоматически заполнить поля спортивной формы.

РЕДАКТИРОВАТЬ:

«спорт» - это поле турнирной формы. Это ModelChoiceField, в котором перечислены все виды спорта, которые уже сохранены в БД. Я хотел бы сделать это: когда я выбираю один вид спорта, моя другая форма (спортивная форма) автоматически заполняется данными, которые уже существуют.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...