Django 表单不通过 ModelForm 保存到数据库

Django form not saving to database via ModelForm

我正在尝试使用 ModelForm 将我的表单添加到数据库中,但它没有通过,甚至没有在视图中打印表单,我也尝试通过清理数据在视图中单独处理每个字段,但仍然没有插入任何内容数据库

我的view.py

def index(request):
    component = Component.objects.all()
    form = ComponentModelForm()
    if request == 'POST':
        form = ComponentModelForm(request.POST)
        print(form)
        if form.is_valid():
            form.save()
            return redirect('/maintenance')  
        else:
            form = ComponentModelForm()              
    context = {
        'components': component,
        'form':ComponentModelForm(),
    }
    return render(request, 'maintenance/index.html', context)

models.py

class Component(MPTTModel):
    name = models.CharField(max_length=100)
    manufacturer = models.CharField(max_length=100)
    model = models.CharField(max_length=100)
    serial_number = models.CharField(max_length=255)
    price = models.IntegerField()
    note = models.TextField()
    parent = TreeForeignKey("self", verbose_name=(
        "Parent Component"), blank=True, null=True, related_name='children', on_delete=models.CASCADE)

    def __str__(self):
        return f"{self.id}, {self.name}"

forms.py

class ComponentModelForm(forms.ModelForm):
    class Meta:
        model = Component
        fields = ("name",
                  "manufacturer",
                  "model",
                  "serial_number",
                  "price",
                  "note",
                  "parent",)

模板:

   <div>
         <form method='POST' action=''>
            {% csrf_token %}
            {{form.as_p}}
            <input type="submit" value='Create'/>
         </form>
      </div>

尝试

If request.method == 'POST'

而不是:

If request == 'POST'