我试图在模型表单中保存布尔字段。我得到类型错误'bool'对象不是可迭代的,我不太确定为什么。我愚蠢地认为django只是处理了布尔值在数据库(PostgreSQL)中保存为字符串的事实,因为它在新用户注册后的信号保存后成功地保存了它。经过一点研究和尝试和错误,我在这里迷路了。任何建议将不胜感激。
class SundayBoolAvailable(models.Model):
teacher_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True,
default='',
related_name='teacher_bool_available_id')
sunday_bool = models.BooleanField(null=False, default=True)
class SundayTime(models.Model):
teacher_id_time = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True,
default='',
related_name='teacher_time_available_id')
sun_from_hour = models.TimeField(choices=HOUR_CHOICES, null=True, blank=True)
sun_to_hour = models.TimeField(choices=HOUR_CHOICES, null=True, blank=True)
def __str__(self):
return str(self.teacher_id)
class SundayBoolForm(forms.ModelForm):
sunday_bool = forms.BooleanField(required=False)
class Meta:
model = SundayBoolAvailable
fields = ['sunday_bool', ]
# widgets = {
# 'sunday': forms.HiddenInput(),
# }
def __init__(self, *args, **kwargs):
super(SundayBoolForm, self).__init__(*args, **kwargs)
self.fields['sunday_bool'].required = False
class SundayTimeForm(forms.ModelForm):
class Meta:
model = SundayTime
fields = ['sun_to_hour', 'sun_from_hour']
# widgets = {
# 'sunday': forms.HiddenInput(),
# }
SundayInlineFormSet = inlineformset_factory(MyUser, SundayTime, form=SundayTimeForm, extra=0,
can_delete=True, min_num=0, validate_min=True, max_num=3, validate_max=True,
fields=['sun_to_hour', 'sun_from_hour'])
@login_required()
@teacher_required
def availability_update_view(request, pk, *args, **kwargs):
sun_obj = get_object_or_404(MyUser, id=pk)
if request.method == 'POST':
sun_bool = SundayBoolForm(request.POST, request.FILES, instance=sun_obj)
sunday_formset = SundayInlineFormSet(request.POST, request.FILES, instance=sun_obj, prefix='id_sunday_formset')
if all(sun_bool.is_valid() and sunday_formset.is_valid()):
sun_bool_instance = sun_bool.save(commit=False)
# I feel there is something missing here?
sun_bool_instance.save()
sunday_formset.save()
messages.success(request, f'You have successfully updated your availability!')
return redirect('teacher_profile')
else:
sun_bool = SundayBoolForm(instance=sun_obj)
sunday_formset = SundayInlineFormSet(instance=sun_obj, prefix='id_sunday_formset')
context = {
'sun_bool': sun_bool, 'sunday_formset': sunday_formset
}
return render(request, 'appointment/availability_update_new.html', context)
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_sunday_appointment_bool(instance, created, **kwargs):
if created:
SundayBoolAvailable.objects.get_or_create(teacher_id=instance)
{% load crispy_forms_tags %}
{% load static %}
{% block content %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" type="text/css" href="{% static 'css/availability_update_new.css' %}">
</head>
<body>
<input type="button" class="sun-not-available" value="Not Available Sunday" onclick="sunCheckOne(); sunHideShow()"
id="sun-not-available">
<form id="all-add-form" method="POST" action="" enctype="multipart/form-data">
<div class="sunday-all" id="sunday-all-id">
{% csrf_token %}
<legend class="bottom mb-4">Profiles Info</legend>
<div class="sun-bool">
{{ sun_bool.sunday_bool }}
</div>
</div>
{{ sunday_formset.management_form }}
{% for sun_form in sunday_formset %}
{% for hidden in sun_form.hidden_fields %}
{{ hidden }}
{% endfor %}
<div class="sun_time_slot_form">
{{ sun_form }}
<button class="delete-sun-form" type="button" id="delete-sun-btn" onclick=""> Delete This
Sunday
Timeslot
</button>
</div>
{% endfor %}
<button id="add-sun-form" type="button" class="button">Add Other Sunday Times</button>
<input type="submit" name="submit" value="Submit" class="btn btn-primary"/>
</form>
<script type="text/javascript" src="{% static 'js/add_timeslot.js' %}"></script>
</body>
</html>
{% endblock content %}
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/availability_update_new/3/
Django Version: 3.0.4
Python Version: 3.9.6
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mysite',
'users.apps.UsersConfig',
'appointments.apps.TeacherAppointmentConfig',
'crispy_forms',
'imagekit',
'compressor',
'django_extensions']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "C:\Users\Admin\PycharmProjects\untitled7\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Admin\PycharmProjects\untitled7\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Admin\PycharmProjects\untitled7\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Admin\PycharmProjects\untitled7\venv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\Admin\PycharmProjects\untitled7\venv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\Admin\PycharmProjects\untitled7\appointments\views.py", line 111, in availability_update_view
if all(sun_bool.is_valid() and sunday_formset.is_valid()):
Exception Type: TypeError at /availability_update_new/3/
Exception Value: 'bool' object is not iterable
1条答案
按热度按时间flvlnr441#
替换:
其中:
all(…)
[Python-doc]接受一个iterable并检查是否所有项目都具有真实性True
。但这里只有一个布尔值。