Using Django ChoiceField gives a Value Error

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__"
Back to Top