Barly Espinal
Barly Espinal

Reputation: 105

Django url dynamic link

im using vuejs in django and i have this code

<form method="POST" :action="edit ? '{% url 'productoEdit' pk=request.path|slice:'19:21' %}' : '{% url 'productoCrud' %}'" enctype="multipart/form-data">

if the variabble edit is true action will be {% url 'productoEdit' pk=request.path|slice:'19:21' %} if is false {% url 'productoCrud' %}

the problem is that django gives me an error:
Reverse for 'productoEdit' with keyword arguments '{'pk': ''}' not found. 2 pattern(s) tried: ['user/productoEdit$', 'user/productoEdit/(?P<pk>[^/]+)$']

this is my urls.py

path('productoEdit/<str:pk>', views.productoEdit, name="productoEdit"),
path('productoEdit', views.productoEdit, name="productoEdit")

as you can see the path productoEdit has 2 views, one with parameters and other without parameters.

this is my productoEdit in views.py

def productoEdit(request, pk=''): 
  producto = Producto.objects.get(id=pk)
  form = CreateProductForm(instance=producto)
  if request.method == 'POST':
    form = CreateProductForm(request.POST, instance=producto)
    if form.is_valid():
      form.save()
      redirect('productoCrud')

  return render(request, 'productoCrud.html', {'form': form})

the problem ocurred when request.path is an empty string pk=''.

i tried using a ternay operator like this: pk=request.path|slice:'19:21' ? request.path|slice:'19:21' : None

or pk=request.path|slice:'19:21'|yesno:'request.path|slice:'19:21',None'

Django doesnt like my solutions xD, how can i resolve this problem?? thx so much for your help

Problem solved* i did what Abdul Aziz Barkat suggested

{% if request.path|slice:'19:21' %}
     <form method="POST" action="{% url 'productoEdit' pk=request.path|slice:'19:21' %}" enctype="multipart/form-data">
{% else %}
     <form method="POST" action="{% url 'productoCrud' %}'" enctype="multipart/form-data">
{% endif %}

i was using the js approach, now the error is gone, thx so much everyone

Upvotes: 0

Views: 210

Answers (1)

Yousef Alm
Yousef Alm

Reputation: 238

Add if statement to check if PK exists before reversing a url.

Upvotes: 1

Related Questions