'I cant update an object in Django?
Ive created a Django application where you add jobs and Im fully able to add new jobs but I can update them for some reason? The update feature isn't working and I don't know why??
<form action='/update_job/{{job.id}}' method="POST">
<ul>
{% for message in messages %}
<li>{{message}}</li>
{% endfor %}
</ul>
{% csrf_token %}
Title: <input type='text' value="{{job.job}}" name='job'>
Description: <input type='text' value="{{job.description}}" name='description'>
Location: <input type='text' value="{{job.location}}" name='location'>
<input type='submit'>
</form>
def update_job(request, job_id):
errors = Job.objects.job_validator(request.POST, job_id)
if job.creator.id != request.session['user_id']:
messages.error(request, "This isn't yours to edit!")
if len(errors):
for key, value in errors.items():
messages.error(request, value)
return redirect(f'/edit_job/{job_id}')
job = Job.objects.get(id=job_id)
job.job = request.POST['job']
job.description = request.POST['description']
job.location = request.POST['location']
job.save()
return redirect('/main')
Page not found (404)
Request Method: POST
Request URL: http://localhost:8000/update_job/2
Using the URLconf defined in Python_Exam.urls, Django tried these URL patterns, in this order:
register
login
logout
main
job_link
job/create
jobs/<int:job_id>/view
jobs/<int:job_id>/delete
jobs/<int:job_id>/edit
jobs/<int:job_id>/update_job
The current path, update_job/2, didn't match any of these.
Solution 1:[1]
You swapped the primary key and the update_job, it is:
<form action="/jobs/{{ job.id }}/update_job" method="POST">
…
</form>
You however might want to use the {% url … %} template tag [Django-doc] to determine the URL.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
