Home > Blockchain >  OrderForm not saving data to django database
OrderForm not saving data to django database

Time:04-07

i'm creating a webapp that allows a user to enter information in a form which then saves the data into django. Everything works well, I can add information to the form in the template and press submit however the data is not saved into the database (I cannot see it in my admin panel inside 'Order' table. I have the if form.is_valid() form.save() in my views.py file which should POST the data to my database but its not.

Anyone know what i'm doing wrong?

Order model from models.py

class Order(models.Model):
    STATUS = (
            ('Pending', 'Pending'),
            ('Out for delivery', 'Out for delivery'),
            ('Delivered', 'Delivered'),
            )
    # on_delete = If customer is delete, we dont delete child (orders), customer just becomes null without deleting order
    customer = models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL)
    product = models.ForeignKey(Product, null=True, on_delete= models.SET_NULL)
    date_created = models.DateTimeField(auto_now_add=True, null=True)
    status = models.CharField(max_length=200, null=True, choices=STATUS)

forms.py

OrderForm class is inherited by CreateOrder views.py

from django.forms import ModelForm
from .models import Order

class OrderForm(ModelForm):
    class Meta:
        model = Order
        fields = '__all__'

createOrder function from views.py:

def createOrder(request):
    
    form = OrderForm()
    if request.method == 'POST':
        #print('Printing POST:',request.POST)
        form = OrderForm(request.POST)
        #form handles the process of saving to database/
        if form.is_valid():
            form.save
            return redirect('/')
    context = {'form':form}
    return render(request, 'accounts/order_form.html', context)

CodePudding user response:

You are calling a function with form.save, you forgot ():

views.py

def createOrder(request):
    
    form = OrderForm()
    if request.method == 'POST':
        #print('Printing POST:',request.POST)
        form = OrderForm(request.POST)
        #form handles the process of saving to database/
        if form.is_valid():
            form.save()  # Here
            return redirect('/')
    context = {'form':form}
    return render(request, 'accounts/order_form.html', context)
  • Related