Django.fun

django form gettting error while posting data

form.py
while creating new data based on city getting error(\forms.py", line 709, in init super(IncentiveForm,self).init(*args,**kwargs) TypeError: init() got an unexpected keyword argument 'city_id')

class IncentiveForm(forms.ModelForm):
    city_id = CityModelChoiceField(
        required=False, queryset=City.objects.all(), label='City', widget=Select2Widget)
    
    class Meta:
        model=Incentive
        fields= ['start_date','end_date','no_of_trips','incentive']
        
    
    def __init__(self,*args,**kwargs):              
        self.request = kwargs.pop('request', None)
        super(IncentiveForm,self).__init__(*args,**kwargs)

views.py

def incentive_form(request,city_id=None):
    city = City.objects.get(pk=city_id)
    create=Incentive.objects.filter(city_id=city_id)
    if request.method == 'POST':
        form=IncentiveForm(request.POST,city_id=city_id)
        if form.is_valid():
            start_date=form.cleaned_data['start_date']
            end_date=form.cleaned_data['end_date']
            no_of_trips=form.cleaned_data['no_of_trips']
            incentive=form.cleaned_data['incentive']
            if create is not None:
                create.start_date=start_date
                create.end_date=end_date
                create.no_of_trips=no_of_trips
                create.incentive=incentive
                create.city_id=city_id           
                create.save()
                messages.success(request,'Incentive data created successfully!')
            
    else:
        form=IncentiveForm()

        
    context={
        'menu_incentive': 'active',
        'submenu_incentive_list': 'active',
        'city_id': city_id,
        'city': city,
        'form':form,


    }
    return render(request,"hiringprocess/incentive.html",context=context)

traceback

return view_func(request, *args, **kwargs)
  File "E:\Ashish Pandey\everest_jarvis\fleet\views.py", line 3408, in incentive_form
    form=IncentiveForm(request.POST,city_id=city_id)
  File "E:\Ashish Pandey\everest_jarvis\fleet\forms.py", line 709, in __init__
    super(IncentiveForm,self).__init__(*args,**kwargs)
TypeError: __init__() got an unexpected keyword argument 'city_id'
ERROR "POST /fleet/incentive/1/add HTTP/1.1" 500 86701

Answers: 2

Answered by amadou sow, Nov. 25, 2021, 9:58 a.m.

change this line

form=IncentiveForm(request.POST,city_id=city_id)

to

form=IncentiveForm(request.POST)

this will solve the error you are getting but note that you are actually not handling that form well.let me know if you need more help on this.

Answered by Tonio, Nov. 25, 2021, 11:59 a.m.

First, you need to get a Incentive instance if exist in order to update it's values. In your code, Incentive.objects.filter(city_id=city_id) returns a queryset, not a object instance. To get a instance (or null if not exists) you can:

try:
    incentive = Incentive.objects.filter(city_id=city_id)[0]
except Incentive.DoesNotExist
    incentive = None

or more easy: incentive = Incentive.objects.filter(city_id=city_id).first(). Now, incentive is an Incentive instance or None if it not exists.

Second, a ModelForm automaticaly sets the properties to a model with the save method. You don't need set it manually with start_date=form.cleaned_data['start_date']. You only need set the correct model instance in the forms constructor, with the instance parameter. If the instance is None, the form creates itself a new one to save in the DB.

Bringing it all together:

def incentive_form(request,city_id=None):
    # Best replace this line with city = get_object_or_404(City, pk=city_id)
    city = City.objects.get(pk=city_id)
    incentive = Incentive.objects.filter(city_id=city_id).first()

    if request.method == 'POST':
        form = IncentiveForm(instance=instance, data=request.POST)
        if form.is_valid():
            form.save() # <- This returns the upadted or created instance.
            messages.success(request,'Incentive data created successfully!')
            # After the messages, best sends a redirect to prevent the user 
            # re-sends the form  when try to refresh the page. 
            # The next example returns to the same url.
            return HttResponseRedirect(request.path)
    else:
        # This loads the instance values in the form
        form = IncentiveForm(instance=instance)

    # ....