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'
Related
I am using Django with MySQL database. Everything is working, but the data I input will not save to the database.
This is my HTML:
<form class="space-y-8 divide-y divide-gray-200 m-2">
{% csrf_token %}
<div class="space-y-8 divide-y divide-gray-200">
<div class="pt-8">
<div>
<h3 class="text-lg leading-6 font-medium text-gray-900">
Project Information
</h3>
</div>
<div class="mt-6 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6">
<div class="sm:col-span-3">
<label for="project-name" class="block text-sm font-medium text-gray-700">
Project Name
</label>
<div class="mt-1">
<input type="text" name="project-name" id="project-name"
class="shadow-sm focus:ring-gray-500 focus:border-gray-500 block w-full sm:text-sm border-gray-300 rounded-md">
</div>
</div>
<div class="sm:col-span-3">
<label for="project-location" class="block text-sm font-medium text-gray-700">
Project Location
</label>
<div class="mt-1">
<input type="text" name="project-location" id="project-location"
class="shadow-sm focus:ring-gray-500 focus:border-gray-500 block w-full sm:text-sm border-gray-300 rounded-md">
</div>
</div>
</div>
<div class="mt-6 grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6">
<div class="sm:col-span-3">
<label for="project-operator" class="block text-sm font-medium text-gray-700">
Operator
</label>
<div class="mt-1">
<input type="text" name="project-operator" id="project-operator"
class="shadow-sm focus:ring-gray-500 focus:border-gray-500 block w-full sm:text-sm border-gray-300 rounded-md">
</div>
</div>
<div class="sm:col-span-3">
<label for="project-start-date" class="block text-sm font-medium text-gray-700">
Start Date
</label>
<div class="mt-1">
<input type="text" name="project-start-date" id="project-start-date"
class="shadow-sm focus:ring-gray-500 focus:border-gray-500 block w-full sm:text-sm border-gray-300 rounded-md">
</div>
</div>
</div>
</div>
<div class="pt-5">
<div class="flex justify-end">
<button type="submit"
class="ml-3 inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-gray-600 hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500">
Save
</button>
</div>
</div>
</div>
</form>
This is my views.py
def project(request):
if request.method == 'POST':
form = ProjectForm(request.POST or None)
if form.is_valid():
form.save()
all_items = Project.objects.all
return render(request, 'project.html', {'all_items': all_items})
all_items = Project.objects.all
return render(request, 'project.html', {'all_items': all_items})
This is my forms.py:
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ['project_name', 'project_location',
'operator', 'date_started']
This is my models.py
class Project(models.Model):
project_name = models.CharField(max_length=30)
project_location = models.CharField(max_length=30)
operator = models.CharField(max_length=30)
date_started = models.DateField()
I am not getting any errors, but the data I save is not saved in the database. Can anyone see what I need to fix?
In your view which directs you to html page :
def project(request):
if request.method == "POST":
form = ProjectForm(request.POST)
if form.is_valid():
form.save()
else:
print("Invalid input from user") # for debugging only, handle according to your need
form = ProjectForm()
all_items = Project.objects.all()
return render(request, 'project.html', {'form': form, 'all_items':all_items})
In your html
<form action="{% url 'url_name_for_your_project_view' %}" method="POST">
{% csrf_token %}
{{ form }}
<input type="submit" value="submit">
</form>
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)
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 %}
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>
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.