Skip to content
Advertisement

How can pass primary key to url Django

I have basically 3 issues

  1. I am trying to pass the primary key of vendor in url after creating it, but when i go the vendor page it shows the error ‘ Reverse for ‘vendorCategory’ with arguments ‘(”,)’ not found. 1 pattern(s) tried: [‘vendorCategory/(?P<vendor_id>[0-9]+)/$’] ‘

  2. In Vendor Category when i am trying to store multiple products against the specific vendor it show the error ‘Field id int but You got [’12’, ’11’] ‘

  3. in Vendor Category template when i select any category it just show the last category which i added

View.py

class Vendor(TemplateView):

     template_name = 'purchase/vendor.html'

     def get(self, request, *args, **kwargs):
         return render(request, self.template_name)

     def post(self, request, vendor_id):
        try:
           data = self.request.POST.get
           vendor = VendorModel(
                name=data('name'),
                email=data('email'),
                Contact_No=data('Contact_No'),
                address=data('address')
           )
           vendorId = vendor.objects.get(pk=vendor_id)
           vendor.save()
           
           return redirect('vendorCategory', args={'vendor': vendorId})
        except Exception as e:
           return HttpResponse('failed{}'.format(e))


class Vendor_Category(TemplateView):

    template_name = 'purchase/vendorCategory.html'

    def get(self, request, vendor_id=None, *args, **kwargs):
        categories = CategoryModel.objects.all()
        categoryId = self.request.GET.get('SelectCategory')
        products = ProductModel.objects.filter(category_id=categoryId)
        vendor= VendorModel.objects.get(id=vendor_id)
        args = {'categories': categories, 'products': products, 'selectedCategory':  categoryId, 'vendor': vendor}
        return render(request, self.template_name, args)

   def post(self, request):

       categoryobj = self.request.GET.get('SelectCategory')
       productobj = self.request.POST.getlist('ProductSelect')

       try:
          vendor = VendorCategory(
              vendor_id=self.request.vendor_id,
              category_id=categoryobj,
              product_id=productobj

          )
          vendor.save()
          return redirect('menu')
       except Exception as e:
           return HttpResponse('failed{}'.format(e))

Urls.py

urlpatterns = [

   path('vendorCategory/<int:vendor_id>/', Vendor_Category.as_view(), name='vendorCategory')
   path('vendor', Vendor.as_view(), name='vendor'),
]

Template

VendoreCategory.html

   {% extends 'auth/home.html' %}

  {% block content %}

<form method="get">
{% csrf_token %}
    <label>
        <select name="SelectCategory" >
        <option disabled="disabled" value="True" selected="{{ selectedCategory|yesno:"yes, no"|safe }}"> Select Category</option>
            {% for category in categories %}
            <option value="{{ category.id }}" selected="{% if category.id == selectedCategory %} {% endif %}">
                {{ category.name }}
            </option>
            {% endfor %}
        </select>
    </label>

    <input type="submit" value="Select">
</form>
<form method="post">
<input type="hidden" value={{  selectedCateogry }} name="ProductSelect">
{% csrf_token %}
<label>
    {% for product in products%}
    <input type="checkbox" name="ProductSelect" value="{{ product.id }}" >{{ product.name }}
    {% endfor %}
    </label>
<input type="submit" value="Select">


</form>

{% endblock %}

Vendor.html

   {% extends 'auth/home.html' %}

{% block content %}
<form method="post">
 {% csrf_token %}
    <label for="name">Name
        <input type="text" name="name" id="name" placeholder="Enter vendor name">
    </label>
    <label for="email">Email
        <input type="email" name="email" id="email" placeholder="Enter vendor's email address">
    </label>
    <label for="Contact_No">Contact no
        <input type="number" name="Contact_No" id="Contact_No" placeholder="Enter vendor contact no">
    </label>
    <label for="address">Address
        <input type="text" name="address" id="address" placeholder="Enter vendor address">
    </label>
    <button type="submit">Submit </button>
</form>
 {% endblock %}

Advertisement

Answer

I think your problem is that you’re extending a TemplateView and then treating it as if it’s a View.

If you override a TemplateView you should read the kwargs in the get_context_data method. If you like a more “hands-on approach” (as myself) then get rid of the TemplateView and extend a normal View, and then override the get and post methods (as you’re doing right now).

from django.views import View

Edit: I took a second look

Error 1:

Maybe try this?

def get(self, request, *args, **kwargs):
    categories = CategoryModel.objects.all()
    categoryId = self.request.GET.get('SelectCategory')
    products = ProductModel.objects.filter(category_id=categoryId)
    vendor= VendorModel.objects.get(id=self.kwargs['vendor_id'])
    args = {'categories': categories, 'products': products, 'selectedCategory':  categoryId, 'vendor': vendor}
    return render(request, self.template_name, args)

In the URL you are asking for a kwarg (vendor_id) but then i dont see you using it anywhere. Also that error will appear everytime you go to that path and fail to specify the requested kwarg. So when you try to run the VendorCategory view be sure your url has a /1/ or something at the end.

Error 2:

You are trying to assign a list to an int variable. No wonder it doesn’t work. My advice is to add:

print(self.request.POST.getlist('ProductSelect'))

in your post method and see what comes out. Then you can devise a way to unpack it and store it. I mean, we already know it’s a list.. so you clearly cant assign multiple ids to the single object you’re creating. You should be creating a vendor first and then have a product creating loop to add products to that vendor. Something like this might work:

categoryobj = self.request.GET.get('SelectCategory')
productobj = self.request.POST.getlist('ProductSelect')

try:
  vendor = VendorCategory.objects.create(
      vendor_id=self.request.vendor_id,
      category_id=categoryobj,
  )
  vendor.save()
  for product_id in productobj:
    product = ProductModel.objects.get(id=product_id)
    product.vendormodel = vendor
    product.save()

Now.. I think you got a mistake there where you write vendor = VendorCategory( or at least i’ve never seen this syntax and I don’t know what it’s supposed to accomplish. In my version i replaced it with VendorCategory.objects.create because that’s what i assumed you were trying to do.

Error 3:

In the template you’re using a |yesno filter with an int value. Are you trying to understand whether there’s an id at all?

You’re running a for cycle in which you possibly will select multiple values, in this case the item should have a “multiple” in it. <select name="asdsad" multiple>

I find it odd that you have a <label> wrapping the entire <select>. The <label> should have for="field_id" and that’s it. Except really special cases.

Last but not least, you have a typo:

<input type="hidden" value={{  selectedCateogry }} name="ProductSelect">
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement