display images in select option for selection -Django Python - 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)

Related

How to submit input type = range in flask

While trying to submit input type = range i'm getting "Bad request error".
HTML:
{% extends "base.html" %} {% block content %} <head>
<link rel="stylesheet" href="css/style.css" />
</head>
<div class="search-bar">
<div class="rt-container">
<form method="post" action="#">
<div class="col-rt-12">
<div class="Scriptcontent">
<!-- Range Slider HTML -->
<div slider id="slider-distance">
<div>
<div inverse-left style="width: 70%"></div>
<div inverse-right style="width: 70%"></div>
<div range style="left: 30%; right: 40%"></div>
<span thumb style="left: 30%"></span>
<span thumb style="left: 60%"></span>
<div sign style="left: 30%">
<span id="value">0</span>
</div>
<div sign style="left: 60%">
<span id="value">100</span>
</div>
</div>
<input name="max" type="range" tabindex="0" value="30" max="100" min="0" step="1" oninput="
this.value=Math.min(this.value,this.parentNode.childNodes[5].value-1);
var value=(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.value)-(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.min);
var children = this.parentNode.childNodes[1].childNodes;
children[1].style.width=value+'%';
children[5].style.left=value+'%';
children[7].style.left=value+'%';children[11].style.left=value+'%';
children[11].childNodes[1].innerHTML=this.value;" />
<input name="min" type="range" tabindex="0" value="60" max="100" min="0" step="1" oninput="
this.value=Math.max(this.value,this.parentNode.childNodes[3].value-(-1));
var value=(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.value)-(100/(parseInt(this.max)-parseInt(this.min)))*parseInt(this.min);
var children = this.parentNode.childNodes[1].childNodes;
children[3].style.width=(100-value)+'%';
children[5].style.right=(100-value)+'%';
children[9].style.left=value+'%';children[13].style.left=value+'%';
children[13].childNodes[1].innerHTML=this.value;" />
<input id="search" type="submit" value="SEARCH" href="#"></input>
</div>
</form>
</div>
</div>
</div>
<form action="/lobbies" method="POST">
<input type="checkbox" name="IsVisible" value="0" default="0">Private?</input>
<input type="text" name="LobbyValue" placeholder="Value" href="#" required></input>
<input type="submit" value="CREATE" href="#"></input>
</form>
</div>
<div class="container"> {% for lobby in data%} <div class="lobby-item">
<div class="lobby-coins">
<img src="static/StashedCoins.png" alt="coin" width="32px" height="32px" /> {% print lobby['GameValue']%}
</div>
<div class="lobby-photo">
<a href="/Player/{{lobby['PlayerOneID']}}">
<img src=https://robohash.org/{{lobby['CreatorName']}} alt="coin" width="110px" height="110px" />
</a>
</div>
<div class="lobby-join">
Join
</div>
</div>
{%endfor%}
</div>
{% endblock %}
Flask:
#app.route("/lobbies", methods=["GET", "POST"])
def lobbies():
if "username" in session:
coins = requests.get(API_URL + "/GetUserBalance/" + str(session["id"])).json()[
"balance"
]
ProfilePicture = "https://robohash.org/" + str(session["username"])
color = str(session["color"])
PlayerID = session["PlayerID"]
if request.method == "POST":
LobbyValue = request.form['LobbyValue']
if "IsVisible" in request.form:
response = requests.post(API_URL + "/CreateNewLobby", params={"ApiUser": API_USER,"PlayerID": PlayerID, "IsVisible": 0, "LobbyValue": LobbyValue}).json()
else:
response = requests.post(API_URL + "/CreateNewLobby", params={"ApiUser": API_USER,"PlayerID": PlayerID, "LobbyValue": LobbyValue}).json()
LobbyID = response['LobbyID']
return redirect(url_for('lobby',LobbyID=LobbyID))
data = requests.get(API_URL + "/GetLobbies", params={"PlayerID": PlayerID})
return render_template(
"lobbies.html",
coins=coins,
ProfilePicture=ProfilePicture,
color=color,
data=data.json(),
)
else:
return redirect(url_for("login"))
I dont understand what im doing wrong here.
I want to give user a slider with two handlers like this:
So they can filter the lobbies within the price range set in slider. I need in this example number 0 and 69 to be send to my flask app so i can then display lobbies within the price range.

Field 'id' expected a number but got 'Student'

