so this is the view :
def update_ticket(response,ticket_title):
ticket = get_object_or_404(TicketsModel, title=ticket_title)
ticket_form = AddTicketsForm(response.POST or None,instance=ticket,assigned_by=response.user)
if 'return' in response.POST:
return redirect('home', type_user=response.session.get('type_user'))
if ticket_form.is_valid():
ticket.ticket_creation_date = datetime.now()
ticket_form.save()
return redirect('home', type_user=response.session.get('type_user'))
return render(response, "template/testapp/update_ticket.html", {'ticket_title': ticket.title, 'ticket_form': ticket_form})
the problem is , when i render the form , i dont see the data inside of the inputs , but if i delete the 'response.POST' in the AddTicketsForm() , i can see the data but i cant update nothing
here is the html content
<h2>Update Ticket</h2>
<form action="{% url 'update_ticket' ticket_title=ticket_title %}" method="post">
{% csrf_token %}
{{ ticket_form.as_p }}
<button type="submit" name="save" id="regDirect" >Save</button>
<button type="submit" name="return">Return</button>
<form/>
To display the current data in the form fields while also being able to update the data, you should use the request.method
property to conditionally include request.POST
when the form is being submitted, and exclude it when rendering the form for the first time.
Try this view:
def update_ticket(response, ticket_title):
ticket = get_object_or_404(TicketsModel, title=ticket_title)
ticket_form = AddTicketsForm(instance=ticket, assigned_by=response.user, **response.POST** if response.method == 'POST' else None)
if 'return' in response.POST:
return redirect('home', type_user=response.session.get('type_user'))
if ticket_form.is_valid():
ticket.ticket_creation_date = datetime.now()
ticket_form.save()
return redirect('home', type_user=response.session.get('type_user'))
return render(response, "template/testapp/update_ticket.html", {'ticket_title': ticket.title, 'ticket_form': ticket_form})
So now, your AddTicketsForm
will have the request.POST
data when the form is submitted, and it will not include request.POST
when rendering the form for the first time, which allows you to see the data inside the inputs.
When the form is submitted, the request.POST
will be included, and the is_valid()
method will handle the update accordingly.