【问题标题】:How do I pass the value of two separate inputs into the content field of my form in Django?如何将两个单独输入的值传递到 Django 表单的内容字段中?
【发布时间】: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


    【解决方案1】:

    这对你有帮助,你应该先看看 django Class-Based Views,更具体地说是 FormView,django 已经有能够处理表单上发布的数据的通用视图。您的代码如下所示:

    # forms.py
    # imports ...
    class WorkoutModelForm(forms.ModelForm):
        class Meta:
            model = Workout
            fields = ['content']
    
    
    # urls.py
    from django.urls import path
    from . import views
    app_name = 'myapp'
    
    urlpatterns = [
        path("test-form/", views.TesteFormView.as_view(), name='test-form'),
    ]
    
    
    # views.py
    from django.views.generic import FormView
    from myapp import forms
    from django.contrib import messages
    
    class TesteFormView(FormView):
        template_name = "myapp/index.html"
        success_url = reverse_lazy('myapp:test-form')
        form_class = forms.WorkoutModelForm
    
        def get(self, request, *args, **kwargs):
            return super(TesteFormView, self).get(request, *args, **kwargs)
    
        def form_valid(self, form):
            print(f"POST DATA =  {self.request.POST}") # debug
            content = form.cleaned_data.get('content')
            # fieldx= form.cleaned_data.get('fieldx')
            # do something whit this fields like :
            Workout.object.create(content=content)
            messages.success(self.request,"New workout object created")
    
            return super(TesteFormView, self).form_valid(form=self.get_form())
    
        def form_invalid(self, form):
            print(f"POST DATA =  {self.request.POST}") # debug
            for key in form.errors:
                messages.error(self.request, form.errors[key])
            return super(TesteFormView, self).form_invalid(form=self.get_form())
    
    

    你的模板看起来像:

    # myapp/index.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>TestForm</title>
    </head>
    <body>
    <form method="post">
        {% csrf_token %}
        {{ form }}
        <button type="submit">submit</button>
    </form>
    </body>
    </html>
    

    【讨论】:

    • 非常感谢您的回复。我以前不知道通用类 FormView 。您能否在评论部分解释一下您所说的 fieldx 是什么意思?这会是我包含递增/递减按钮和脚本标签的地方吗?为听起来很愚蠢而道歉
    • @sgt_pepper85 fieldx 是一个假设字段,这意味着我们可以根据表单中的字段数量获取更多数据,在这种情况下它只是内容字段
    • 关于按钮,我不太明白你的应用程序的目的是什么,但是如果重量和代表是表单字段,它们应该在 forms.py 中
    • 嗯,好的。现在有道理了。谢谢你,这有很大帮助
    猜你喜欢
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多