#django #django-models #django-views #django-forms #django-templates
Вопрос:
Я пытаюсь добавить набор встроенных форм, но когда я пытаюсь сохранить информацию о формах, она выдает мне эту ошибку
views.py
Цель состоит в том, чтобы создать больше заказов для конкретного клиента, по этой причине я сосредотачиваюсь на функции «Создать заказ» для ее достижения.
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 (most recent call last):
File "C:Usersleanaconda3envsmyenvlibsite-packagesdjangocorehandlersexception.py", line 47, in inner
response = get_response(request)
File "C:Usersleanaconda3envsmyenvlibsite-packagesdjangocorehandlersbase.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:UsersleDesktopdjango-courseDjango(02-09-21)crm1accountsviews.py", line 47, in createOrder
form_set_value.save()
File "C:Usersleanaconda3envsmyenvlibsite-packagesdjangoformsmodels.py", line 681, in save
return self.save_existing_objects(commit) self.save_new_objects(commit)
File "C:Usersleanaconda3envsmyenvlibsite-packagesdjangoformsmodels.py", line 787, in save_existing_objects
if not self.initial_forms:
File "C:Usersleanaconda3envsmyenvlibsite-packagesdjangoformsformsets.py", line 200, in initial_forms
return self.forms[:self.initial_form_count()]
File "C:Usersleanaconda3envsmyenvlibsite-packagesdjangoutilsfunctional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:Usersleanaconda3envsmyenvlibsite-packagesdjangoformsformsets.py", line 157, in forms
for i in range(self.total_form_count())
File "C:Usersleanaconda3envsmyenvlibsite-packagesdjangoformsformsets.py", line 130, in total_form_count
return min(self.management_form.cleaned_data[TOTAL_FORM_COUNT], self.absolute_max)
File "C:Usersleanaconda3envsmyenvlibsite-packagesdjangoutilsfunctional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:Usersleanaconda3envsmyenvlibsite-packagesdjangoformsformsets.py", line 113, in management_form
form.full_clean()
File "C:Usersleanaconda3envsmyenvlibsite-packagesdjangoformsforms.py", line 372, in full_clean
self._clean_fields()
File "C:Usersleanaconda3envsmyenvlibsite-packagesdjangoformsforms.py", line 384, in _clean_fields
value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
File "C:Usersleanaconda3envsmyenvlibsite-packagesdjangoformswidgets.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'
Я думаю, что это связано с тем, как информация управляется из шаблона, но я не совсем уверен. Кто-нибудь может мне помочь?
Комментарии:
1. Можете ли вы добавить полную обратную трассировку ошибок?
2. Не могли бы вы, пожалуйста, показать свой forms.py
3. Я просто обновил сообщение, добавил трассировку и forms.py @amadousow
Ответ №1:
Изменить:
OrderFormSet(request, instance=customer)
Для:
OrderFormSet(request.POST, instance=customer)
Набор форм требует данных post, а не объекта запроса.
Комментарии:
1. Спасибо за вашу помощь..!!!