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>
Related
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>
lostList.html shows LostNotices and Dogs.
I want to match lostnotice and dog using foreign key in Dog model.
So i used for loop and if in the template.
But it doesn't work....
I am trying to fix this for 2 days but i couldn't.
It will be really big help for me. Thank you
{% for lostPost in lostPosts.all reversed %}
<h6>{{lostPost.id}}</h6>
{% for dog in dogs.all %}
<h6>{{dog.breed}}</h6><br>
<div class="col-lg-3 col-sm-6 col-md-6">
<div class="card">
<div class="card-body">
{% if dog.LostNoticeNum == lostPost.id %}
views.py
def lostList(request):
lostPosts = LostNotice.objects
dogs=Dog.objects
return render(request, '/lostList.html', {'lostPosts' : lostPosts,'dogs':dogs})
model.py
class LostNotice(models.Model):
Title=models.CharField(max_length=20,null=True)
State=models.IntegerField()
PubDate=models.DateTimeField()
MissingDate=models.DateTimeField()
Text=models.TextField()
Phone=models.CharField(max_length=20,null=True)
Author=models.ForeignKey(Member, on_delete = models.CASCADE,null=True)
Si=models.CharField(max_length=20,null=True)
Gu=models.CharField(max_length=20,null=True)
Dong=models.CharField(max_length=20,null=True)
class Dog(models.Model):
Name=models.CharField(max_length=20)
Breed=models.CharField(max_length=20)
Sex=models.CharField(max_length=20,null=True)
Color=models.CharField(max_length=20,null=True)
LostNoticeNum=models.ForeignKey(LostNotice, on_delete = models.CASCADE,null=True)
FindNoticeNum=models.ForeignKey(FindNotice, on_delete = models.CASCADE,null=True)
template:
<div class="" id="list">
<div class="container">
<div class="row mx-auto">
<div class="col-lg-12 col-sm-12 col-md-12 col-12 pr-1">
<div class="row mb-2 ml-2 mr-2">
{% for lostPost in lostPosts.all reversed %}
<h6>{{lostPost.id}}</h6>
{% for dog in dogs.all %}
<h6>{{dog.breed}}</h6><br>
<div class="col-lg-3 col-sm-6 col-md-6">
<div class="card">
<div class="card-body">
{% if dog.LostNoticeNum == lostPost.id %}
<h6>breed</h6>
<h6 class="card-title" style="text-align: center; color: gray">{{dog.Breed}}</h6>
{% else %}
<h6 class="card-title" style="text-align: center">{{lostPost.sex}}</h6>
{% endif %}
{{lostPost.photo}}
{% if lostPost.photo %}
<img class="card-img-top rounded-circle mx-auto pt-1" src="{{ lostPost.photo.url }}"
style="height: 200px">
{% else %}
<img class="card-img-top rounded-circle mx-auto pt-1"
src="https://image.flaticon.com/icons/svg/2138/2138440.svg" style="height: 200px">
<h4 class="card-title">{{lostPost.pet_name}}</h4>
<p class="card-text"> text: {{lostPost.Text}} <br> location: {{lostPost.Si}}<br>date :
{{lostPost.MissingDate}}</p>
more
{% endif %}
</div>
</div>
</div>
{% endfor %}
{% endfor %}
</div>
</div>
</div>
</div>
</div>
You can access the related dogs with .dog_set.all:
{% for lostPost in lostPosts reversed %}
<h6>{{lostPost.id}}</h6>
{% for dog in lostPost.dog_set.all %}
<h6>{{dog.breed}}</h6><br>
…
{% endfor %}
{% endfor %}
In the view, you pass a queryset with .prefetch_related:
def lostList(request):
lostPosts = LostNotice.objects.prefetch_related('dog')
dogs=Dog.objects
return render(request, '/lostList.html', {'lostPosts' : lostPosts})
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.