I am trying to add a set of inline forms, but when I try to save the information of the forms it throws me this error
views.py
The intention is to create more orders for a particular client, for that reason I focus on the "createOrder" function to achieve it.
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import *
from django.forms import inlineformset_factory
from .forms import OrderForm, CustomerForm
# Create your views here.
def home(request):
orders_value = Order.objects.all()
customer_value = Customer.objects.all()
total_orders_value = orders_value.count()
total_customers_value = customer_value.count()
pending_value = orders_value.filter(status='Pending').count()
delivered_value = orders_value.filter(status='Delivered').count()
context = {'orders_key': orders_value, 'customer_key': customer_value,
'total_orders_key':total_orders_value, 'pending_key': pending_value,
'delivered_key': delivered_value}
return render (request, 'accounts/dashboard.html', context)
def products(request):
products_value = Product.objects.all()
return render (request, 'accounts/products.html', {'products_key': products_value})
def customer(request, pk_test):
customer_value = Customer.objects.get(id=pk_test)
orders_value = customer_value.order_set.all()
orders_value_count = orders_value.count()
context = {'customer_key':customer_value, 'orders_key': orders_value, 'orders_key_count': orders_value_count}
return render (request, 'accounts/customer.html', context)
def createOrder(request, pk):
OrderFormSet= inlineformset_factory(Customer, Order, fields=('product', 'status'))
customer = Customer.objects.get(id=pk)
form_set_value= OrderFormSet(instance=customer)
if request.method == 'POST':
form_set_value= OrderFormSet(request, instance=customer)
if form_set_value.is_valid:
form_set_value.save()
return redirect('/')
context = {'form_set_key':form_set_value}
return render(request, 'accounts/order_form.html', context)
order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<form action="" method="POST">
{% csrf_token %}
{{ form_set_key.management_form }}
{% for form in form_set_key %}
{{form}}
<hr>
{% endfor %}
<input type="submit" name="Submit">
</form>
{% endblock %}
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('products/', views.products, name="products"),
path('customer/<int:pk_test>/', views.customer, name="customer"),
path('create_order/<int:pk>', views.createOrder, name='create_order'),
path('update_order/<int:pk>', views.updateOrder, name='update_order'),
path('delete_order/<int:pk>', views.deleteOrder, name='delete_order'),
path('create_customer/', views.createCustomer, name='create_customer'),
]
forms.py
from django.forms import ModelForm, fields
from .models import Order, Customer
class OrderForm(ModelForm):
class Meta:
model = Order
# fields = ['customer', 'product']
fields = '__all__'
class CustomerForm(ModelForm):
class Meta:
model = Customer
fields = '__all__'
models.py
from django.db import models
from django.db.models.deletion import SET_NULL
class Customer(models.Model):
name = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
data_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.name
class Tag(models.Model):
name = models.CharField(max_length=200, null=True)
def __str__(self):
return self.name
class Product(models.Model):
CATEGORY = (
('Indoor', 'Indoor'),
('Out Door', 'Out Door'),
)
name = models.CharField(max_length=200, null=True)
prince = models.FloatField(null=True)
category = models.CharField(max_length=200, null=True, choices=CATEGORY)
description = models.CharField(max_length=200, null=True, blank=True)
data_created = models.DateTimeField(auto_now_add=True, null=True)
tags = models.ManyToManyField(Tag)
def __str__(self):
return self.name
class Order(models.Model):
STATUS = (
('Pending', 'Pending'),
('Out for delivery', 'Out for delivery'),
('Delivered', 'Delivered'),
)
customer = models.ForeignKey(Customer, null=True, on_delete=SET_NULL)
product = models.ForeignKey(Product, null=True, on_delete=SET_NULL)
status = models.CharField(max_length=200, null=True, choices=STATUS)
data_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.product.name
Traceback
Traceback (most recent call last):
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\le\Desktop\django-course\Django(02-09-21)\crm1\accounts\views.py", line 47, in createOrder
form_set_value.save()
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\forms\models.py", line 681, in save
return self.save_existing_objects(commit) self.save_new_objects(commit)
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\forms\models.py", line 787, in save_existing_objects
if not self.initial_forms:
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\forms\formsets.py", line 200, in initial_forms
return self.forms[:self.initial_form_count()]
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\forms\formsets.py", line 157, in forms
for i in range(self.total_form_count())
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\forms\formsets.py", line 130, in total_form_count
return min(self.management_form.cleaned_data[TOTAL_FORM_COUNT], self.absolute_max)
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\forms\formsets.py", line 113, in management_form
form.full_clean()
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\forms\forms.py", line 372, in full_clean
self._clean_fields()
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\forms\forms.py", line 384, in _clean_fields
value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\forms\widgets.py", line 263, in value_from_datadict
return data.get(name)
Exception Type: AttributeError at /create_order/1
Exception Value: 'WSGIRequest' object has no attribute 'get'
I think it has to do with the way the information is managed from the template, but I'm not really sure. Can someone help me?
CodePudding user response:
Change:
OrderFormSet(request, instance=customer)
to:
OrderFormSet(request.POST, instance=customer)
The formset requires the post data, not the request object.