简体   繁体   English

django:在模板 (pk) 中引用模型主键的问题

[英]django: problems refering to model primary key in templates (pk)

I am trying to pass the primary keys of a model through various templates and it seems like refering to model primary key as pk does not work.我试图通过各种模板传递模型的主键,似乎将模型主键称为pk不起作用。 After reading the doc, it seems that the primary key of a model can always be refered as pk.阅读文档后,似乎模型的主键总是可以称为pk。

Here is how I set things up:这是我如何设置:

model.py模型.py

class Products(models.Model):
   
    ProductName = models.CharField(max_length=100, primary_key=True)
    ProductUnit = models.CharField(max_length=100, default="NA")
    ProductCategory = models.CharField(max_length=100)
    ProductTagNumber = models.IntegerField(max_length=100)
    StockOnHand = models.FloatField(max_length=100)

views.py视图.py

def ProductsView(request):
     queryset = Products.objects.all()
     products_list = list(queryset)
     request.session['context'] = products_list
     
     return render(request, 'inventory.html', {'products_list':products_list})
                                               

def UpdateProductView(request,pk):
     
   
     Product = get_object_or_404(Products, pk=pk)
   
     if request.method == 'POST':
          form = UpdateProductForm(request.POST, instance = Product)
          if form.is_valid():
               form.save()
            
          Name = form.cleaned_data.get('ProductName')
          Category = form.cleaned_data.get('ProductCategory')
          OH = form.cleaned_data.get('StockOnHand')
          
          update1 = Products.objects.filter(pk = pk).update(ProductName = Name)
          update2 = Products.objects.filter(pk = pk).update(ProductCategory = Category)
          update3 = Products.objects.filter(pk = pk).update(StockOnHand = OH)
          messages.success(request, "Changed in Product successfully recorded")
          return redirect('https://www.allelegroup.exostock.net/inventory.html')
     else:
          form = UpdateProductForm(initial = {
            'Name' : Products.ProductName,
            'Category' : Products.ProductCategory,
            'OH' : Products.StockOnHand}, instance =Product)
                                 
          return render(request, 'update_product.html', {'form' : form})                       
            

urls.py网址.py

path('inventory.html', ProductsView, name="inventory"),
path('update_product/<int:pk>', UpdateProductView, name="update_product"),

inventory.html库存.html

 <tbody style="background-color: white">
                    {% for Product in products_list %}
                    <tr>
                  
                        
                        <td>{{ Product.pk }}</td>
                        <td>{{ Product.ProductCategory }}</td>
                        <td>{{ Product.ProductTagNumber }}</td>
                        <td>{{ Product.StockOnHand }}</td>
                     
                      <td>
                       <div class="dropdown open">
                         <a href="#!" class="px-2" id="triggerId1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                          <i class="fa fa-ellipsis-v">
                        
                             </i>
                        </a>
                        <div class="dropdown-menu" aria-labelledby="triggerId1" x-placement="bottom-start" style="position: absolute; transform:translate3d(17px,21px,0px); top: 0px; left:0px;will-change: transform;">
                         <a class="dropdown-item" href="{% url 'update_product' pk=Product.pk %}">
                          <i class="fa fa-pencil mr-1"></i>
                          Edit
                         </a>

At first, the primary key of the model was an ``AutoFilled``` field and the above code was working just fine.起初,模型的主键是一个“AutoFilled”字段,上面的代码运行得很好。 Now that I changed the pk, it is not working, and I cannot find a way to get it work.现在我更改了 pk,它不起作用,我找不到让它工作的方法。

the error that gets output is the following one:获取输出的错误如下:

Reverse for 'update_product' with keyword arguments '{'pk': 'Biomass'}' not found. 1 pattern(s) tried: ['update_product\\/(?P<pk>[0-9]+)$']

I am wondering if someone can spot where i messed up or if I am miss understanding the documentation about pk我想知道是否有人可以发现我搞砸的地方,或者我是否想念有关 pk 的文档

Using pk is the correct method to get a primary key.使用pk是获取主键的正确方法。 The issue is in the URLs.问题出在 URL 中。 Since your Products.pk is a CharField , you have to use a correct converter ( <str:pk> ).由于您的 Products.pk 是CharField ,您必须使用正确的转换器( <str:pk> )。

path('update_product/<str:pk>', UpdateProductView, name="update_product")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM