首页 > 解决方案 > 自动将动态值转化为形式

问题描述

我有一个预订用户课程的表格。我使用lesson.lesson_instrumentandlesson.lesson_datetime_start来显示课程的乐器和日期。我希望我的表单使用lesson.lesson_instrumentandlesson.lesson_datetime_start的值form.booked_instrumentform.booked_date以便将信息保存在新的单独模型实例中。我想知道如何在不输入表单文本输入的情况下从中获取值。

HTML

<div class="text-center">
    <div class="form-group">
        <div class="ins-left">
            <p>{{ lesson.lesson_instrument }} {{ form.booked_instrument }}</p>
        </div>
        <div class="date-right">
            <p>{{ lesson.lesson_datetime_start|date}} {{ form.booked_date }}</p>
        </div>
    </div>

    <br />
    <br />
    <div class="form-group">
        <label>Length</label>
        {{ form.booked_length }}
    </div>

    <br />

    <div class="form-group">
        <label>Time</label>
        {{ form.booked_time }}
    </div>

    <div class="bottom">
        <button type="submit" name="submit" class="btn blue_button">Book Now</button>
    </div>
</div>

表格.py

class BookedForm(forms.ModelForm):
    booked_instrument = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control'}))
    booked_length = forms.ChoiceField(choices=length_list, widget=forms.Select(attrs={'class' : 'form-control', 'id' : 'length', 'required' : 'True'}))
    booked_date = forms.DateField(input_formats=['%Y-%m-%d'], widget=forms.DateInput(attrs={'class': 'form-control'}))
    booked_time = forms.ChoiceField(widget=forms.Select(attrs={'class' : 'form-control', 'id' : 'time', 'required' : 'True'}))

    class Meta:
        model = Booked
        fields = ('booked_instrument', 'booked_length', 'booked_date', 'booked_time')

标签: pythondjangoforms

解决方案


您将使用 theModelChoiceField而不是您当前的ChoiceField. 顾名思义,ModelChoiceField 将特定模型与 ChoiceField 联系在一起,从而为您提供所需的准确信息。

本质上就像 Django 的文档显示:

booked_instrument = forms.ModelChoiceField(queryset=Instruments.objects.query(lesson=current_lesson...)

current_lesson当前课程的实例在哪里显示,或者您可以按其他标准过滤,或者只渲染您在数据库中拥有的所有乐器。

看看文档: ModelChoiceField


推荐阅读