I tried to apply python manage.py migrate I get the error Field 'id' expected a number but got 'Student'.
I've set the value of primary key to be id.
views.py:
#----------------------STUDENT OPERATION------------------------------------
#login_required()
def test_form(request):
students = TestModel.objects.all()
paginator = Paginator(students,20)
page_number = request.GET.get('pages')
page_obj = paginator.get_page(page_number)
enter code here
if request.method == 'POST':
form = TestForm(request.POST)
if form.is_valid():
x = form.instance.student
print(x)
p = form.save(commit=False)
p.save()
messages.success(request,'Student "{}" has been succesfully added!'.format(x))
return redirect('testform')
else:
form = TestForm()
return render(request,'testform.html', {'form':form,'students':page_obj})
#login_required()
def update_form(request,id):
if request.method == 'POST': #defpost
obj = TestModel.objects.get(pk = id)
form = TestForm(request.POST,instance=obj)
if form.is_valid():
form.save()
messages.success(request,'Student "{}" was succesfully updated'.format(obj.student))
return redirect('testform')
else: #def get()
obj = TestModel.objects.get(pk=id)
print(obj.student)
print('###')
form = TestForm(instance=obj)
return render(request,'testform_update.html',{'form':form})
#login_required()
def del_testform(request,id):
if request.method == 'POST':
obj = TestModel.objects.get(pk = id)
student = obj.student
obj.delete()
messages.warning(request,'Student "{}" has been deleted succesfully!'.format(student))
return redirect('testform')
def home(request):
posts = Post.objects.all().order_by('-date_posted')[:8]
destinations = Destinations.objects.all().order_by('date_posted')[:6]
return render(request,'home.html', {'posts':posts, 'destinations':destinations})
models.py:
class TestModel(models.Model):
GENDER_CHOICES = (('Male','Male'),('Female','Female'))
student = models.CharField(max_length=100,null=True)
address = models.CharField(max_length=100)
gender = models.CharField(choices=GENDER_CHOICES,max_length=50)
email = models.EmailField(null=True)
def __str__(self):
return self.student
testform.html:
{% extends 'index.html' %}
{% load static %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-md-8">
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }} alert-dismissible fade show my-2" role="alert">
{{ message }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endfor %}
{% endif %}
<div class="col-md-5 mr-auto">
<form method="POST">
{% csrf_token %}
<legend class="">Enter Student Details</legend>
<div class="form-group">
{{form|crispy}}
<button type="submit" class="btn btn-primary">Add Student</button>
</div>
</form>
</div>
<div>
</div>
<div class="my-2 ">
<div class="text-center border bg-white">
<h3>Student Table</h3>
</div>
<table class="table table-white table-striped table-hover table-bordered">
<tr>
<td colspan="6">
<form class="form-inline" name = "table-search" >
<div class="form-group mr-auto">
<input type="text" class="form-control" placeholder = "Search Student">
<button class="btn btn-primary ml-2 mt-1 form-control " type="submit">Search</button>
</div>
<div class="form-group">
</div>
</form>
</td>
</tr>
<thead>
<tr>
<th>SN</th>
<th>Name</th>
<th>Address</th>
<th>Gender</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
{% for student in students %}
<tr>
<td>{{forloop.counter}}.</td>
<td>{{student.student}}</td>
<td>{{ student.address}}</td>
<td>{{student.gender}}</td>
{% if student.email %}
<td>{{student.email}}</td>
{% elif student.email == None %}
<td class="text-danger">Not Available</td>
{% endif %}
<td>
<button type="button" class="btn btn-danger btn-sm" data-toggle="modal"
data-target="#staticBackdrop{{student.id}}">
<i class="fas fa-trash mr-2"></i> Delete
</button>
<a class="btn btn-primary btn-sm " href="{% url 'testform-update' student.id%}"><i class="fas fa-pen mr-2"></i> Update</a>
</td>
</tr>
<!-- modal-->
<div class="modal fade" id="staticBackdrop{{student.id}}" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel"><span class="text-danger">Delete</span></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="text-muted">Delete student <strong>"{{student.student}}"</strong>?
</div>
<div class="modal-footer">
<form method="POST" action="{% url 'testform-delete' student.id %}" name="deleteform">
{% csrf_token %}
<button class="btn btn-danger" type="submit">Delete</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close
</button>
</form>
</div>
</div>
</div>
</div>
<!-- modal-->
{% endfor %}
</table>
</div>
</div
</div>
</div>
{% endblock %}

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.

Only part of form is saved upon validation error

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.

Categories

Resources