Django表单,有两个模型

2024-10-03 17:19:06 发布

您现在位置:Python中文网/ 问答频道 /正文

现在我想创建一个表单,在这个表单中我可以编辑两个模型(我想显示带有产品的购物车,并且可以编辑来自这个购物车的每个产品的价格)。我使用了inlineformset_factory,但它显示错误。我第一次用这种方法,所以我不知道我必须改变什么。在

'shop.Product' has no ForeignKey to 'shop.Cart'.

在模型.py在

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.IntegerField(default='0')

    def __unicode__(self):
        return u"{}({})".format(self.name, self.price)

class Cart(models.Model):
    product = models.ManyToManyField(Product)
    name = models.CharField(max_length=50)

    def __unicode__(self):
        return self.name

在表单.py在

^{pr2}$

在视图.py在

def cart_new(request):
    if request.method == "POST":
        form = CartForm(request.POST)
        if form.is_valid():
            cart = form.save(commit=False)
            cart.save()
            form.save_m2m()
            ingredient_formset = IngredientFormSet(request.POST)
            if ingredient_formset.is_valid():
                ingredient = formset.save(commit=False)
                ingredient_formset.save()
                return redirect('shop.views.cart_detail', pk=cart.pk)
    else:
        form = CartForm()
    return render(request, 'shop/cart_edit.html', {'form': form})

错误:

    Traceback:
File "C:\Users\znawca\myapp\venv\lib\site-packages\django\core\handlers\base.py" in get_response
  119.                 resolver_product = resolver.resolve(request.path_info)
File "C:\Users\znawca\myapp\venv\lib\site-packages\django\core\urlresolvers.py" in resolve
  366.             for pattern in self.url_patterns:
File "C:\Users\znawca\myapp\venv\lib\site-packages\django\core\urlresolvers.py" in url_patterns
  402.         patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\znawca\myapp\venv\lib\site-packages\django\core\urlresolvers.py" in urlconf_module
  396.             self._urlconf_module = import_module(self.urlconf_name)
File "D:\Python27\Lib\importlib\__init__.py" in import_module
  37.     __import__(name)
File "C:\Users\znawca\myapp\league\league\urls.py" in <module>
  6.     url(r'', include('shop.urls')),
File "C:\Users\znawca\myapp\venv\lib\site-packages\django\conf\urls\__init__.py" in include
  33.         urlconf_module = import_module(urlconf_module)
File "D:\Python27\Lib\importlib\__init__.py" in import_module
  37.     __import__(name)
File "C:\Users\znawca\myapp\league\shop\urls.py" in <module>
  2. from . import views
File "C:\Users\znawca\myapp\league\shop\views.py" in <module>
  2. from .forms import *
File "C:\Users\znawca\myapp\league\shop\forms.py" in <module>
  19. IngredientFormSet = inlineformset_factory(Cart, Product)
File "C:\Users\znawca\myapp\venv\lib\site-packages\django\forms\models.py" in inlineformset_factory
  1020.     fk = _get_foreign_key(parent_model, model, fk_name=fk_name)
File "C:\Users\znawca\myapp\venv\lib\site-packages\django\forms\models.py" in _get_foreign_key
  992.                     parent_model._meta.object_name,

Exception Type: ValueError at /
Exception Value: 'shop.Product' has no ForeignKey to 'shop.Cart'.

Tags: nameinpyimportselfformvenvmodels
1条回答
网友
1楼 · 发布于 2024-10-03 17:19:06

正如您在documentation中发现的那样,内联表单集只适用于外键,而不适用于M2M字段。您必须手动构建自己的表单集。在

你可以这样做:

# In your view:
IngredientFormSet = modelformset_factory(Product)
ingredient_formset = IngredientFormSet(
    request.POST, request.FILES,
    queryset=cart.product.all()
)

你还需要调整实际的节省,把配料附加到他们的购物车上。在

^{pr2}$

相关问题 更多 >