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

How can i display my RadioSelect Widget in django

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

views.py

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

models.py

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

forms.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 }

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

# 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.