I try to create dynamic choice. I fill choices with unit_list
. Data to unit_list
loading from API (units
). I set the choices dynamicly in the constructor. But when I try to save a new form, it gives 'value error'.
Have a nice day.
class Announcement(models.Model):
title = models.CharField(max_length=200, verbose_name=_('İlan Başlığı'))
unit = models.IntegerField(null=True,blank=True)
def announcement_new(request):
response = requests.get('http://127.0.0.1:8001/api/units/list/')
units = response.json()
unit_list=[]
for unit in units:
unit_list.append(((int(unit.get('id'))), str(unit.get('name'))))
ann_form = AnnouncementForm(unit_list)
if request.method == 'POST':
ann_form = AnnouncementForm( request.POST)
if ann_form.is_valid():
ann_instance = ann_form.save(commit=False)
ann_instance.save()
return redirect('ann')
else:
print('Hata: ',ann_form.errors)
else:
context = {
'ann_form':ann_form,
}
return render(request,'pages/ann/ann_new.html',context)
class AnnouncementForm(forms.ModelForm):
title = forms.CharField(widget=forms.TextInput(attrs={
"class": "form-control",
"placeholder": "",
}))
unit = forms.ChoiceField(
required=False,
widget=forms.Select(attrs={
"class": "form-control form-select select2",
}),)
def __init__(self, unit_list, *args, **kwargs):
super(AnnouncementForm, self).__init__(*args, **kwargs)
self.fields['unit'].choices = unit_list
class Meta:
model = Announcement
fields = "__all__"
Traceback (most recent call last):
File "C:\Users\feyza\OneDrive\Masaüstü\basvuru\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\feyza\OneDrive\Masaüstü\basvuru\venv\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response
self.check_response(response, callback)
File "C:\Users\feyza\OneDrive\Masaüstü\basvuru\venv\lib\site-packages\django\core\handlers\base.py", line 332, in check_response
raise ValueError(
Exception Type: ValueError at /ann/new/
Exception Value: The view apps.announcements.views.announcement_new didn't return an HttpResponse object. It returned None instead.
Hello, I found the solution by changing my method. Instead of sending the unit_list data to the form over the view, I created it directly in form.py.
class AnnouncementForm(forms.ModelForm):
title = forms.CharField(widget=forms.TextInput(attrs={
"class": "form-control",
"placeholder": "",
}))
unit = forms.ChoiceField(
required=False,
widget=forms.Select(attrs={
"class": "form-control form-select select2",
}),)
def __init__(self, *args, **kwargs):
super(AnnouncementForm, self).__init__(*args, **kwargs)
response = requests.get('http://127.0.0.1:8001/api/units/list/')
units = response.json()
unit_list=[]
for unit in units:
unit_list.append(((int(unit.get('id'))), str(unit.get('name'))))
self.fields['unit'].choices = unit_list
class Meta:
model = Announcement
fields = "__all__"