Assuming OpsForm
is a ModelForm
and not a Form
, I suspect the problem is how you're fetching instance
. Currently it's being set to a QuerySet
. You want the actual instance:
from django.shortcuts import get_object_or_404
instance = get_object_or_404(Ops, id=ops_id)
If you'd prefer to do your own error handling if the instance doesn't exist then:
instance = Ops.objects.filter(id=ops_id).first()
If it doesn't exist, instance
will be set to None
.
Edit:
The other thing you should strongly consider doing is to move the id of the Ops
instance into the url, then the request body can just be the form and doesn't have to be wrapped in another object. The documentation covers urls pretty well.
This would change your view to:
from django.http.response import HttpResponseForbidden
def update_ops(request, ops_id):
instance = get_object_or_404(Ops, ops_id)
if request.method != "POST":
raise HttpResponseForbidden
form = OpsForm(request.POST, instance=instance)
if form.is_valid():
form.save()
print('saved bro!')
return HttpResponseRedirect('/ops/')
else:
print('form is not valid')
return render(request, 'ops_form.html', {'form': form})
urls.py
from django.urls import path
urlpatterns = [
path('update_ops_form/<int:ops_id>', views.update_ops, name='update_ops_form')
]
template
<form action="{% url 'update_ops_form' ops_id=ops.id %}" id="post-form" method="post">
script:
<script>
$("#post-form").submit(function (event) {
event.preventDefault(); //prevent default action
var post_url = $(this).attr("action");
console.log(post_url)//get form action url
var request_method = $(this).attr("method"); //get form GET/POST
console.log(form_data)
$.ajax({
url: post_url,
type: request_method,
data: $(this).serialize()
})
});
</script>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…