Issue
In the update template my form isnt getting prepopulated however the functionality of updating is working fine. the form stays empty when i am trying to parse an instance of a specific ID
My view.py :
def update_component(request, pk):
component = Component.objects.all()
component_id = Component.objects.get(id=pk)
form = ComponentModelForm(instance=component_id)
if request.method == 'POST':
form = ComponentModelForm(request.POST, instance=component_id)
if form.is_valid():
form.save()
return HttpResponseRedirect(request.path_info)
context = {
'components': component,
'form': ComponentModelForm(),
'component_id':component_id,
}
return render(request, 'update_component.html', context)
The form in template :
<div>
{% load widget_tweaks %}
<form class="component-form-flex" method='POST' action=''>
{% csrf_token %}
<div style="width:50%;" >
<br>
<span class="component-label-text">Name</span>
{% render_field form.name class="component-form" %}
<span class="component-label-text">Manufacturer</span>
{% render_field form.manufacturer class="component-form" %}
<span class="component-label-text">Model</span>
{% render_field form.model class="component-form" %}
<span class="component-label-text">Serial Number</span>
{% render_field form.serial_number class="component-form" %}
<span class="component-label-text">Price</span>
{% render_field form.price class="component-form" %}
<span class="component-label-text">Note</span>
{% render_field form.note class="component-form" %}
{% render_field form.parent class="component-form" %}
<input type="submit" class="form-submit-button" value='Update Component' />
</div>
<div>
<img class="maintenance-nav-list-img" src="{{ component_id.image.url }}" />
{% render_field form.image %}
</div>
</form>
</div>
urls.py :
from django.urls import path
from . import views
appname = 'maintenance'
urlpatterns = [
path('', views.index , name='maintenance'),
path('<int:pk>/update/', views.update_component , name='update_component'),
]
Solution
This is just a typo, instead of
context = {
'components': component,
'form': ComponentModelForm(),
'component_id':component_id,
}
it should be
context = {
'components': component,
'form': form, # <--- HERE !!!!
'component_id':component_id,
}
Answered By - dani herrera
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.