Django Forms没有提交单选按钮值,也没有在终端中显示任何输出

dluptydi  于 2022-11-26  发布在  Go
关注(0)|答案(1)|浏览(107)

这是HTML代码。

<form action = "." method = "post">
    <div class="form_data">

        {% csrf_token %}
         <br><br>

        {{form.myfield}}
<br><br>
     <input type="submit" value="Submit" class="btn btn-success" />
        </div>
</form>

这是forms.py代码

class TestForm(forms.ModelForm):
    class Meta:
        model = TestModel
        fields = "__all__"
        widgets = {'myfield': forms.RadioSelect()}

这是models.py代码

class TestModel(models.Model):
    git_Id = models.CharField(max_length=200)
    git_Response = models.CharField(max_length=200)
    is_approved = models.IntegerField()
    MY_CHOICES = (
        ('opt0', 'Approved'),
        ('opt1', 'Not Approved'),
    )
    myfield = models.CharField(max_length=10, choices=MY_CHOICES, default="N/A")

views.py 代码

def test(request):
    if request.method == "POST":
        form = TestForm(request.POST)
        if form.is_valid():
            print("Form is Valid")
            selected = form.cleaned_data['myfield']
            print(selected)

            if selected == 'opt0':
                from config import request_id as r
                rq = r["request_id"]
                print(rq)
                s = sql()
                query = f"""update request_form_mymodel
                                       set is_approved=1
                                       where request_id = '{rq}' """
                print(query)
                s.update_query(query)
            else:
                pass

    else:
        form = TestForm()
    return render(request, 'test.html', {'form': form})

我没有得到任何输出,如果我尝试提交后,选择单选按钮,然后它不工作,不打印终端中的任何变量值,以及表单没有提交。我想要什么-我想得到的表单被提交,如果单选按钮被选中opt 0,然后调用s.update()。

v8wbuo2f

v8wbuo2f1#

表单不会转到test视图,因为您在action属性中指定了.,请删除action属性,因为Django总是使用当前页面路径,所以它会自动转到test视图,因此:

<form method="POST">
    <div class="form_data">

        {% csrf_token %}
         <br><br>

        {{form.myfield}}
<br><br>
     <input type="submit" value="Submit" class="btn btn-success" />
        </div>
</form>

相关问题