首页 > 解决方案 > 为什么我的 django 模板中的单选按钮不能被选择或显示?

问题描述

一段时间以来,我一直试图让单选按钮显示在我的 Django 网站上,但一直遇到问题。我终于发现了手动呈现的表单字段并一直在使用它。当我让它们显示时,我无法选择它们。如果我能够选择它们,那么我似乎永远无法将这些信息推送到模型中。我尝试了很多不同的东西,但总是空虚。我读了这篇文章“如何手动渲染 Django 表单”' 希望它会有所帮助,但我不确定我是否理解他正在做的事情和我正在做的事情之间的区别。如果这是关于不声明一个值,这是我所理解的,那么我不知道如何以一种让按钮显示的方式来做到这一点。此外,当我能够选择单选按钮和 POST 时,除了它不发布到模型之外,我<ul class="errorlist"><li>month<ul class="errorlist"><li>This field is required.</li></ul></li></ul>在控制台内收到此错误。

这是我现在所拥有的。我将尝试对我的尝试进行编码评论。

模型.py

from django.db import models

class CustomerData(models.Model):
    firstname = models.CharField(max_length=255)
    lastname = models.CharField(max_length=255)
    npo = models.CharField(max_length=255)
    email = models.CharField(max_length=255)
    phone = models.CharField(max_length=255)
    month = models.CharField(max_length=255)

    def __str__(self):
        return self.npo

class Ebook(models.Model):
    ebook = models.CharField(max_length=255)

    def __str__(self):
        return self.ebook

表格.py

from django.forms import ModelForm
from django import forms
from .models import CustomerData, Ebook

MONTH_CHOICES = [
    ('January', 'January'),
    ('February', 'February'),
    ('March','March'),
    ('April', 'April'),
    ('May', 'May'),
    ('June','June'),
    ('July', 'July'),
    ('August', 'August'),
    ('September','September'),
    ('October','October'),
    ('November','November'),
    ('December','December')
]


class ContactForm(ModelForm):
    firstname = forms.CharField(label='First Name:', error_messages={'required': '*'}, required=True, widget=forms.TextInput(attrs={"placeholder" : "Richard"}))
    lastname = forms.CharField(label='Last Name:', error_messages={'required': '*'}, required=True, widget=forms.TextInput(attrs={"placeholder" : "Eby"}))
    npo = forms.CharField(label='Organization:', error_messages={'required': '*'}, required=True, widget=forms.TextInput(attrs={"placeholder" : "The Coding Recruiter"}))
    email = forms.CharField(label='Email:', error_messages={'required': '*'}, required=True, widget=forms.TextInput(attrs={"placeholder" : "email@example.com"}))
    phone = forms.CharField(label='Phone:', required=False, widget=forms.TextInput(attrs={"placeholder" : "XXX-XXX-XXXX"}))
    month = forms.ChoiceField(label='Month of Renewal/Expiration:', choices=MONTH_CHOICES, widget=forms.RadioSelect(), required=True)
    class Meta:
        model = CustomerData
        fields = ['firstname', 'lastname', 'npo', 'email', 'phone', 'month']

    def clean(self):
        cleaned_data = super(ContactForm, self).clean()
        firstname = cleaned_data.get('firstname')
        lastname = cleaned_data.get('lastname')
        phone = cleaned_data.get('phone')
        email = cleaned_data.get('email')
        month = cleaned_data.get('month')
        if not firstname and not lastname and not phone and not email and not month:
            raise forms.ValidationError('You have to write something!')



EBOOK_CHOICES = [
    ('Grant Writing', 'Grant Writing'),
    ('Volunteer Management', 'Volunteer Management')
]

class EbookForm(ModelForm):
    ebook = forms.ChoiceField(label='', choices=EBOOK_CHOICES, widget=forms.RadioSelect(), error_messages={'required': 'Ebook Choice Required'})
    class Meta:
        model = Ebook
        fields = ['ebook']

