python - 自动将动态值转化为形式
问题描述
我有一个预订用户课程的表格。我使用lesson.lesson_instrument
andlesson.lesson_datetime_start
来显示课程的乐器和日期。我希望我的表单使用lesson.lesson_instrument
andlesson.lesson_datetime_start
的值form.booked_instrument
,form.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')
解决方案
您将使用 theModelChoiceField
而不是您当前的ChoiceField
. 顾名思义,ModelChoiceField 将特定模型与 ChoiceField 联系在一起,从而为您提供所需的准确信息。
本质上就像 Django 的文档显示:
booked_instrument = forms.ModelChoiceField(queryset=Instruments.objects.query(lesson=current_lesson...)
current_lesson
当前课程的实例在哪里显示,或者您可以按其他标准过滤,或者只渲染您在数据库中拥有的所有乐器。
看看文档: ModelChoiceField
推荐阅读
- jenkins - ORA-12154: TNS: 无法解析指定的连接标识符 - Jenkins 设置
- javascript - 使用带有年龄和性别的 FaceApi js 检测单人脸
- apache-spark - HBase 加载了来自 Spark Streaming 的实时数据。如何为每个键执行更新?
- r - 如何在 R 插入符号和 rsamples 中使用相同的交叉验证集
- javascript - 胜利图——折线
- java - 我的当前时间和我的 TimePicker 时间相差约 40.000 秒(昨天是 +46.803,今天是 -39.598 秒)
- java - Java——if语句中的++
- flutter - 颤动中的分页数据表
- r - R闪亮:取消选择时删除动态创建的checkboxGroupInput
- flutter - 相机预览打开原生相机而不是拍照