【发布时间】:2021-01-15 02:47:00
【问题描述】:
在我的模板中,我有一个包含两个输入元素的表单,其值可以使用 javascript 进行调整。我希望能够获取这些值,并在提交表单时,在下面的 for 循环中将它们显示在一个句子中。
index.html:
<form action="{% url 'workouts:workout' %}" method="post">
{% csrf_token %}
<div class="weight">
<h4>WEIGHT (kgs):</h4>
<button type="button" class="weight-dec">-</button>
<input type="text" value="0" class="weight-qty-box" readonly="" name="one">
<button type="button" class="weight-inc">+</button>
</div>
<div class="reps">
<h4>REPS:</h4>
<button type="button" class="rep-dec">-</button>
<input type="text" value="0" class="rep-qty-box" readonly="" name="two">
<button type="button" class="rep-inc">+</button>
</div>
<input type="submit" value="Save" name="submit_workout">
<input type="reset" value="Clear">
</form>
{% if exercise.workout_set.all %}
{% for w in exercise.workout_set.all %}
{{ w.content }}
{% endfor %}
{% endif %}
我在上面的表单中给出了一个映射到视图的 url 的动作属性,每个输入都有一个名称,以便在视图中访问它们的值。我也在forms.py中写了这个表格:
class WorkoutModelForm(forms.ModelForm):
class Meta:
model = Workout
fields = ['content']
对于上下文,这是我的模型:
class Workout(models.Model):
content = models.CharField(max_length=50)
created = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now=True)
exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, default=None)
class Meta:
ordering = ('created',)
我的问题是我不知道如何将我的模型表单实际合并到我的模板中,或者如何编写一个视图来做我想做的事情。我对此仍然很陌生,并且一直在寻找答案一段时间,但到目前为止还没有找到答案。请帮忙。
【问题讨论】:
标签: django forms input modelform