Hi All, I am working on small hands-on project.. and having an issue when calling the POST method with form.py
Below is the code. Here i have two models.. one is Category and another is SubCategory. For SubCategory i have created form "SubCategoryFormv2" in forms.py... where i am checking if categoryid is passed then pre-select that Category, else display all Category for selection. On submit the form from html... i am getting TypeError. (full error is displayed below) Please help... What i could identify is with the POST method, when the statement *form = SubCategoryFormv2(request.POST)* is executed, it is expecting some id.. not sure what is this id. # models.py ------------------------ class SubCategory(models.Model) : category = models.ForeignKey(Category, null = True, on_delete = models.SET_NULL) name = models.CharField(max_length = 200, null = True) dateCreated = models.DateTimeField(default = timezone.now) createdBy = models.ForeignKey(User, on_delete = models.PROTECT ) # forms.py -------------------------- class SubCategoryFormv2(forms.ModelForm): class Meta: model = SubCategory fields = '__all__' widgets = {'dateCreated' : DateInput()} def __init__(self, categoryid=None, *args, **kwargs): super(SubCategoryFormv2, self).__init__(*args, **kwargs) if categoryid is not None: self.fields['category'] = forms.ModelChoiceField(initial=categoryid, queryset=Category.objects.filter(id=categoryid)) # views.py -------------------------------- def createSubCategoryV2(request, categoryid=None): context = { 'title':'Add SubCategory' } if request.method =='POST': print('POST METHOD') form = SubCategoryFormv2(request.POST) print('POST METHOD - SubCategoryFormv2 called') if form.is_valid(): ins = form.save(commit=True) print('Inside for form validation') messages.success(request, f'SubCategory added Successfully') return redirect('listsubcategory') else: # for GET method. print('GET METHOD') form = SubCategoryFormv2(categoryid) context["form"]= form return render(request, 'DailyBudget/subcategory_form.html', context) Error : Exception Value: Field 'id' expected a number but got <QueryDict: {'csrfmiddlewaretoken': ['XXXXXXXXXX'], 'category': ['12'], 'name': ['Test Data'], 'dateCreated': ['2020-05-02'], 'initial-dateCreated': ['2020-05-02 04:11:38'], 'createdBy': ['1']}>. -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/1fa99634-a1cb-477c-8972-19f23d7f2284%40googlegroups.com.