提问人:Thomas Leon Rodrigues 提问时间:11/14/2023 更新时间:11/14/2023 访问量:15
我的 django 复选框组没有收到有效的值,我该怎么办?
My django checkbox group is not recieving the values as valid, what do I do?
问:
我是 Django 的新手,只是因为我正在做的一个学生项目而潜入其中,并且这个复选框有一个我不明白的问题......
<div class="form-group">
<label>4 - Deficiência do Participante: <span>*</span></label>
<div class="checkbox-group">
{% for disability in form.participant_disability %}
<div class="form-check">
{{ disability }}
</div>
{% endfor %}
</div>
</div>
我尝试搜索、删除、更改,但没有任何效果,这是 forms.py、models.py 和 views.py
models.py
from django.db import models
from .choices import PARTICIPANT_DISABILITY_CHOICES
class Disability(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class ParticipantResponse(models.Model):
PARTICIPANT_DISABILITY_CHOICES = [
('auditiva', 'Deficiência Auditiva'),
('fisica', 'Deficiência Física'),
('intelectual', 'Deficiência Intelectual'),
('visual', 'Deficiência Visual'),
('autista', 'Transtorno Espectro Autista'),
# Add more options as needed
]
participant_disability = models.CharField(max_length=255, choices=PARTICIPANT_DISABILITY_CHOICES, default=[''])
def __str__(self):
return f"Response for {self.participant_name}"
views.py
from django.shortcuts import render, redirect
from .forms import ParticipantResponseForm
from .models import ParticipantResponse
def form_view(request):
if request.method == 'POST':
form = ParticipantResponseForm(request.POST)
if form.is_valid():
# Convert selected disability choices to integers
form.cleaned_data['participant_disability'] = [int(choice) for choice in form.cleaned_data['participant_disability']]
# Save the form data without committing to the database
response = form.save(commit=False)
# Assign the disability choices to the response object
response.participant_disability.set(form.cleaned_data['participant_disability'])
# Save the response object to the database
response.save()
return redirect('responses')
else:
print(form.errors)
print(request.POST)
else:
form = ParticipantResponseForm()
return render(request, 'form.html', {'form': form})
def show_responses(request):
responses = ParticipantResponse.objects.all()
print(responses)
return render(request, 'responses.html', {'responses': responses})
forms.py
from django import forms
from .choices import PARTICIPANT_DISABILITY_CHOICES
from .models import ParticipantResponse, Disability
class ParticipantResponseForm(forms.ModelForm):
PARTICIPANT_DISABILITY_CHOICES = [(str(disability.id), disability.name) for disability in Disability.objects.all()]
participant_disability = forms.MultipleChoiceField(
choices=PARTICIPANT_DISABILITY_CHOICES,
widget=forms.CheckboxSelectMultiple,
required=True,
label='4 - Deficiência do Participante'
)
class Meta:
model = ParticipantResponse
exclude = []
fields = '__all__'
widgets = {
'birth_date': forms.DateInput(attrs={'type': 'date', 'class': 'w3-input', 'id': 'id_birth_date'}),
}
def __init__(self, *args, **kwargs):
super(ParticipantResponseForm, self).__init__(*args, **kwargs)
self.fields['participant_disability'].choices = PARTICIPANT_DISABILITY_CHOICES
如果你能帮我,我就很棒了。
答:
你的代码中有不止一个问题,但不要担心,这在学习 Django 的初期是很正常的。你的项目似乎对学习很有启发性。
首先,在初始化中,您将动态设置participant_disability选项:forms.py
ParticipantResponseForm
PARTICIPANT_DISABILITY_CHOICES = [(str(disability.id), disability.name) for disability in Disability.objects.all()]
这是正确的,但它依赖于数据库中已存在的对象。如果“残疾”表中没有条目,则您的选择将为空。Disability
其次,您正在使用 带有小部件。这是处理多个复选框的正确方法。但是,您的模型字段是 ,这与用户选择的多个选项不一致。对于多个选择,a 会更合适,或者您需要将选项列表作为 .MultipleChoiceField
CheckboxSelectMultiple
participant_disability
CharField
ManyToManyField
CharField
另一个是,在您的函数中,尝试将残疾选择转换为整数,然后使用 .这不是必需的,也不会起作用,因为 .这段代码似乎写得好像是一个.form_view
response.participant_disability.set(...)
participant_disability
CharField
participant_disability
ManyToManyField
我的主要建议是将模型中的字段更改为引用模型的字段,或者通过将所选选项连接/拆分为单个字符串来正确处理。participant_disability
ParticipantResponse
ManyToManyField
Disability
CharField
评论