Home > OS >  Django Crispy Form doesn't add or update database
Django Crispy Form doesn't add or update database

Time:12-04

Hello, I am writing a small project about a car shop and this is the problem I came up with.

I'm trying to add a new car and everything seems to work, but when I fill out the form and click submit, it just redirects me to products page without errors and without adding a new car to the database. Here is the code.

views.py

class AddProductView(View):
    action = 'Add'
    template_name = 'myApp/manipulate_product.html'
    context = {

    }
    form_class = ManipulateProductForm

    def get(self, req, *args, **kwargs):
        form = self.form_class()
        self.context['action'] = self.action
        self.context['form'] = form
        return render(req, self.template_name, self.context)

    def post(self, req, *args, **kwargs):
        form = self.form_class(req.POST or None)
        if form.is_valid():
            form.save()
        else:
            print(form.errors)

        return redirect('products', permanent=True)

models.py

class Car(models.Model):
    name = models.CharField(max_length=32)
    model = models.CharField(max_length=32, unique=True)
    price = models.IntegerField(validators=[
        MinValueValidator(0),
    ])

    def __str__(self):
        return f'{self.name} {self.model}'

forms.py

class ManipulateProductForm(forms.ModelForm):
    def __init__(self, action="Submit", *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.action = action
        self.helper = FormHelper(self)
        self.helper.add_input(Submit('submit', self.action, css_class='btn btn-primary'))

    class Meta:
        model = Car
        fields = '__all__'

manipulate_product.html

{% extends 'base.html' %}
{% load static %}
{% load crispy_forms_tags %}

{% block content %}
    <div >
        {% crispy form form.helper%}
    </div>
{% endblock %}

I'm sure the problem is in Crispy, because if I replace code in forms.py and manipulate_product.html to this

forms.py

class ManipulateProductForm(forms.ModelForm):
    class Meta:
        model = Car
        fields = '__all__'

manipulate_product.html

{% extends 'base.html' %}
{% load static %}
{% load crispy_forms_tags %}

{% block content %}
    <div >
        <form action="" method="POST">
            {% csrf_token %}
            {{ form.as_div }}
            <input type="submit" value="Submit">
        </form>
    </div>
{% endblock %}

Everything is working fine!

I noticed that when I use Crispy in AddProductView post method is_valid() method returns False but without Crispy it returns True

I have tried everything except one delete the whole project and start over. I searched on youtube , google , stackoverflow but didn't find anything similar. Looked at the Crysp documentation, but it's also empty.

I hope someone has come across this problem and can help me.

Thank you!

CodePudding user response:

Try rewriting your form like this:

class ManipulateProductForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ManipulateProductForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_action = 'Submit'
        self.helper.add_input(Submit('submit', 'Submit', css_class='btn btn-primary'))

    class Meta:
        model = Car
        fields = '__all__'

And in your template you can just do the following, since you used the default name of the helper:

{% crispy form %}
  • Related