I am a newbie, and I am working on a website. On this website I have created admin panel to manage different products and attributes .
I have a page named size.html and and I am supposed to change it name and make it productAtributes.html and on this single page I want to do all add, update, delete operations for different Product attributes.
My code is as:
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)
def __str__(self):
return "{}-->{}".format(self.prod_ID,
self.prod_Name)
class Size(models.Model):
size_id = models.AutoField("Size ID", primary_key=True, auto_created=True)
prod_size = models.CharField("Product Size", max_length=20, null=False)
def __str__(self):
return "{size_id}-->{prod_size}".format(size_id=self.size_id,
prod_size=self.prod_size)
class Color(models.Model):
color_id = models.AutoField("Color ID", primary_key=True, auto_created=True)
prod_color = models.CharField("Product Color", max_length=50, null=False)
def __str__(self):
return "{color_id}-->{prod_color}".format(color_id=self.color_id,
prod_color=self.prod_color)
class PaperChoice(models.Model):
paper_id = models.AutoField("Paper Choice ID", primary_key=True, auto_created=True)
paper_choices_name = models.CharField("Paper Choices", max_length=50, null=False)
def __str__(self):
return "{}-->{}".format(self.paper_id,
self.paper_choices_name)
views.py
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.shortcuts import render, redirect
from user.models import *
def size(request):
if request.method == 'POST':
size_store = request.POST['prod_size']
size_update = Size(prod_size=size_store)
size_update.save()
return redirect('/admin1/productSize')
else:
size_show = Size.objects.all()
# start paginator logic
paginator = Paginator(size_show, 3)
page = request.GET.get('page')
try:
size_show = paginator.page(page)
except PageNotAnInteger:
size_show = paginator.page(1)
except EmptyPage:
size_show = paginator.page(paginator.num_pages)
# end paginator logic
return render(request, 'admin1/size.html', {'size_show': size_show})
def size_edit(request, id):
size_edit = Size.objects.filter(size_id=id)
return render(request, 'admin1/size.html', {'size_edit': size_edit})
def size_edit_update(request, id):
if request.method == 'POST':
size_store = request.POST['prod_size']
size_update = Size(size_id=id, prod_size=size_store)
size_update.save()
return redirect('/admin1/productSize')
def size_delete(request, id):
size_deletee = Size.objects.filter(size_id=id)
size_deletee.delete()
return redirect('/admin1/productSize')
As I created add, update, delete functionality for Size I am going to do it same with color and Papaer choice.
size.html
{% extends 'admin1/layout/master.html' %}
{% block title %}Size{% endblock %}
{% block main %}
<h1>
<center>Size</center>
</h1>
<div class="container">
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10">
<button type="button" class="btn btn-primary mt-2" data-toggle="modal" data-target="#modal-primary">Add
Size
</button>
<div class="modal fade" id="modal-primary">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Product Size</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
</div>
<div class="modal-body mt-2">
<form action="{% url 'admin-product-size'%}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<label>Product Size:</label>
<input type="text" name="prod_size" class="form-control w-50"><br>
<br>
<input type="Submit" name="Submit" value="Submit" class="btn btn-success w-50"><br>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-outline-light" data-dismiss="modal">Close
</button>
</div>
</form>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<br>
{% if size_show %}
<div class="container-fluid ">
<div class="row">
<div class="card mt-2 border border-secondary">
<div class="card-header">
<h3 class="card-title ">Product Table</h3>
</div>
<!-- /.card-header -->
<div class="card-body">
<table class="table table-bordered border border-info">
<thead>
<tr>
<th>Product Id</th>
<th>Product Size</th>
</tr>
</thead>
<tbody class="justify-content-center">
{% for x in size_show %}
<tr>
<td>{{x.size_id}}</td>
<td>{{x.prod_size}}</td>
<td><a href="/admin1/size_edit/{{x.size_id}} "
class="btn btn-outline-primary mt-2"><i
class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
<a href="/admin1/size_delete/{{x.size_id}}"
class="btn btn-outline-danger mt-2"><i
class="fa fa-trash" aria-hidden="true"></i></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- /.card-body -->
<div class="card-footer clearfix ">
<ul class="pagination pagination-sm m-0 justify-content-center">
{% if size_show.has_previous %}
<li class="page-item"><a class="page-link"
href="?page={{size_show.has_previous_page_number}}">
Previous </a>
</li>
{% endif%}
{% for x in size_show.paginator.page_range %}
{% if size_show.number == x %}
<li class="page-item active"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% else%}
<li class="page-item"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% endif %}
{% endfor %}
{% if size_show.has_next %}
<li class="page-item"><a class="page-link"
href="?page={{size_show.has_next_page_number}}"> Next </a>
</li>
{% endif %}
</ul>
</div>
</div>
<!-- /.card -->
</div>
</div>
{% endif %}
{% if size_edit %}
{% for x in size_edit %}
<form action="/admin1/size_data_update/{{x.size_id}}" method="POST">
{% csrf_token %}
<label>Size Name:</label>
<input type="text" name="prod_size" value="{{x.prod_size}}" class="form-control w-50"><br>
<input type="Submit" name="Submit" value="Submit" class="btn btn-success w-50"><br>
</form>
{% endfor %}
{% endif %}
</div>
</div>
</div>
{% endblock %}
For performing oertions of views.py I have created size.html .Nut there around 10 to 12 product attributes ,and for that attributes I don't want to create seprate html pages.
I want to do all the operations for all the attributes in single html page. Is it possible?
Means according to the atrribut type request the page data should change dynamically, I do not have to create seprate template pages for each attribute.
You need to make the form in your views, not the Templates, I'm not sure if this is best practise but it's the only way I see you can do this, (using Class-Based Views would simplify this process a lot) but if you want to stick to functions, this is what you do.
Let's take an input line:
<label>Product Size:</label>
<input type="text" name="prod_size" class="form-control w-50"><br>
Let's use Django's tags and turn it into this:
<label>{{form.display_name}}:</label>
<input type="text" name="{{form.name}}" class="form-control w-50">
The class will probably be the same but you could extend the same functionality to the class or type fields.
In the backend, you want to make a list of all the elements you want to show, with nested dictionaries:
forms = [ # Each form
[ # Each field within the form, this way, you can have a different amount each time
{'display_name': 'Product Size', # label Display name
'name': 'prod_size'}, # name tag value
{'display_name': "it's value", # This is a different field
'name': 'just an example'}
],
]
Then you can do a for loop in the templates:
{% for form in forms %}
{$ for field in form %}
<label>{{field.display_name}}:</label>
<input type="text" name="{{field.name}}" class="form-control w-50">
I'm not exactly sure what you're trying to do in your code, so I didn't make this example too specific, but hopefully, it will give you inspiration to get you on the right track, if you need more help, just ask
Related
I am using bootstrap tabs navigation bar and I want to retrieve the id of the tag and pass it to my view but my main issue though is I am not using them in my urls.py. Here is my urls.py file.
from django.urls import path
from .views import (
index, add_task, update_task,
delete_task, update_categories,
delete_all_task
)
urlpatterns = [
path('', index, name="home"),
path('add-task/', add_task, name="add-task"),
path('update-task/<int:pk>/', update_task, name="update-task"),
path('delete-task/<int:pk>/', delete_task, name="delete-task"),
path('update-category/', update_categories, name="update-category"),
path('delete_all_tasks/', delete_all_task, name="delete_all_tasks"),
]
And here is the views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.forms import modelformset_factory
from .models import Tasks, Category
from .forms import AddTaskForm, UpdateTaskForm, UpdateCategoryForm
def get_task_minid(categories):
id_list = []
for task in categories:
id_list.append(task.id)
min_id = min(id_list)
return min_id
def index(request):
tasks = Tasks.objects.all()
categories = Category.objects.all()
if len(categories) > 1:
min_id = get_task_minid(categories)
if request.method == "POST":
category = request.POST.get('category')
cat = Category.objects.create(name=category)
cat.save()
return redirect('home')
context = {
'tasks': tasks,
'categories': categories,
'min_id': min_id,
}
return render(request, 'Todo/index.html', context)
and here is the index.HTML
<div class="" id="Todo-tasks">
<div class="card card-primary card-outline">
<div class="card-body">
<div class="row">
<div class="col-5 col-sm-3">
<div class="card-header">
<span>All Categories</span>
</div>
<div class="nav flex-column nav-tabs h-100" id="vert-tabs-tab" role="tablist" aria-orientation="vertical">
{% for cat in categories %}
{% if cat.id == min_id %}
<a class="nav-link active" id="vert-tabs-{{cat}}-tab" data-toggle="pill" href="#vert-tabs-{{cat}}"
role="tab" aria-controls="vert-tabs-{{cat}}" aria-selected="true">{{cat}}</a>
{% else %}
<a class="nav-link" id="vert-tabs-{{cat}}-tab" data-toggle="pill" href="#vert-tabs-{{cat}}"
role="tab" aria-controls="vert-tabs-{{cat}}" aria-selected="false">{{cat}}</a>
{% endif %}
{% endfor %}
<div class="card-footer mt-3">
<form action="" method="POST">
{% csrf_token %}
<input type="text" name="category" placeholder="Add category" class="new-input cat" aria-label="Add new category" />
<button type="submit" class="new">+</button>
</form>
</div>
Manage Categories
</div>
</div>
<div class="col-7 col-sm-9">
<div class="tab-content" id="vert-tabs-tabContent">
{% for cat in categories %}
{% if cat.id == min_id %}
<div class="tab-pane text-left fade show active" id="vert-tabs-{{cat}}" role="tabpanel" aria-labelledby="vert-tabs-{{ cat }}-tab">
<ul class="list-unstyled border pb-4">
<div class="card-header d-flex justify-content-between justify-content-center">
{{ cat }}
<div class="form-group">
<form action="" class="p-0 justify-content-end" method="post">
<input type="text" name="search" class="form-input pl-3" placeholder="Search for tasks..."/>
</form>
</div>
</div>
{% for task in cat.tasks.all %}
<li class="align-content-center"><a>{{task.text}}
<small class="badge bg-success">{{task.due_date|timeuntil|upto:','}}</small>
<span class=""></i></span>
<span class=""></i></span>
</a>
</li>
{% empty %}
<h3 class="alert alert-info m-5"><i class="fas fa-alert-outline"></i> Please add new tasks to categories</h3>
{% endfor %}
</ul>
</div>
{% else %}
<div class="tab-pane text-left fade show" id="vert-tabs-{{cat}}" role="tabpanel" aria-labelledby="vert-tabs-{{ cat }}-tab">
<ul class="list-unstyled border pb-4">
Now, how I am thinking of a way to get the h ref in the like(h ref="vert-tabs-{{cat}}" I want to get the value of the cat variable anytime I switch to a different sort of view or tab content.
Any help would be so appreciated even JavaScript or j query.
Thank you in advance...
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 %}
I am trying to create a edit form to update the database using Django model Forms but the problem is that edit form part of the sizeProductMap.html page is not rendering when edit form (sizeProductMap_edit) request is made.
My models are as shown below.
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)
def __str__(self):
return "{}-->{}".format(self.prod_ID,
self.prod_Name)
class Size(models.Model):
size_id = models.AutoField("Size ID", primary_key=True, auto_created=True)
prod_size = models.CharField("Product Size", max_length=20, null=False)
def __str__(self):
return "{size_id}-->{prod_size}".format(size_id=self.size_id,
prod_size=self.prod_size)
class SizeProductMapping(models.Model):
size_p_map_id = models.AutoField("Size & Product Map ID", primary_key=True, auto_created=True)
size_id = models.ForeignKey(Size, null=False, on_delete=models.CASCADE, verbose_name="Size ID")
prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")
def __str__(self):
return ".`. {}_____{}".format(self.size_id,
self.prod_id)
This is the form I used to add and edit the model.
forms.py
from django import forms
from user.models import SizeProductMapping
class SizeProductMapForm(forms.ModelForm):
class Meta:
model = SizeProductMapping
fields = ['size_id', 'prod_id']
Here is the view I created to add ,update and delete the record.
views.py
def sizeProductMap(request):
form = SizeProductMapForm(request.POST, request.FILES)
if request.method == 'POST':
if form.is_valid():
form.save()
return redirect("/admin1/sizeProductMap/")
else:
sizeProductMap_show = SizeProductMapping.objects.all()
# start paginator logic
paginator = Paginator(sizeProductMap_show, 3)
page = request.GET.get('page')
try:
sizeProductMap_show = paginator.page(page)
except PageNotAnInteger:
sizeProductMap_show = paginator.page(1)
except EmptyPage:
sizeProductMap_show = paginator.page(paginator.num_pages)
# end paginator logic
return render(request, 'admin1/sizeProductMap.html', {'sizeProductMap_show': sizeProductMap_show, 'form': form})
def sizeProductMap_delete(request, id):
sizeProductMap_delete = SizeProductMapping.objects.filter(size_p_map_id=id)
sizeProductMap_delete.delete()
return redirect('/admin1/productSizeMap')
def sizeProductMap_edit(request, id):
instance = SizeProductMapping.objects.get(size_p_map_id=id)
form = SizeProductMapForm(instance=instance)
if request.method == 'POST':
form = SizeProductMapForm(request.POST, instance=instance)
if form.is_valid():
form.save()
return redirect('/admin1/sizeProductMap')
return render(request, 'admin1/sizeProductMap.html', {'form': form})
This is my urls.
urls.py
from django.urls import path
from admin1 import views
urlpatterns = [
path('sizeProductMap/', views.sizeProductMap, name="admin-size-product-map"),
path('sizeProductMap_delete/<int:id>', views.sizeProductMap_delete, name="admin-size-product-map-delete"),
path('sizeProductMap_edit/<int:id>', views.sizeProductMap_edit, name="admin-size-product-map-edit"),
]
This is the Html page where I want to display the form according to the page request.
sizeProductMap.html
{% extends 'admin1/layout/master.html' %}
{% block title %}Size Product Map{% endblock %}
{% block main %}
<h1>
<center>Size Product Map</center>
</h1>
<div class="container">
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10">
{% if sizeProductMap_show %}
<button type="button" class="btn btn-primary mt-2" data-toggle="modal" data-target="#modal-primary">Add
Size Product Mapping
</button>
<div class="modal fade" id="modal-primary">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Size Product Mapping</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
</div>
<div class="modal-body mt-2">
<form action="{% url 'admin-size-product-map'%}" method="POST"
enctype="multipart/form-data">
{% csrf_token %}
<table border="1" class="table table-bordered border border-info">
<tr>
<th>
{{form.size_id.label_tag}}
</th>
<td>{{form.size_id}}</td>
</tr>
<tr>
<th>
{{form.prod_id.label_tag}}
</th>
<td>
{{form.prod_id}}
</td>
</tr>
</table>
<input type="Submit" name="Submit" value="Submit" class="btn btn-success w-50"><br>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-outline-light" data-dismiss="modal">Close
</button>
</div>
</form>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<div class="container-fluid ">
<div class="row">
<div class="card mt-2 border border-secondary">
<div class="card-header">
<h3 class="card-title ">Size Product Map Table</h3>
</div>
<!-- /.card-header -->
<div class="card-body">
<table class="table table-bordered border border-info">
<thead>
<tr>
<th>Size Product Mapping Id</th>
<th>Product ID</th>
<th>Size ID</th>
<th>Action</th>
</tr>
</thead>
<tbody class="justify-content-center">
{% for x in sizeProductMap_show %}
<tr>
<td>{{x.size_p_map_id}}</td>
<td>{{x.prod_id}}</td>
<td>{{x.size_id}}</td>
<td><a href="{% url 'admin-size-product-map-edit' x.size_p_map_id %}"
class="btn btn-outline-primary mt-2"><i
class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
<a href="{% url 'admin-size-product-map-delete' x.size_p_map_id %}"
class="btn btn-outline-danger mt-2"><i
class="fa fa-trash" aria-hidden="true"></i></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- /.card-body -->
<div class="card-footer clearfix ">
<ul class="pagination pagination-sm m-0 justify-content-center">
{% if sizeProductMap_show.has_previous %}
<li class="page-item"><a class="page-link"
href="?page={{sizeProductMap_show.previous_page_number}}">
Previous </a>
</li>
{% endif%}
{% for x in sizeProductMap_show.paginator.page_range %}
{% if sizeProductMap_show.number == x %}
<li class="page-item active"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% else%}
<li class="page-item"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% endif %}
{% endfor %}
{% if sizeProductMap_show.has_next %}
<li class="page-item"><a class="page-link"
href="?page={{sizeProductMap_show.next_page_number}}">
Next </a>
</li>
{% endif %}
</ul>
</div>
</div>
<!-- /.card -->
</div>
</div>
{% endif %}
{% if sizeProductMap_edit %}
<form action="{% url 'admin-size-product-map-edit' x.size_p_map_id %}" method="POST">
{% csrf_token %}
{{form.size_id}}
{{form.prod_id}}
</form>
{% endif %}
</div>
</div>
</div>
{% endblock %}
And if it is possible to reduce the number of line of code please also help. Thanks in advance.
I've found out the answer. There was a really a silly mistake by me.
In the sizeProductMap.html there is a mistake let me point out that:
sizeProductMap.html
{% if sizeProductMap_edit %}
<form action="{% url 'admin-size-product-map-edit' x.size_p_map_id %}" method="POST">
{% csrf_token %}
{{form.size_id}}
{{form.prod_id}}
</form>
{% endif %}
Here I am checking for instance {% if sizeProductMap_edit %} this is the wrong thing.
I have to check {% if instance %} according to my views.py.
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'm currently working on a project that require Django Forms but I ended up with some issues. My form doesn't display at all ... No field appear on my template.
So my code :
models.py
class Place(models.Model):
name = models.CharField(max_length=255)
longitudeMax = models.DecimalField(max_digits=8, decimal_places = 4 ,blank=True)
longitudeMin = models.DecimalField(max_digits=8, decimal_places = 4, blank=True)
latitudeMax = models.DecimalField(max_digits=8, decimal_places = 4, blank=True)
latitudeMin = models.DecimalField(max_digits=8, decimal_places = 4, blank=True)
datasetPath = models.CharField(max_length=255)
isActive = models.BooleanField(default=True)
def __str__(self):
return self.name
def get_place(self, name):
return None
forms.py
class NewPlaceForm(forms.Form):
name = forms.CharField(
widget=forms.TextInput(
attrs={
"placeholder" : "Name",
"class": "form-control"
}
))
longMax = forms.DecimalField(
widget=forms.NumberInput(
attrs={
"placeholder" : "Longitude Max",
"class": "form-control"
}
))
longMin = forms.DecimalField(
widget=forms.NumberInput(
attrs={
"placeholder" : "Longitude Min",
"class": "form-control"
}
))
latMax = forms.DecimalField(
widget=forms.NumberInput(
attrs={
"placeholder" : "Latitude Max",
"class": "form-control"
}
))
latMin = forms.DecimalField(
widget=forms.NumberInput(
attrs={
"placeholder" : "Latitude Min",
"class": "form-control"
}
))
class Meta:
model = Place
fields = ('name', 'longitudeMax', 'longitudeMin', 'latitudeMax', 'latitudeMin')
views.py
def upload(request):
msg = None
if request.method == "POST":
form = NewPlaceForm(request.POST)
if form.is_valid():
form.save()
msg = 'Place created'
else:
msg = 'Form is not valid'
else:
form = NewPlaceForm()
return render(request, "pages/place_upload.html", {"form": form, "msg" : msg})
urls.py
from django.urls import path, re_path
from app import views
urlpatterns = [
#Data modification page
path('pages/place_modification.html', views.modification, name="place_modification"),
#New place adding page
path('pages/place_upload.html', views.upload, name="place_upload"),
# Matches any html file
re_path(r'^.*\.html', views.pages, name='pages'),
# The home page
path('', views.index, name='home'),
]
html file
<form method="post" action="">
{% csrf_token %}
<div class="card-body">
<div class="row">
<div class="col-md-6 col-lg-4">
<div class="form-group">
<div class="input-group mb-3">
<div class="input-group-prepend">
</div>
{{ form.name }}
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-lg-4">
<div class="form-group">
<div class="input-group mb-3">
<div class="input-group-prepend">
</div>
{{ form.longMax }}
</div>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
</div>
{{ form.longMin }}
</div>
</div >
<div class="col-md-6 col-lg-4">
<div class="input-group mb-3">
<div class="input-group-prepend">
</div>
{{ form.latMax }}
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
</div>
{{ form.latMin }}
</div>
</div>
<div class="col-md-6 col-lg-4">
<div class="form-group form-floating-label">
<small id="emailHelp2" class="form-text text-muted">Use negative numbers for South and positive numbers for North</small>
</div>
<div class="form-group form-floating-label">
<small id="emailHelp2" class="form-text text-muted">Use negative numbers for West and positive numbers for East</small>
</div>
</div>
</div>
</div>
<div class="card-action">
<button type="submit" class="btn btn-success">Submit</button>
<button class="btn btn-danger">Cancel</button>
</div>
</form>
I don't see why it doesn't work and it's been several days that I try to make it work ... Did I do something wrong ? Have I forgot something ? Because I don't feel like I did and it's getting on my nerve ahaha
Django handles the form rendering out of the box, to display a basic form, try:
<form method="POST" action="{% url 'namespaced:url' %}">
{ csrf_token %}
{{ form.as_p }}
<input type="submit" value="submit">
</form>
That said, it looks like you're using bootstrap in your template, you might find the package django-bootstrap4 useful (https://github.com/zostera/django-bootstrap4).
Quick example:
pip install django-bootstrap4
and add bootstrap4 to your installed apps.
Then in your template:
{% load bootstrap4 %}
{# Load CSS and JavaScript #}
{% bootstrap_css %}
{% bootstrap_javascript jquery='full' %}
<form action="{% url 'namespaced:url' %}" method="post" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button type="submit" class="btn btn-primary">
Submit
</button>
{% endbuttons %}
</form>
If you want, you can render each field manually using:
{% bootstrap_field field %}, so you can do things like <div class="col-md-6">{% bootstrap_field my_field %}</div>, to manually arrange your form fields on the page.