【问题标题】:how to get the selected radio button value from models in django如何从 django 中的模型中获取选定的单选按钮值
【发布时间】:2021-12-23 20:42:49
【问题描述】:

我在 django 做一个网站,但这是我第一次使用这个框架,所以我不太习惯。 我需要在数据库中保存一些信息,并且我需要从一些单选按钮中获取这些信息。 我尝试了很多方法来获取数据,但没有任何效果。 所以我想问一下如何从template,html 获取models.py 中的这些数据。

这是views.py中的代码:

def question1(request):
    form = CHOICES(request.POST)
    return render(request, 'question1.html', {'form': form})

这是模板question1.html

<form class="form-inline" method='POST' action="" enctype='multipart/form-data'>{% csrf_token %}

                {{form.NUMS}}
</form>

然后有forms.py中的表格:

NUMS = [
  ('one', 'one'),
  ('two', 'two'),
  ('three', 'three'),
  ('four', 'four'),
  ('five', 'fives'),
]

class CHOICES(forms.Form):
    NUMS = forms.ChoiceField(choices=NUMS, widget=forms.RadioSelect)

然后我真的不知道如何在models.py 中执行该功能

【问题讨论】:

    标签: python django django-models django-forms django-templates


    【解决方案1】:

    您可能应该仔细阅读此内容。 https://docs.djangoproject.com/en/3.2/topics/forms/

    基本上你想要一个model form 链接到models.py 中的模型

    那么(假设您的表单名为 CHOICES)在您的视图中将是这样的:

    def question1(request):
        if request.method == 'POST':
            form = CHOICES(request.POST)
            if form.is_valid():
                print(form.cleaned_data())
                form.save()
        else:
            form = CHOICES()
        return render(request, 'question1.html', {'form': form})
    

    模板应该是这样的:

    <form class="form-inline" method='POST' action="" enctype='multipart/form-data'>
        {% csrf_token %}
        {{ form }}
        <input type="submit" value="Submit">
    </form>
    

    【讨论】:

    • 感谢您的回答。但问题是我不知道如何让选定的单选按钮将其保存在数据库中
    • @Burzi 我已经编辑了答案,让 print(form.cleaned_data()) 打印语句将打印表单中的值。它们也将在 request.POST 中。
    • 在 print(form.cleaned_data()) 我有这个错误:请求方法:POST 请求 URL:127.0.0.1:8000/question1.html Django 版本:3.2.8 异常类型:TypeError 异常值:'dict' 对象是不可调用
    • @Burzi my bad 添加了额外的括号。
    猜你喜欢
    • 1970-01-01
    • 2021-01-19
    • 2014-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 2013-03-28
    相关资源
    最近更新 更多