I am trying to create an update view that allows users to update their data. I am trying to access the data by using primary keys. My problem is that i do not know the syntax to implement it.
views.py
def updatedetails(request, pk):
detail = Detail.objects.get(id=pk)
form = Details(instance=detail)
if request.method == "POST":
form = Details(request.POST, instance=detail)
if form.is_valid():
form.save()
return redirect(success)
return render(request, "details.html", {"form":form})
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("details/", views.details, name="details"),
path("success/", views.success, name="success"),
path("edit/<str:pk>/", views.updatedetails, name="updatedetails"),
]
my html template
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Success</title>
</head>
<body>
<h1>Thank You for Filling Out the Form</h1>
<p><a href="/edit/{{request.detail.id}}/">Click Here To Edit</a></p>
</body>
</html>
So what I am trying to figure out is how to call the primary key in my template.
CodePudding user response:
Try using
href="{% url 'updatedetails' pk=request.detail.id %}"
Let me know if that works. This will look for the path name updatedetails located in your urlpatterns and provide the id as the key. I'm somewhat new at this also, so i'm hoping this helps and is correct.
CodePudding user response:
At first, I'd recommend you to change <str:pk>
to <int:pk>
in updatedetails
path so urls.py should be:
from django.urls import path
from . import views
urlpatterns = [
path("details/", views.details, name="details"),
path("success/", views.success, name="success"),
path("edit/<int:pk>/", views.updatedetails, name="updatedetails"),
]
Secondly, I'd recommend you to use get_object_or_404()
instead of get()
and also if you see it correctly you are also missing ""
in redirect(success)
that should be redirect("success")
so views.py should be:
from django.shortcuts import get_object_or_404
def updatedetails(request, pk):
detail = get_object_or_404(Detail,id=pk)
form = Details(instance=detail)
if request.method == "POST":
form = Details(request.POST, instance=detail)
if form.is_valid():
form.save()
return redirect("success")
return render(request, "details.html", {"form":form})
Then, in the template you can use url tags
and pass pk
to updatedetails
view as:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Success</title>
</head>
<body>
<h1>Thank You for Filling Out the Form</h1>
<p><a href="{% url 'updatedetails' request.detail.id %}">Click Here To Edit</a></p>
</body>
</html>