Я уже некоторое время пытаюсь заставить радио-кнопки отображаться на моем сайте Django и продолжаю сталкиваться с проблемами.Я наконец узнал о визуализированных вручную полях формы и работал с этим.Когда я их показываю, я не могу их выбрать.Если я смогу их выбрать, то я никогда не смогу выдвинуть эту информацию в модель.Я пробовал много разных вещей, но продолжаю выдавать пустой.Я прочитал эту статью Как визуализировать формы Django вручную , надеясь, что это поможет, но я не уверен, что понимаю разницу между тем, что он делает, и тем, что я делаю.Если речь идет не об объявлении значения, что я понимаю, то я не знаю, как это сделать, чтобы кнопки отображались.Кроме того, когда я могу выбрать переключатели и POST, кроме того, что они не публикуются в модели, я получаю эту ошибку <ul class="errorlist"><li>month<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
внутри консоли.
Вот что у меня сейчас.Я попытаюсь прокомментировать мои попытки.
models.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
forms.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)
views.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)
index.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>