Only part of form is saved upon validation error - python

I am trying to eliminate the loss of data upon page refresh when validation fails. When the form is refreshed after validation error, all the fields are empty, except for the fields in the that caused the error. How can I have the page refresh, display the validation errors and still have all the fields in all the divs populated?
Thanks in advance!
My code is displayed below:
views.py
class CreateListingView(CreateView):
template_name = 'listing/listing.html'
model = Listing
form_class = ListingForm
# success_url = '/add-listing/'
def get_success_url(self):
return reverse('store') + "?success=true"
def dispatch(self, request, *args, **kwargs):
if self.request.user.is_authenticated():
if not self.request.user.has_company():
return HttpResponseRedirect(reverse('get_paid'))
elif not self.request.user.has_shipping():
return HttpResponseRedirect(reverse('get_paid'))
elif not self.request.user.has_bank():
return HttpResponseRedirect(reverse('get_paid'))
else:
return super(CreateListingView, self).dispatch(request, *args, **kwargs)
else:
return HttpResponseRedirect(reverse('create_user'))
def get_initial(self):
return {'company_profile': self.request.user.company}
def get_form_kwargs(self):
kwargs = super(CreateListingView, self).get_form_kwargs()
if self.request.method in ('POST', 'PUT'):
kwargs['data']['price'] = kwargs['data']['price'].replace(',','')
return kwargs
forms.py
class ListingForm(forms.ModelForm):
caliber_firearm = forms.CharField(required=False, widget=forms.TextInput(attrs={'class': 'req'}))
caliber_ammo = forms.CharField(required=False)
tags = forms.CharField(required=False)
img_0 = forms.ImageField(required=False, widget=forms.FileInput(attrs={'class': 'image-input'}))
img_1 = forms.ImageField(required=False, widget=forms.FileInput(attrs={'class': 'image-input'}))
img_2 = forms.ImageField(required=False, widget=forms.FileInput(attrs={'class': 'image-input'}))
img_3 = forms.ImageField(required=False, widget=forms.FileInput(attrs={'class': 'image-input'}))
img_4 = forms.ImageField(required=False, widget=forms.FileInput(attrs={'class': 'image-input'}))
class Meta:
model = Listing
exclude = ['copy', 'caliber']
widgets = {
'title': forms.TextInput(attrs={'class': 'title-listing'}),
'listing_type': forms.RadioSelect(),
'upc': forms.TextInput(attrs={'class': 'upc'}),
'category': forms.Select(attrs={'class': 'short-input', 'required': 'True'}),
'price': forms.TextInput(attrs={'class': 'price dollar req'}),
'list_price': forms.TextInput(attrs={'class': 'list_price_input'}),
'quantity': forms.TextInput(attrs={'class': 'qty req'}),
'description': forms.Textarea(attrs={'class': 'description req'}),
'estimated_ship_days': forms.TextInput(attrs={'class': 'qty req', 'placeholder': 'Days'}),
'capacity': forms.TextInput(attrs={'class': 'req'}),
'weight_pounds': forms.TextInput(attrs={'class': 'weight req', 'placeholder': 'Pounds'}),
'weight_ounces': forms.TextInput(attrs={'class': 'weight', 'placeholder': 'Ounces'}),
'barrel_length': forms.TextInput(attrs={'class': 'req', 'placeholder': 'Inches'}),
'overall_length': forms.TextInput(attrs={'class': 'req', 'placeholder': 'Inches'}),
'company_profile': forms.HiddenInput(),
'shipping_zip_code': forms.TextInput(attrs={'placeholder': 'Your shipping zip code'}),
}
error_messages = empty_errors
def clean(self):
listing_type = self.cleaned_data.get('listing_type')
if self.cleaned_data.get('img_0') is None and \
self.cleaned_data.get('img_1') is None and \
self.cleaned_data.get('img_2') is None and \
self.cleaned_data.get('img_3') is None and \
self.cleaned_data.get('img_4') is None:
self.add_error('img_0', 'One photo must be uploaded')
if listing_type == 'Firearm':
if self.cleaned_data.get('caliber_firearm', None) is None:
self.add_error('caliber_firearm', 'This field is required')
else:
self.cleaned_data['caliber'] = self.cleaned_data.get('caliber_firearm')
if self.cleaned_data.get('capacity', None) is None:
self.add_error('capacity', 'This field is required')
if self.cleaned_data.get('weight_pounds', None) is None:
self.add_error('weight_pounds', 'This field is required')
if self.cleaned_data.get('weight_ounces', None) is None:
self.add_error('weight_ounces', 'This field is required')
if self.cleaned_data.get('barrel_length', None) is None:
self.add_error('barrel_length', 'This field is required')
if self.cleaned_data.get('overall_length', None) is None:
self.add_error('overall_length', 'This field is required')
elif listing_type == 'Ammo':
if self.cleaned_data.get('caliber_ammo', None) is not None:
self.cleaned_data['caliber'] = self.cleaned_data.get('caliber_ammo')
if self.cleaned_data.get('shipping_zip_code') is None or \
self.cleaned_data.get('shipping_weight') is None or \
self.cleaned_data.get('shipping_height') is None or \
self.cleaned_data.get('shipping_length') is None or \
self.cleaned_data.get('shipping_width') is None:
self.add_error('shipping_weight', 'Shipping information is not complete')
return self.cleaned_data
Template
{% extends 'base.html' %}
{% load staticfiles %}
{% block head %}
<title>Dealer Direct by FFL Design</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
type="text/css"
href="{% static 'listing/css/listing.css' %}">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'listing/js/listing.js' %}"></script>
<!-- Start of ffldesign Zendesk Widget script -->
<script>/*<![CDATA[*/window.zEmbed||function(e,t){var n,o,d,i,s,a=[],r=document.createElement("iframe");window.zEmbed=function(){a.push(arguments)},window.zE=window.zE||window.zEmbed,r.src="javascript:false",r.title="",r.role="presentation",(r.frameElement||r).style.cssText="display: none",d=document.getElementsByTagName("script"),d=d[d.length-1],d.parentNode.insertBefore(r,d),i=r.contentWindow,s=i.document;try{o=s}catch(c){n=document.domain,r.src='javascript:var d=document.open();d.domain="'+n+'";void(0);',o=s}o.open()._l=function(){var o=this.createElement("script");n&&(this.domain=n),o.id="js-iframe-async",o.src=e,this.t=+new Date,this.zendeskHost=t,this.zEQueue=a,this.body.appendChild(o)},o.write('<body onload="document._l();">'),o.close()}("https://assets.zendesk.com/embeddable_framework/main.js","ffldesign.zendesk.com");/*]]>*/</script>
<!-- End of ffldesign Zendesk Widget script -->
{% endblock %}
{% block body %}
<body>
<div class="listing">
<p class="ffl">Add a new listing</p>
<form action="{% url 'add-listing' %}" method="post" enctype="multipart/form-data">
<div class="errors">{{ form.shipping_weight.errors }}</div>
{% csrf_token %}
<div class="photos">
<p class="ffl-small">Photos</p>
<p class="desc" id="photos-desc">Must add at least one photo.</p>
<ul>
<li id="photo_0">
<div id="input_photo_0">
<img src="{% static 'listing/images/add-photo.png' %}" class="add-photo">
<p><button type="button" class="active-button">Add Photo</button></p>
{{ form.img_0 }}
</div>
<div id="display_photo_0" class="hidden">
<img src="" width="143" height="105" id="img_view_0" class="item-image">
<button type="button" class="remove-zoom active-button magnify"><img src="{% static 'listing/images/zoom.png' %}" width="18" height="18"></button><button type="button" class="remove-zoom active-button delete_photo"><img src="{% static 'listing/images/remove.png' %}"></button>
</div>
</li>
<li id="photo_1">
<div id="input_photo_1">
<img src="{% static 'listing/images/add-photo.png' %}" class="add-photo">
<p><button type="button" class="active-button">Add Photo</button></p>
{{ form.img_1 }}
</div>
<div id="display_photo_1" class="hidden">
<img src="" width="143" height="105" id="img_view_1" class="item-image">
<button type="button" class="remove-zoom active-button magnify"><img src="{% static 'listing/images/zoom.png' %}" width="18" height="18"></button><button type="button" class="remove-zoom active-button delete_photo"><img src="{% static 'listing/images/remove.png' %}"></button>
</div>
</li>
<li id="photo_2">
<div id="input_photo_2">
<img src="{% static 'listing/images/add-photo.png' %}" class="add-photo">
<p><button type="button" class="active-button">Add Photo</button></p>
{{ form.img_2 }}
</div>
<div id="display_photo_2" class="hidden">
<img src="" width="143" height="105" id="img_view_2" class="item-image">
<button type="button" class="remove-zoom active-button magnify"><img src="{% static 'listing/images/zoom.png' %}" width="18" height="18"></button><button type="button" class="remove-zoom active-button delete_photo"><img src="{% static 'listing/images/remove.png' %}"></button>
</div>
</li>
<li id="photo_3">
<div id="input_photo_3">
<img src="{% static 'listing/images/add-photo.png' %}" class="add-photo">
<p><button type="button" class="active-button">Add Photo</button></p>
{{ form.img_3 }}
</div>
<div id="display_photo_3" class="hidden">
<img src="" width="143" height="105" id="img_view_3" class="item-image">
<button type="button" class="remove-zoom active-button magnify"><img src="{% static 'listing/images/zoom.png' %}" width="18" height="18"></button><button type="button" class="remove-zoom active-button delete_photo"><img src="{% static 'listing/images/remove.png' %}"></button>
</div>
</li>
<li id="photo_4">
<div id="input_photo_4">
<img src="{% static 'listing/images/add-photo.png' %}" class="add-photo">
<p><button type="button" class="active-button">Add Photo</button></p>
{{ form.img_4 }}
</div>
<div id="display_photo_4" class="hidden">
<img src="" width="143" height="105" id="img_view_4" class="item-image">
<button type="button" class="remove-zoom active-button magnify"><img src="{% static 'listing/images/zoom.png' %}" width="18" height="18"></button><button type="button" class="remove-zoom active-button delete_photo"><img src="{% static 'listing/images/remove.png' %}"></button>
</div>
</li>
<li class="desc">
For best results, use high quality jpeg or gif files that are at least 570 px wide.
</li>
</ul>
</div>
<div class="select-type">
<p class="ffl-small">Select listing type</p>
{% for radio in form.listing_type %}
{{ radio }}
{% endfor %}
{# <label><input type="radio" name="listing" checked>Firearms</label>#}
{# <label><input type="radio" name="listing">Ammo</label>#}
{# <label><input type="radio" name="listing">Optics</label>#}
{# <label><input type="radio" name="listing">Apparel</label>#}
{# <label><input type="radio" name="listing">Other</label>#}
</div>
<div class="details">
<p class="ffl-small">Listing Details</p>
<p><label for="id_title">Title<span>*</span></label><input type="text" id="id_title" name="title" class="title-listing" required><span class="desc">Describe your item using words and phrases people would use in a search.</span>
<span class="title-error">Error: you cannot use a period in the title name.</span>
</p>
<p><label for="id_upc">UPC</label><input type="text" name="upc" id="id_upc" class="upc" maxlength="12"></p>
<p><label for="id_category">Category<span>*</span></label>
{{form.category}}
</p>
<p>
<label for="id_price">Cost<span>*</span></label><input type="number" name="price" id="id_price" class="price dollar req" min=0 step="0.01">
<span class="list_price_text">List Price:<input type="number" name="list_price" id="id_list_price" class="list_price_input" step="0.01" readonly></span>
<span class="list_price_desc">The "List Price" is automatically calculated with Dealer Direct seller fees. This price is what the dealer will see. The "Cost" field is the amount you will be paid.</span>
</p>
<p><label for="id_quantity">Quantity<span>*</span></label><input type="text" name="quantity" id="id_quantity" class="qty req"></p>
<p><label for="id_description" class="textarea-label">Description<span>*</span></label><textarea name="description" id="id_description" class="description req"></textarea></p>
<p><label for="id_estimated_ship_days">Days to ship:<span>*</span></label><input type="text" name="estimated_ship_days" id="id_estimated_ship_days" class="qty req" placeholder="days"></p>
{% for field in form.hidden_fields %}
{{ field }}
{% endfor %}
</div>
<div class="details ammo type-ammo">
<p class="ffl-small">Ammo Details</p>
<p><label for="id_rounds">Rounds per box</label>{{ form.rounds }}</p>
<p><label for="id_caliber_ammo">Caliber/Gauge</label>{{ form.caliber_ammo }}</p>
<p><label for="id_weight">Weight</label>{{ form.weight }}</p>
<p><label for="id_muzzle_velocity">Muzzle Velocity</label>{{ form.muzzle_velocity }}</p>
<p><label for="id_length">Length</label>{{ form.length }}</p>
<p><label for="id_ammo_type">Type</label>{{ form.ammo_type }}</p>
</div>
<div class="details ammo type-firearm">
<p class="ffl-small">Firearm Details</p>
<p><label for="id_caliber_firearm">Caliber<span>*</span></label>{{ form.caliber_firearm }}</p>
<p><label for="id_capacity">Capacity<span>*</span></label>{{ form.capacity }}</p>
<p><label for="id_weight_pounds">Weight<span>*</span></label>{{ form.weight_pounds }}<label for="id_weight_ounces" class="weight-label"></label>{{ form.weight_ounces }}</p>
<p><label for="id_barrel_length">Barrel Length<span>*</span></label>{{ form.barrel_length }}</p>
<p><label for="id_overall_length">Overall Length<span>*</span></label>{{ form.overall_length }}</p>
<p><label for="id_finish">Finish</label>{{ form.finish }}</p>
</div>
<div class="details optics type-optics">
<p class="ffl-small">Optics Details</p>
<p><label for="id_magnification">Magnification</label><input id="id_magnification" name="magnification" type="text"></p>
<p><label for="id_field_of_view">Field of View</label><input id="id_field_of_view" name="field_of_view" type="text"></p>
<p><label for="id_reticle">Reticle</label><input id="id_reticle" name="reticle" type="text"></p>
<p><label for="id_objective_lens">Objective Lens</label><input id="id_objective_lens" name="objective_lens" type="text"></p>
<p><label for="id_eye_relief">Eye Relief</label><input id="id_eye_relief" name="eye_relief" type="text"></p>
<p><label for="id_max_elevation_adjustment">Max Elevation Adjustment</label><input id="id_max_elevation_adjustment" name="max_elevation_adjustment" type="text"></p>
<p><label for="id_max_windage_adjustment">Max Windage<br/>Adjustment</label><input id="id_max_windage_adjustment" name="max_windage_adjustment" type="text"></p>
<p><label for="id_length_optics">Length</label><input id="id_length_optics" name="length" type="text"></p>
<p><label for="id_weight_optics">Weight</label><input id="id_weight_optics" name="weight" type="text"></p>
<p><label for="id_battery">Battery</label><input id="id_battery" name="battery" type="text"></p>
<p><label for="id_dot_size">DOT Size</label><input id="id_dot_size" name="dot_size" type="text"></p>
<p><label for="id_finish_optics">Finish</label><input id="id_finish_optics" name="finish" type="text"></p>
</div>
<div class="details apparel type-apparel">
<p class="ffl-small">Apparel Details</p>
<p><label for="id_shirt_size">Size</label>
{{ form.shirt_size }}
</p>
<p><label for="id_shirt_color">Color</label><input id="id_shirt_color" name="shirt_color" type="text"></p>
</div>
<div class="search">
<p class="ffl-small">Search Terms</p>
<p class="desc">Help dealers find this product by using accurate and descriptive words or phrases.</p>
<ul class="search-ul">
<li>
<span class="tags"><label for="id_tags">Tags</label></span>
<span class="desc">Optional</span>
</li>
<li>
<label><input type="text" name="tags" id="id_tags" placeholder="example: ar15, iron sights, glock holster, etc" class="tag-input"><span class="desc left">10 left</span></label>
<p class="tags-wrapper">must separate each tag by a comma</p>
<p id="tag-list"></p>
</li>
<li>
<span class="desc">
We highly recommend using all 10 tags for<br />your listing to get
found. Use words you think<br />dealers would use to search for this product.
</span>
</li>
</ul>
</div>
<div class=" details shipping">
<p class="ffl-small">Shipping</p>
<p class="desc">For realistic shipping expectations, please provide accurate product shipping information below.</p>
<div class="errors">{{ form.shipping_zip_code.errors }}{{ form.shipping_weight.errors }}</div>
{% comment %}
<p class="zip"><label for="">Zip Code</label><input name="" type="text" placeholder="Your shipping zip code"></p>
<p class="shipping-weight"><label for="">Weight</label><input name="" type="text"><label for=""></label><input name="" type="text"></p>
<p class="dimensions"><label for="">Dimensions</label><input name="" type="text"><label for=""></label><input name="" type="text"><label for=""></label><input name="" type="text"></p>
{% endcomment %}
<p class="zip">
<label for="id_shipping_zip_code">Zip Code</label>
{{form.shipping_zip_code}}
</p>
<p class="shipping-weight">
<label for="id_shipping_weight">Weight</label>
{{form.shipping_weight}}
</p>
<p class="dimensions">
<label for="">Dimensions</label>
{{form.shipping_length}}
<label for=""></label>
{{form.shipping_width}}
<label for=""></label>
{{form.shipping_height}}
</p>
</div>
<button class="submit-btn active-button">Submit Listing</button>
</form>
<div class="wrapper">
<div class="">
<button class="active-button">Close</button>
<img src="{% static 'listing/images/example-img.png' %}">
</div>
</div>
</div>
<div id="spacer"></div>
</body>
{% endblock %}

Much more simple than I had assumed. Just needed to add 'value="{{ form.field_name.value }}"' to each input.
<input type="text" class="foo" value="{{ form.field_name.value }}"/>
I also found that each django template tag was being saved. Replacing each <input> tag with the django {{ form.field_name }} variable also solved the problem.

Related

Django Form Post but doesn't display data

I'm working on a project but I'm kind of stuck on a problem. My Django post form doesn't have any bug but every time I submit a form, it redirects as it should but doesn't display anything. And I have 5 forms of the same type but it's only one of them that does it.
Code Snippet Below.
views.py:
########################## PRESCRIPTION #####################################################
def patients_list(request):
context = {'patients_list': Prescription.objects.all()}
return render(request, 'dashboard/patients_list.html', context)
def patients_form(request, id=0):
if request.method == 'GET':
if id == 0:
pform = PatientsForm()
else:
prescription = Prescription.objects.get(pk=id)
pform = PatientsForm(instance=prescription)
return render(request, 'dashboard/patients_form.html', {'pform': pform})
else:
if id == 0:
pform = PatientsForm(request.POST)
else:
prescription = Prescription.objects.get(pk=id)
pform = PatientsForm(request.POST, instance=prescription)
if pform.is_valid():
pform.save()
return redirect('/list')
urls.py:
########################## PRESCRIPTION #####################################################
path('form', views.patients_form, name='patients_form'),
path('list', views.patients_list, name='patients_list'),
path('update_patient/<str:id>/', views.patients_form, name="update_patient"),
path('patients_delete/<str:id>/', views.patients_delete, name="patients_delete"),
########################## END PRESCRIPTION #####################################################
patients_form.html:
<form action="" method="POST">
{% csrf_token %}
<div class="form-group">
{{pform.first_name|as_crispy_field}}
</div>
<div class="form-group">
{{pform.last_name|as_crispy_field}}
</div>
<div class="form-group">
{{pform.CNI|as_crispy_field}}
</div>
<div class="form-group">
{{pform.gender|as_crispy_field}}
</div>
<div class="form-group">
{{pform.marital_status|as_crispy_field}}
</div>
<div class="form-group">
{{pform.telephone1|as_crispy_field}}
</div>
<div class="form-group">
{{pform.telephone2|as_crispy_field}}
</div>
<div class="form-group">
{{pform.town|as_crispy_field}}
</div>
<div class="form-group">
{{pform.address|as_crispy_field}}
</div>
<div class="form-group">
{{pform.occupation|as_crispy_field}}
</div>
<div class="form-group">
{{pform.status|as_crispy_field}}
</div>
<div class="row">
<div class="col md 6">
<button class="btn btn-success my-4" type="submit"> <i class="flaticon-381-database"> </i> Submit</button>
</div>
<div class="col md 6">
<a href="{% url 'patients_list' %}" class="btn btn-secondary btn-block">Back To List
<i class="fas fa-stream"></i>
</a>
</div>
</div>
</form>
forms.py:
class PatientsForm(forms.ModelForm):
class Meta:
model = Prescription
fields = '__all__'
labels = {
'first_name': 'First Name',
'last_name': 'Last Name'
}
patients_list.html:
{% for prescription in patients_list %}
<tbody>
<tr>
<td>
<div class="custom-control custom-checkbox">
<input
type="checkbox"
class="custom-control-input"
id="customCheckBox2"
required=""
/>
<label
class="custom-control-label"
for="customCheckBox2"
></label>
</div>
</td>
<td>{{prescription.id}}</td>
<td>{{prescription.date_added}}</td>
<td>{{prescription.first_name}}</td>
<td>{{prescription.last_name}}</td>
<td>{{prescription.age}}Years</td>
<td>{{prescription.doctor}}</td>
<td>{{prescription.town}}</td>
<td>{{prescription.gender}}</td>
<td>
{% if prescription.status == 'New Patient' %}
<span class="badge badge-outline-primary">
<i class="fa fa-circle text-primary mr-1"></i>
{{prescription.status}}
</span>
{% elif prescription.status == 'In Treatement' %}
<span class="badge badge-warning light">
<i class="fa fa-circle text-warning mr-1"></i>
{{prescription.status}}
</span>
{% elif prescription.status == 'Recovered' %}
<span class="badge badge-info light">
<i class="fa fa-circle text-info mr-1"></i>
{{prescription.status}}
</span>
{% endif %}
</td>
<td>
<a href="{% url 'update_patient' prescription.id %}" class='btn text-secondary px-0'>
<i class="fa fa-pencil fa-fw"></i> Edit
</a>
</td>
<td>
<form action="{% url 'patients_delete' prescription.id %}" method='post' class='d-inline'>
{% csrf_token %}
<button class="btn text-warning px-0" type="submit"><i class="fa fa-trash-o fa-fw"></i> Delete
</button>
</form>
</td>
</tr>
</tbody>
{% endfor %}
please, try to use DGCBV in your case createView and updateView. It can be much much better. more here: https://docs.djangoproject.com/en/4.1/ref/class-based-views/flattened-index/#editing-views
in your case:
def patients_form(request, id=0):
if request.method == 'GET':
# some staff on get without return
else:
# some staffon post
if pform.is_valid():
pform.save()
return redirect('/list')
return render(request, 'dashboard/patients_form.html', {'pform': pform})
in this code you return form-render if form is NOT valid. Otherwise instance should be saved and you goes to '/list'

Django modelformset_factory id is required field

I'm trying to create a table of records to update with a single click. I keep getting the error [{'id': ['This field is required.']}] I can't seem to figure it out. I have tried to put {{ form.label_tag }} in somewhere to see if that would help, but it doesn't. I can't figure out how to be sure id gets passed back in for the edit.
forms.py
class ReleaseAssignForm(ModelForm):
def __init__(self, *args, **kwargs):
super(ReleaseAssignForm, self).__init__(*args, **kwargs)
for key in self.fields:
self.fields[key].required = False
class Meta:
model = Releases
fields = [
'id',
'rel_title',
'rel_summary',
'rel_english_title',
'rel_english_summary',
'rel_country',
'rel_risk_category',
'rel_ops_category',
'rel_assoc_indicator',
'rel_industry',
'rel_risk_assigned',
'rel_ops_assigned',
'rel_indu_assigned',
'rel_indi_assigned',
]
views.py
def preview_releases(request):
today = datetime.date.today()
count = 0
releases = Releases.published.filter(rel_date=today)
ReleaseAssignFormSet = modelformset_factory(Releases, ReleaseAssignForm, fields = '__all__', extra=0)
if request.method == "POST":
formset = ReleaseAssignFormSet(request.POST, queryset=releases)
if formset.is_valid():
posts = formset.save(commit=False)
for post in posts:
post.save()
return redirect('preview_releases')
else:
print(formset.errors)
print("Form Invalid")
else:
formset = ReleaseAssignFormSet(queryset=releases)
count = formset.total_form_count()
context = {
'count': count,
'formset': formset,
}
return render(request, 'management/preview-releases.html', context)
template.html
<form action="" method="POST">
{% csrf_token %}
{{ formset.management_form }}
{% if formset %}
{% for form in formset.forms %}
<div class="row py-5" style="border-bottom: 1px black solid;font-size: 14px;">
<div class="row px-5 pb-2" style="border-bottom: 1px lightgray dotted;font-size: 14px;">
<div class="col px-5 pb-2">
<span style="font-size: 12px;color: darkred;">Risk Category</span><br>
{{ form.rel_risk_category }}
</div>
<div class="col px-5 pb-2" style="border-right: 1px darkgray dotted;">
<span style="font-size: 12px;color: darkred;">Assigned</span><br>
{{ form.rel_risk_assigned }}
</div>
<div class="col px-5 pb-2">
<span style="font-size: 12px;color: darkred;">Ops Category</span><br>
{{ form.rel_ops_category }}
</div>
<div class="col px-5 pb-2">
<span style="font-size: 12px;color: darkred;">Assigned</span><br>
{{ form.rel_ops_assigned }}
</div>
</div>
<div class="row px-5 pt-2 pb-5">
<div class="col px-5 pb-2">
<span style="font-size: 12px;color: darkred;">Associated Indicator</span><br>
{{ form.rel_assoc_indicator }}
</div>
<div class="col px-5 pb-2" style="border-right: 1px darkgray dotted;">
<span style="font-size: 12px;color: darkred;">Assigned</span><br>
{{ form.rel_indi_assigned }}
</div>
<div class="col px-5 pb-2">
<span style="font-size: 12px;color: darkred;">Industry</span><br>
{{ form.rel_industry }}
</div>
<div class="col px-5 pb-2" >
<span style="font-size: 12px;color: darkred;">Assigned</span><br>
{{ form.rel_indu_assigned }}
</div>
</div>
<div class="row">
<div class="col px-5">
<h3>{{ form.instance.rel_title }}</h3>
<p>{{ form.label_tag }}</p>
<p>{{ form.instance.rel_summary }}</p>
</div>
<div class="col px-5" style="border-left: 1px lightgray dashed;">
<a target="_blank" href="{% url 'clean_release' form.instance.id %}"><h3>{{ form.instance.rel_title }}</h3></a>
<p>{{ form.instance.rel_country }}</p>
{% autoescape off %}
<p>{{ form.instance.rel_summary }}</p>
{% endautoescape %}
</div>
<div class="col px-5" style="border-left: 1px lightgray dashed;">
<a target="_blank" href="{% url 'clean_release' form.instance.id %}"><h3>{{ form.instance.rel_english_title }}</h3></a>
<p>{{ form.instance.rel_country }}</p>
{% autoescape off %}
<p>{{ form.instance.rel_english_summary }}</p>
{% endautoescape %}
</div>
</div>
</div>
{% endfor %}
{% else %}
No resources found.
{% endif %}
<div class="text-end py-5">
<button type="submit" class="btn btn-primary">Submit Changes</button>
</div>
</div>
</form>

display images in select option for selection -Django Python

I am working on a PRoject and I am stuck on order page.
Here, I want to display list of product images in options tag so that a user can select one image from all or can upload an image functionality of uploading image is working correctly but the selection is not working.
I want to show images to user so that user can select one of them.
models.py
class Product(models.Model):
prod_ID = models.AutoField("Product ID", primary_key=True)
prod_Name = models.CharField("Product Name", max_length=30, null=False)
prod_Desc = models.CharField("Product Description", max_length=2000, null=False)
prod_Price = models.IntegerField("Product Price/Piece", default=0.00)
prod_img = models.ImageField("Product Image", null=True)
class ImageTemplate(models.Model):
temp_id = models.AutoField("Template ID", primary_key=True, auto_created=True)
temp_img = models.ImageField("Template Image", null=False)
class ImageTemplateProductMapping(models.Model):
imageTemp_p_map_id = models.AutoField("Template Image & Product Map ID", primary_key=True, auto_created=True)
temp_id = models.ForeignKey(ImageTemplate, null=False, on_delete=models.CASCADE,
verbose_name="Image Template ID")
prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")
views.py
def order(request, id):
products = Product.objects.all()
ImageTemplateProductsList = []
try:
ImageTemplateProductsMap = ImageTemplateProductMapping.objects.filter(prod_id=id)
ImageTemplateProductsList = [data.temp_id.temp_img for data in
ImageTemplateProductsMap]
except AttributeError:
pass
context = {'products': products,
"ImageTemplateProductsList": ImageTemplateProductsList
}
return render(request, 'user/order.html', context)
order.html
{% extends 'user/layout/userMaster.html' %}
{% block title %}Order{% endblock %}
{% block css %}
form
{
position:relative;
}
.tasksInput
{
margin-right:150px;
}
label
{
vertical-align: top;
}
{% endblock %}
{% block header %}
{% endblock %}
{% block main %}
<div class="container">
<div>
<div class="row rounded mx-auto d-block d-flex justify-content-center">
<button class="btn btn-secondary my-2 mr-1">Custom</button>
<button class="btn btn-secondary my-2 ml-1">Package</button>
</div>
<div class="row">
<div class="col-4">
<div class="card border border-secondary">
<div class="card body mx-2 mt-4 mb-2">
{% for product in products %}
<a id="{{ product.prod_ID }}" class="card-header" style="font-size:5vw;color:black;"
href="{% url 'user-order' product.prod_ID %}">
<h5 class="h5">{{ product.prod_ID }}. {{ product.prod_Name }}</h5></a>
<div class="dropdown-divider"></div>
{% endfor %}
</div>
</div>
</div>
<div class="col-8">
<form>
<div class="card mx-2 my-2 border border-secondary">
<div class="my-2">
<div class="form-group">
<div class="form-group row mx-2">
<label for="quantity"
class="form-control-label font-weight-bold card-header col-4 ml-4 my-auto"
style="background-color:#e3e4e6"><h5>Quantity : </h5></label>
<input id="quantity" class="form-control col-5 mx-2 my-auto" type="number">
</div>
</div>
<div class="form-group">
<div class="form-group row mx-2">
<label for="ImageTemplateProductsList"
class="form-control-label font-weight-bold card-header col-4 ml-4"
style="background-color:#e3e4e6"><h5>Image Template : </h5></label>
<div id="ImageTemplateProductsList" class="mx-2">
<input id="Upload" type="radio" name="ImageSelection" value="Upload"/> Upload an
Image
<input type="file" name="file" class='btn btn-outline-secondary type my-2'>
<br>
<input id="Select" type="radio" name="ImageSelection" value="Select"/> Select
From Templates
<!-- Button trigger modal -->
<input type="button" name="url" style='display: none;'
class='btn btn-outline-secondary type my-2'
value="Choose Template" data-toggle="modal"
data-target="#exampleModalLong">
<!-- Modal -->
<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLongTitle" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Select
Template</h5>
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="d-flex-row justify-content-center modal-body"
style="background:red;">
<div>
<!-- Here I want to display images in select tag to make selection of one from all images but not able to achieve it. -->
<select id="ImageTemplateProductsList1">
{% for IT in ImageTemplateProductsList %}
<option value="{{IT}}"
><img src="{{IT.url}}" height="250" width="400"
class="border border-secondary rounded my-2 mx-3">
</option>
<br>
{% endfor %}
</select>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-danger"
data-dismiss="modal">Close
</button>
<button type="button" class="btn btn-outline-secondary">
Select
</button>
</div>
</div>
</div>
</div>
<br>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<div class="row rounded mx-auto d-block d-flex justify-content-center">
<button class="btn btn-success my-2">Place Order</button>
</div>
</div>
</div>
{% endblock %}
{% block js %}
$("document").ready(function(){
$(".type").hide();
$("input:radio").change(function() {
$(".type").hide();
$(this).next("input").show();
});
});
{% endblock %}
urls.py
path('order/<int:id>', views.order, name="user-order"),
I have slightly modified my html template with jquery and changed views a little bit and now it is working for me.
order.html
{% extends 'user/layout/userMaster.html' %}
{% block title %}Order{% endblock %}
{% block css %}
.t {
display: none;
}
img:hover {
opacity:0.8;
cursor: pointer;
}
img:active {
opacity:0.5;
cursor: pointer;
}
input[type=radio]:checked + label > img {
border: 20px solid rgb(228, 207, 94);
}
#dropdown{
height: 50px;
width: 50%;
font-size: 20px;
margin-left: 10px;
margin-top: 3px;
}
{% endblock %}
{% block header %}
{% endblock %}
{% block main %}
<div class="container">
<div>
<div class="row rounded mx-auto d-block d-flex justify-content-center">
<button class="btn btn-secondary my-2 mr-1">Custom</button>
<button class="btn btn-secondary my-2 ml-1">Package</button>
</div>
<div class="row">
<div class="col-4">
<div class="card border border-secondary">
<div class="card body mx-2 mt-4 mb-2">
{% for product in products %}
<a id="{{ product.prod_ID }}" class="card-header" style="font-size:5vw;color:black;"
href="{% url 'user-order' product.prod_ID %}">
<h5 class="h5">{{ product.prod_ID }}. {{ product.prod_Name }}</h5></a>
<div class="dropdown-divider"></div>
{% endfor %}
</div>
</div>
</div>
<div class="col-8">
<form method="POST" enctype="multipart/form-data">
<input type="hidden" id="templateValue" name="templateValue" value=""/>
{% csrf_token %}
<div class="form-group">
<div class="form-group row mx-2">
<label for="ImageTemplateProductsList"
class="form-control-label font-weight-bold card-header col-4 ml-4"
style="background-color:#e3e4e6"><h5>Image Template : </h5></label>
<div id="ImageTemplateProductsList" class="mx-2">
<input id="Upload" type="radio" name="ImageSelection"
class="templateSelection"/> Upload an
Image
<div class="type">
<input type="file" name="image"
class='btn btn-outline-secondary my-2 SelectedImage'>
</div>
<br>
<input type="radio" id="Select" name="ImageSelection" class="templateSelection"
/> Select
From Templates
<div class="type">
{% for IT in ImageTemplateProductsList %}
<input type="radio" name="image2" id="{{IT}}"
value="{{IT}}" class="SelectedImage t"/>
<label for="{{IT}}">
<img src="{{IT.url}}" style="width: 20vw;
height: 20vw;
padding: 2vw;"/>
</label>
<br>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row rounded mx-auto d-block d-flex justify-content-center">
<button type="submit" class="btn btn-success my-2">Place Order</button>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
{% block js %}
$("document").ready(function(){
$(".type").hide();
$("input:radio").on('change', function() {
$(".type").hide();
$(this).next("div").show();
});
$("#templateValue").val('');
$(".templateSelection").on('change', function(){
$("#templateValue").val('');
$("#templateValue").val($(this).attr('id'));
console.log($("#templateValue").val());
});
});
{% endblock %}
I have used hidden field to check whether user is trying to upload the image or select tha image and according to that I am taking the decision that what should I do:
views.py
def order(request, id):
products = Product.objects.all()
ImageTemplateProductsList = []
try:
ImageTemplateProductsMap = ImageTemplateProductMapping.objects.filter(prod_id=id)
ImageTemplateProductsList = [data.temp_id.temp_img for data in
ImageTemplateProductsMap]
except AttributeError:
pass
if request.method == 'POST':
try:
if request.POST['templateValue'] == 'Upload':
if 'image' in request.FILES:
Template_Value1 = request.FILES['image']
fs = FileSystemStorage()
fs.save(Template_Value1.name, Template_Value1)
TemplateValue = Template_Value1.name
elif request.POST['templateValue'] == 'Select':
TemplateValue = request.POST['image2']
else:
pass
except MultiValueDictKeyError:
pass
order_store = Order(product_img=TemplateValue)
order_store.save()
context = {'products': products,
"ImageTemplateProductsList": ImageTemplateProductsList
}
return render(request, 'user/order.html', context)

Django HTML for loop with filter

In my django project, I have an HTML that renders questions header, and inside the question headers I have question items. In my model, Question headers and items are two different entities. I need to show for every header, just the items related to that header. As it shows all items for all questions without any filters. Greatly appreciate any help!
Model:
class Question(models.Model):
question = models.CharField(max_length=240)
mission_section = models.ForeignKey('Mission_Section', on_delete=models.CASCADE)
type_question = models.ForeignKey('Type_Question', on_delete=models.CASCADE)
categories_question = models.ForeignKey('Categories_Question', on_delete=models.CASCADE, default=1)
order = models.IntegerField(default=1)
def __str__(self):
return self.question
class Question_Option(models.Model):
question = models.ForeignKey('Question', on_delete=models.CASCADE,default=1)
option = models.CharField(max_length=240)
correct = models.BooleanField()
order = models.IntegerField(default=1)
View:
class Questions(LoginRequiredMixin, FormView):
template_name = "questions.tmpl"
def get(self, request, pk):
context = {
'pk': pk,
'section': Mission_Section.objects.get(pk = pk ),
'questions_items': Question_Option.objects.filter(question__mission_section__pk=pk).order_by('order','pk'),
'questions': Question.objects.filter(mission_section__pk = pk ),
'question_types' : Type_Question.objects.all(),
'questions_categories': Categories_Question.objects.all()}
return render(self.request, self.template_name, context)
HTML
<input type="hidden" class="form-control" id="section" name="section" value="{{section.id}}" required>
<h1>{{ section.name }}</h1>
<div id="contentDiv">
<ol>
{% for question in questions %}
<div name="question" class="form-group" id="question-{{question.id}}" >
<form class='my-ajax-form' id="form-question-{{question.id}}" method='GET' action='.' data-url='{{ request.build_absolute_uri|safe }}'>
<li><div class="input-group">
{% csrf_token %}
{{ form.as_p }}
<input type="text" value= "{{question.id}}" id="question" name="question-hidden" class="form-control">
<input type="text" value= "{{question.question}}" id="question_name_{{question.id}}" class="form-control" aria-label="Amount" onchange="UpdateQuestion({{question.id}})">
</div>
</form>
<br>
<!-- Options -->
<div id = "question_content_{{question.id}}" name="question-options" class="collapse">
<ol class="example list-group">
{% for qi in questions_items %}
<li class="list-group-item d-flex justify-content-between align-items-center" id={{qi.id}} name="opt-{{question.id}}-{{qi.id}}" onclick="setCorrect({{qi.id}},{{question.id}})" contenteditable="true">{{ qi.option }}
<span class="badge badge-warning badge-pill">-</span>
</li>
{% endfor %} </ol>
<div>
<div class="d-flex justify-content-center">Add Option</div>
<div class="d-flex justify-content-center"> <br><i class="fa fa-plus-circle fa-1x" aria-hidden="true"></i></div>
</div>
</div>
</div></li>
{% endfor %} </ol>
using this answer I figured it out Double loop in Django template
What I need is:
<div id = "question_content_{{question.id}}" name="question-options" class="collapse">
{% csrf_token %}
{{ form.as_p }}
<form class='ajax-form-option' id="form-option-{{question.id}}" method='GET' action='.' data-url='{{ request.build_absolute_uri|safe }}'>
<ol class="example list-group">
{% for qi in question.question_option_set.all %}
<li class="list-group-item d-flex justify-content-between align-items-center" id=option-{{qi.id}} name="opt-{{question.id}}-{{qi.id}}">
<div contenteditable="true">{{ qi.option }}</div>
<div>
<button type="button" name='option-check' class="btn btn-light" value={{qi.id}} id="check-option-{{question.id}}-{{qi.id}}">
<i class="fas fa-check"></i>
</button>
<button type="button" class="btn btn-warning" id="delete-option-{{question.id}}-{{qi.id}}" onclick="deleteOption({{qi.id}})">
<i class="fa fa-trash" aria-hidden="true"></i>
</button>
</div>
</li>
{% endfor %} </ol>
<div onclick="CreateOption({{question.id}})">
<div class="d-flex justify-content-center">Add Option</div>
<div class="d-flex justify-content-center"> <br><i class="fa fa-plus-circle fa-1x" aria-hidden="true"></i></div>
</div>
</form>

Django 2, How to create an instance of Form in FormView with POST request?

I have a form made with HTML and I'm using a formview to take advantage of the POST method. The form has information on several HTML related select (interactive with Javascript), so the best option for me was to create an HTML form.
In summary, I want to instance a form. A form with the POST information, process the form, return the error messages or save (save is not the problem).
Code
Form View
class ServiceOrderForm(forms.Form):
TYPE = (
('preventivo', 'Preventivo'),
('correctivo', 'Correctivo'),
)
STATUS = (
('abierta','Abierta'), #amarillo
('aprobada','Aprobada'), #verde
('modificada','Modificada'), #rojo
('realizada','Realizada'), #azul
('rechazada','Rechazada'), #naranja
('Cerrada','Cerrada'), #Azul con check
)
id_orden_servicio = forms.IntegerField()
id_establecimiento = forms.IntegerField()
id_equipo_establecimiento = forms.IntegerField()
hora_entrada = forms.DateField()
hora_salida = forms.DateField()
tipo = forms.ChoiceField(choices=TYPE)
id_tecnico = forms.IntegerField()
fecha_panificada= forms.DateField()
hora_planificada = forms.DateField()
fecha = forms.DateField()
estado = forms.ChoiceField(choices=STATUS)
observaciones = forms.TextInput()
View
class ServiceOrderTemplateView(FormView):
''' Presenta el formulario del evento y sus detalles '''
template_name = 'serviceorders/service-order.html'
form_class = ServiceOrderForm
def get(self, request, **kwargs):
context = super(ServiceOrderTemplateView, self).get_context_data \
(**kwargs)
if request.user.is_authenticated and self.request.user.is_active:
customer_group = CustomerGroupData(request.user.id).get()
context_data_event = ContextDataEvent(customer_group)
event_service = ServiceEvent(kwargs['id_order_service'])
event_data = event_service.getEvent()
estado_equipo = {
'garantia': {
'label': 'danger',
'icon': 'fa-ban',
},
'vida_util' : {
'label': 'success',
'icon': 'fa-check',
}
}
data = {
'customer_group': customer_group,
'establishments' : context_data_event.getEstablishments(),
'equipments' : context_data_event.getEquipments(),
'create': False,
'technicals' : context_data_event.getTechnicals(),
'current_equipment' : event_data['equipment'],
'current_technical' : event_data['technical'],
'current_establishment': event_data['establishment'],
'current_year': 2018,
'equipment_standard' : event_data['equipment_standard'],
'historic_orders' : event_service.getHistoricEvent(),
'current_order_detail' : event_service.getDetailService(),
'images_service_order' : event_service.getImageItem(),
'items_mantenimiento' : event_service.getDetailService(),
'equipment_estatus' : estado_equipo,
'order_service' : event_data['order_service'],
'id_order' : kwargs['id_order_service'],
}
context.update({'data': data})
return self.render_to_response(context)
def post(self, request, *args, **kwargs):
context = super(ServiceOrderTemplateView, self).get_context_data \
(**kwargs)
form = ServiceOrderForm(request.POST)
#the form always is empty
#if form is valid this method return
if form.is_valid():
print('El formulario es valido')
#more code
HttpResponseRedirect('/mostrar/orden/servicio/')
else:
print('El formulario en invalido')
#return this error ti html template
print(form.errors)
data = {
'form': form,
'errors' : form.errors
}
context.update({ 'data' : data })
print('recibiendo data por post')
return self.render_to_response(context)
html
<form action="" method="post" role="form">
{% csrf_token %}
<input type="hidden" name="id_orden_servicio" value="{{ data.order_service.id_orden_servicio }}">
<div class="col-md-1"></div>
<div class="col-md-5">
<div class="row">
<div class="col-sm-4 text-right">
<label>Nro Orden:</label>
</div>
<div class="col-sm-4">
<input
type="text"
readonly = ""
name="id_orden_servicio"
value="OS-{{ data.current_year }}-{{ data.order_service.id_orden_servicio }}"
>
</div>
<div class="col-sm-2"></div>
</div>
<div class="row">
<div class="col-sm-4 text-right">
<label>Establecimiento:</label>
</div>
<div class="col-sm-4">
<select class="btn btn-sm btn-default" name="id_establecimiento" id="id_establecimiento">
{% if data.create == True %}
<option selected disabled>Seleccione...</option>
{% for establishment in data.establishment %}
<option value="{{ establishment.id_establecimiento }}">{{ establishment }}</option>
{% endfor %}
{% else %}
<option value="{{ data.current_establishment.id_establecimiento }}" disabled selected>{{ data.current_establishment }}</option>
{% endif %}
</select>
</div>
<div class="col-sm-2"></div>
</div>
<div class="row">
<div class="col-sm-4 text-right">
<label>Equipos:</label>
</div>
<div class="col-sm-6">
<select class="btn btn-sm btn-default" name="id_equipo_establecimiento" id="id_equipo_establecimiento">
{% if data.create == True %}
<option selected disabled>Seleccione...</option>
{% for equipment in data.equipments %}
<option value="{{equipment.id_equipo_establecimiento}}">{{ equipment }}</option>
{% endfor %}
{% else %}
<option value="{{data.current_equipment.id_equipo_establecimiento}}" disabled selected>{{ data.current_equipment }}</option>
{% endif %}
</select>
</div>
<div class="col-sm-2"></div>
</div>
<div class="row">
<div class="col-sm-4 text-right">
<label>Mantenimiento.:</label>
</div>
<div class="col-sm-6">
<select class="btn btn-sm btn-default" name="tipo_mantenimiento" id="tipo_mantenimiento">
{% if data.create == True %}
<option selected disabled>Seleccione...</option>
<option value="preventivo">Preventivo</option>
<option value="correctivo">Correctivo</option>
{% else %}
<option selected disabled value="{{data.order_service.tipo}}">{{ data.order_service.tipo | upper}}</option>
{% endif %}
</option>
</select>
</div>
<div class="col-sm-2"></div>
</div>
<div class="row">
<div class="col-sm-4 text-right">
<label>Técnico:</label>
</div>
<div class="col-sm-6">
<select class="btn btn-sm btn-default" name="id_tecnico" id="id_tecnico">
{% if data.create == True %}
<option selected disabled>Seleccione...</option>
{% for technical in data.technicals %}
<option value="{{technical.id_tecnico}}">{{ technicals.apellidos }} {{ technicals.nombres }} </option>
{% endfor %}
{% else %}
<option value="{{ data.order_service.id_tecnico_id }}">{{ data.order_service.id_tecnico }}</option>
{% endif %}
</option>
</select>
</div>
<div class="col-sm-2"></div>
</div>
<div class="row">
<div class="col-sm-4 text-right">
<label>Fecha Mant.:</label>
</div>
<div class="col-sm-5">
<input type="text" name="fecha" style="width: 100%" value = "{{ data.order_service.fecha | date:"d/m/Y" }}">
</div>
</div>
<div class="row">
<div class="col-sm-4 text-right">
<label>Observaciones:</label>
</div>
<div class="col-sm-5">
<textarea rows="5" cols="31" name="observaciones">{{ data.order_service.observaciones }}</textarea>
</div>
</div>
</div>
<div class="col-md-5">
<div class="row">
<div class="col-sm-4 text-right">
<label>Imagen de equipo:</label>
</div>
<div class="col-sm-6">
<img src="{{BASE_URL}}media/{{ data.current_equipment.url_imagen }}" style="width: 60%;height: auto">
</div>
<div class="col-sm-2 text-left">
<span class="label label-{{data.equipment_estatus.garantia.label}}">
<i class="fas {{ data.equipment_estatus.garantia.icon }}"></i> Garantía
</span>
<span class="label label-{{data.equipment_estatus.vida_util.label}}">
<i class="fas {{ data.equipment_estatus.vida_util.icon }}"></i> Vida Útil
</span>
</div>
</div>
<div class="row">
<div class="col-sm-4 text-right">
<label>Plano ubicación:</label>
</div>
<div class="col-sm-6">
<a href="{{BASE_URL}}media/{{ data.current_equipment.url_ubicacion}}" class="btn btn-sm btn-default" target="_blank">
<i class="fa fa-eye"></i> Ver Ubicación
</a>
</div>
<div class="col-sm-2"></div>
</div>
<div class="row">
<div class="col-sm-4 text-right">
<label>Lugar:</label>
</div>
<div class="col-sm-6">
<input type="text" value="{{ data.current_equipment.ubicacion }}" readonly="">
</div>
<div class="col-sm-2"></div>
</div>
<div class="row">
<div class="col-sm-4 text-right">
<label>Nro Serie:</label>
</div>
<div class="col-sm-6">
<input type="text" value="{{ data.current_equipment.nro_serie }}" readonly="">
</div>
<div class="col-sm-2"></div>
</div>
<div class="row">
<div class="col-sm-4 text-right">
<label>Estado Orden:</label>
</div>
<div class="col-sm-6">
{% if data.create == True %}
<a href="#" class="btn btn-sm {{data.order_service.estado}}">
<i class="fas fa-info-circle"></i>
ABIERTA
</a>
{% else %}
<a href="#" class="btn btn-sm {{data.order_service.estado}}">
<i class="fas fa-info-circle"></i>
{{ data.order_service.estado | upper }}
</a>
{% endif %}
</div>
<div class="col-sm-2"></div>
</div>
<br>
<div class="row">
<div class="col-sm-8 text-right">
</div>
<div class="col-sm-4 text-right">
<button class="btn btn-sm btn-primary" type="submit">
{% if data.create == True %}
<span class="fas fa-plus"></span>
Agergar Orden Mantenimiento
{% else %}
<span class="fas fa-save"></span>
Guardar Cambios
{% endif %}
</button>
</div>
</div>
</div>
<div class="col-md-1"></div>
</form>
thanks!.
I solved it
the form was always empty because the forms.py did not have the same fields as the html
i cant use createview because need add information in the form.

Categories

Resources