class RawContactForm(forms.Form):
    firstname = forms.CharField(label='First Name:', error_messages={'required': '*'}, required=True, widget=forms.TextInput(attrs={"placeholder" : "Richard"}))
    lastname = forms.CharField(label='Last Name:', error_messages={'required': '*'}, required=True, widget=forms.TextInput(attrs={"placeholder" : "Eby"}))
    npo = forms.CharField(label='Organization:', error_messages={'required': '*'}, required=True, widget=forms.TextInput(attrs={"placeholder" : "The Coding Recruiter"}))
    email = forms.CharField(label='Email:', error_messages={'required': '*'}, required=True, widget=forms.TextInput(attrs={"placeholder" : "email@example.com"}))
    phone = forms.CharField(label='Phone:', required=False, widget=forms.TextInput(attrs={"placeholder" : "XXX-XXX-XXXX"}))
    month = forms.ChoiceField(label='Month of Renewal/Expiration:', choices=MONTH_CHOICES, widget=forms.RadioSelect(), required=True)

视图.py

def index(request):
    form = ContactForm(request.POST or None)  
    form2 = EbookForm(request.POST or None)
    context = {
        'form2' : form2,
            'form' : form
        }
    if request.method == 'POST':
        form = ContactForm(request.POST)
        context = {
            'form2' : form2,
            'form' : form
        }
    if form.is_valid() & form2.is_valid():
        subject = 'FaithGuard Confirmation Email'
        # Also tried request.POST.get() and a few other things here
        fname = form.cleaned_data['firstname']
        lname = form.cleaned_data['lastname']
        email = form.cleaned_data['email']
        ebook = form2.cleaned_data['ebook']

        ebook = form2.save()
        newcustomer = form.save()
    else:
         print('Not Valid')

    return render(request, 'landingpage/index.html', context)


# This is an alternative approach that I took to try and bypass the is_valid function since it seemed to be causing the issue, or so I think/thought
    def index2(request):
    form = RawContactForm()
    if request.method == "POST":
        form = RawContactForm(request.POST or None)
        if form.is_valid():
            print(form.cleaned_data)
            CustomerData.objects.create(**form.cleaned_data)
        else:
            print(form.errors)
    context = {
        'form' : form
     }

    return render(request, 'landingpage/bootstrap.html', context)

索引.html

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

    <!-- 4 different basic 4 approaches here -->

    <!-- {{form}} /// Radio buttons don't display and can't tell which is selected -->

    <!-- {{form.as_p}} /// Radio buttons don't display and can't tell which is selected -->

    <!-- {{form.as_table}} /// Radio buttons don't display and can't tell which is selected -->


    <!-- {{form.as_ul}} /// Radio buttons don't display and can't tell which is selected -->




  <!-- Slightly altered version I found on the Django Documentation -->
<!-- ////This is selectable, but doesn't push to the model -->
    <div class="fieldWrapper">  
            {{ form.month.errors }}
    <label>Month:</label>
    <br>
        {% for month, monthb in form.fields.month.choices %}
            <label>
             <input name="group1" type="radio" />
             <span> {{month}} </span>
            </label>
        {% endfor %}
    </div>




    <!-- /// Alternate approach to one above. Can't select the radio buttons, but each displays on screen as a radio button -->
    <div>  
        {% for a, b in form.fields.month.choices %}
        <input type="radio" name="phone" id="id_month">
        <span>{{a}}</span>
        {% endfor %} 


        <!-- /// I noticed that when I do it this way, if the label starts and ends next to itself, then it won't dispaly all 12 months as a radio button. -->
<div class="fieldWrapper">  
    {{ form.month.errors.as_text }}   
    <!-- ///// Also did this not using the as_text, but that had not change in affect -->
    {% for month, monthb in form.fields.month.choices %}
   <label>
  <input value='month' type="radio" />
     <span> {{month}} </span>
    </label>
    {% endfor %}
</div>




<div class="div right-align">
<button class="btn waves-effect waves-light" type="submit" name="action" value='Save'>Submit</button>
</div>

</div>
              </form>

标签: python-3.xdjango-modelsdjango-formsdjango-templatesdjango-views

解决方案


这是因为我使用的是 MaterializeCSS。一旦我删除它,它就开始工作了。注意未来的项目,不要使用 Materialize


推荐阅读