'Getting issue while edit record in Django Form

I Everyone i am getting issue while edit record based on problem id, only problem record show automatically chatquestion and option record not show automatically, maybe my ORM is wrong somewhere, even when i save record getting error, please help me out. this is crud operation i have done list and add record but that is also complex if anyone can do simple its more helpful for me.. Thanyou.

models.py -this is all 3 models.

class Problem(models.Model):
    Language = models.IntegerField(choices=Language_CHOICE, default=1)
    type = models.CharField(max_length=500, null=True, blank=True)

    def __str__(self):
        return self.type
        

class ChatQuestion(models.Model):
    question = RichTextField(null=True, blank=True)
    problem_id = models.ForeignKey(
        Problem,
        models.CASCADE,
        verbose_name='Problem',
    )
    sub_problem_id = models.ForeignKey(
        SubProblem,
        models.CASCADE,
        verbose_name='Sub Problem',
        null=True,
        blank=True
    )

    def __str__(self):
        return self.question


class Option(models.Model):
    option_type = models.CharField(max_length=250, null=True, blank=True)
    question_id = models.ForeignKey(
        ChatQuestion,
        models.CASCADE,
        verbose_name='Question',
    )
    problem=models.ForeignKey(
        Problem,
        models.CASCADE,
        verbose_name='Problem',
        null=True,
        blank=True
    )
    next_question_id = models.ForeignKey(ChatQuestion, on_delete=models.CASCADE, null=True, blank=True,
                                         related_name='next_question')

forms.py

class Editchatbot(forms.Form):
    problem=forms.ModelChoiceField(queryset=Problem.objects.all(), required=True, widget=forms.Select(attrs={'class': 'form-control select2'}))
    question=forms.ModelChoiceField(queryset=ChatQuestion.objects.all(), required=True, widget=forms.Select(attrs={'class': 'form-control select2'}))
    option=forms.ModelChoiceField(queryset=Option.objects.all(), required=True, widget=forms.Select(attrs={'class': 'form-control select2'}))
    class Meta:
        fields=['problem','question','option']

views.py

def edit_chatbot(request,id=None):
    problem=Problem.objects.get(pk=id)
    question=ChatQuestion.objects.filter(problem_id=id)
    option=Option.objects.filter(question_id=id)
    if request.method == 'POST':
        form = Editchatbot(request.POST)
        if form.is_valid():
            problem=form.cleaned_data['problem']
            question=form.cleaned_data['question']
            option=form.cleaned_data['option']
            form.save()
            messages.success(request,'successfully!')
            return redirect('/fleet/chatbot_list')
        else:
            messages.error(request,'Please correct following',form.errors)
    else:
        form = Editchatbot(initial={'problem':problem,'question':question,'option':option})
    context = {
        'menu_management': 'active',
        'chatbot': 'active',
        'form': form,
        'question':question,
        'option':option
    }
    return render(request, "chatbot/edit_chatbot.html", context=context)

output error

Traceback (most recent call last):
  File "C:\Users\HI\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\HI\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\HI\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "E:\20_jan_2022_everest\everest_jarvis\fleet\views.py", line 4129, in edit_chatbot
    form.save()
AttributeError: 'Editchatbot' object has no attribute 'save'
ERROR "POST /fleet/chatbot/edit/1 HTTP/1.1" 500 79813


Solution 1:[1]

Answer to initial error

Change these three lines form using changed_data to using cleaned_data.

changed_data is a list that contains the names of the fields that have changes, it does not contain the changes themselves. cleaned_data stored the data after validation. See the Checking which form data has changed docs for more

problem=form.cleaned_data['problem']
question=form.cleaned_data['question']
option=form.cleaned_data['option']

Answer to 2nd error - no save method

Your form should extend from forms.ModelForm rather than form.Form. The former allow you to build database-driven forms (see the docs) whereas the latter as you are currently using allows you to create forms that are not associated with models (see the docs)

You may also find this reference site useful Classy Django Forms it's an extremely useful reference site and works in a similar way to the more commonly used Class Class-Baed Views reference site

Update 3 - Based on reply

I admit I looked more at your error than the what you were doing. I see now that you using multiple models within one form. So one approach would be to keep using the forms.Form and then add a save method yourself that you can call and write custom logic to save to each model. Another option would be use a model form using one model via it's meta, add the other fields as custom ones, overload the save method to save the fist model and then add your own logic to save the other models.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1