gpt4 book ai didi

django - 我如何在 Django 中显示我的 RadioSelect 小部件

转载 作者:行者123 更新时间:2023-12-04 04:13:45 27 4
gpt4 key购买 nike

我有一个模型、表单、 View ,但我似乎无法实际显示 RadioSelect 小部件。它没有显示任何内容,我认为除了 View 之外一切都很好,但是,我不确定。我基本上希望有人从两个单选按钮中进行选择和选择,提交然后能够注册为两个选项之一,但就像我说的那样我什至无法显示按钮。

View .py

def registration(request):
reg = Registration.objects.all()
return render(request, 'HTML/Registration.html', {"reg":reg})

模型.py

class Registration(models.Model):
OPTIONS = (
('COUNS','Counsellor'),
('CLIENT','Client'),
)
SELECT = models.CharField(max_length=15,
choices=OPTIONS)

表单.py

class Registration(forms.ModelForm):
class Meta:
model = Registration
fields = '__all__'
widgets = {'SELECT': forms.RadioSelect}

HTML

<form method="POST">
{% csrf_token %}
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3
border-bottom">
<h1 class="h2">Registration</h1>
</div>

{% render_field reg.SELECT %}

<div class="form-row">
<div class="col pt-md-2">
<input type="submit" value="Next" class="btn btn-primary" style="float: right;">
</div>
</div>
</form>

最佳答案

您指的是模型,而不是表单。请不要为模型和表单指定相同的名称。在表单中添加后缀 Form 是很常见的。

# app/forms.py

from django import forms
from app.models import Registration

class <b>RegistrationForm</b>(forms.ModelForm):
class Meta:
model = Registration
fields = '__all__'
widgets = { 'SELECT': forms.RadioSelect }

然后在 View 中,您可以创建这样的表单:

# app/views.py

from app.forms import <b>RegistrationForm</b>
from django.shortcuts import redirect

def registration(request):
if request.method == 'POST':
reg = <b>RegistrationForm(</b>request.POST, request.FILES<b>)</b>
if reg.is_valid():
reg.save()
return redirect(<i>'name-of-some-view'</i>)
else:
reg = <b>RegistrationForm()</b>
return render(request, 'HTML/Registration.html', {'reg': reg})

Note: In case of a successful POST request, you should make a redirect [Django-doc] to implement the Post/Redirect/Get pattern [wiki]. This avoids that you make the same POST request when the user refreshes the browser.

关于django - 我如何在 Django 中显示我的 RadioSelect 小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61163097/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com