I have a Django form that takes input values from users. The values are then used in making query to a table ResourceBase, which finally returns a list of filtered results.
Since the results might be a long list, I added a pagination function with "Prev" and "Next" buttons. My problem is that when I click "Prev" or "Next" button, the form gets restored into default values. And all returned results are all gone. How do I prevent this from happening?
I think the form gets reset because of "form1 = QueryForm()" when a request is not "POST". However I just have difficulty coming up with a neat solution since I'm new to Django and web dev.
In views.py:
def search(request):
if request.method == "POST":
form1 = QueryForm(data=request.POST)
layer_dict = []
if form1.is_valid():
inp_ct = form1.cleaned_data['country']
q1 = ResourceBase.objects.filter(country_name__iexact=inp_ct)
for layer in q1:
down_url = 'xxxxxxx'.format(layer.title)
view_url = 'xxxxxxx'.format(layer.title)
layer_dict.append((layer.title, down_url, view_url))
layer_dict = sorted(layer_dict, key = lambda x:x[0])
paginator = Paginator(layer_dict, 10)
page = request.GET.get('page', 1)
try:
layers = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
layers = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
layers = paginator.page(paginator.num_pages)
context = {'form1': form1, 'layers': layers}
else:
form1 = QueryForm()
context = {'form1': form1}
return render(request, 'my_app/search.html', context)
In search.html:
<br />
<h3>Pagination Test</h3>
<br /><br/>
<div class="row">
<div class="col-md-4">
<form method="POST">
{% csrf_token %}
<div class="form-controls">
{{ form1|as_bootstrap }}
</div>
<button class="btn btn-primary" type="submit" style="float: right;" title = "Click to search" ><i class="fa fa-search"></i></button>
</form>
<form method="GET">
<button class="btn btn-primary" type="submit" value="Reset" name="Reset" title="Reset all choices">Reset</button>
</form>
</div>
</div>
{% if layers %}
<div class="row">
<div class="col-md-8">
<div id = "search_results" >
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Select</th>
<th scope="col">Layer Name</th>
<th scope="col">Download</th>
<th scope="col">View Layer</th>
</tr>
</thead>
<tbody>
{% for layer in layers %}
<tr>
<td><input class= messageCheckbox type="checkbox" name="checks" value="{{layer.1}}"/></td>
<td>{{layer.0}}</td>
<td> Download Layer </td>
<td><input class="btn btn-primary" onclick="window.open('{{layer.2}}')" id="view" type="button" name="view" value="View"></td>
</tr>
{% endfor %}
<tr>
<td><input type="checkbox" onClick="toggle(this, 'checks')"/> Select All</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<button class="btn btn-primary" type="button" name="download" style="float: left;" onClick= "open_all_links();">Download Selected</button>
</div>
<div class="a_pagination" align="right">
<span class="step-links">
{% if layers.has_previous %}
<a class="btn btn-primary btn-sm" name="prev_page" href="?page={{ layers.previous_page_number }}" role="button">Prev.</a>
{% endif %}
<span class="current" style ="color:#2C689C;font-size:16px;padding:8px;">
page {{ layers.number }} of {{ layers.paginator.num_pages }}
</span>
{% if layers.has_next %}
<a class= "btn btn-primary btn-sm" href="?page={{ layers.next_page_number }}" role="button">Next</a>
{% endif %}
</span>
</div>
</div>
</div>
{% endif %}
<script type="text/javascript" >
.......
</script>
You don't need to use POST Method to pass your arguments to your views.py .
Follow the below example and rewrite your view and your html form.
here a simple form for user to enter the word for search:
<form method="get" action="">
<input type="text" name="search4" class="search_input" placeholder="Search" required="required">
<input type="submit" value="Search">
</form>
The next step is that you should check the input in your views.py, we named the input tage name="search4" so we check if there is any input in our form using this code in our views.py:
from django.db.models import Q
from django.core.paginator import Paginator
def search(request):
query = request.GET.get("search4")
if query:
queryset = ResourceBase.objects.objects.all() # this will get all of your object of your model
results = queryset.filter(Q(country_name__iexact=query)).all()
number_of_objects = results.count() # get the exact number of object to show in your html file
paginator = Paginator(results, 12) # Show 12 contacts per page
page_var = 'page' # this will use for pagination in your html file
page = request.GET.get(page_var) # this will use for pagination in your html file
contacts = paginator.get_page(page) # send only 12 object to your html file to show to user
context = {
"items": contacts,
"key": str(query),
'page': page_var,
"number_of_objects": number_of_objects,
}
return render(request=request, template_name='search.html', context=context, content_type=None, status=None,
using=None)
else:
... # if user didn't enter anything to search
After getting and searching the user input in your data base, You should show it to user in your search.html file like this:
{% for item in items %}
<div>
<div>
<div class="product_title">{{ item.title }}</div> # show the part that you want the users to see
... # rest of your item parts to show
</div>
</div>
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if items.has_previous %} # check the pagination that if there is perivious pages
« first
previous
{% endif %}
<span class="current">
Page {{ items.number }} of {{ items.paginator.num_pages }} # example of result : Page 1 of 13
</span>
{% if items.has_next %}
<a href="?{{ page }}={{ items.next_page_number }}"</a> # check the pagination that if there is any next or perivious pages
last » # a link to last page
{% endif %}
</span>
{{ pagination }}
this is a basic search page with Paginator, if you need any further help or question, I will be happy to help.
The code <a class= "btn btn-primary btn-sm" href="?page={{ layers.next_page_number }}" role="button">Next</a> will indeed GET the page and the form1 = QueryForm() code will result in empty form. You are on a right track here.
You have two options:
1) Change the next/prev buttons so that they are inside the form1 form and they POST stuff. It might be challenging to move them inside the same form tag.
If you target modern browsers you can use HTML5 form tag in submit (https://www.w3schools.com/tags/att_button_form.asp).
<form method="POST" id="form1">
{{ form1|as_bootstrap }}
</form>
... outside the form tag, then
<button class="btn btn-primary btn-sm" form="form1" name="next" value="{{ layers.next_page_number }}" role="button">Next</button>
You should have in request.POST the next value.
2) Initialize the QueryForm from GET params.
form1 = QueryForm(data=request.GET)
and include the form parameters into the url. For this you would need some Javascript (for example How to use an input field as query parameter to a destination?) as Django doesn't know about the values in the form on rendering time before user inserts them.
You can change the pagination links into buttons to submit the form. More detailed answer in here:
How to define which input fields the form has by pressing different buttons?
You can read my comment on the answer. It explains how the answer can be helpful in pagination.
I modified the pagination code I found in https://simpleisbetterthancomplex.com/series/2017/10/09/a-complete-beginners-guide-to-django-part-6.html
The modified code for pagination is also as below:
<nav aria-label="Topics pagination" class="mb-4">
<ul class="pagination">
{% if page_obj.has_previous %}
<li class="page-item">
<button form="my_form" name="page" value="{{page_obj.number|add:'-1'}}" role="button" class="btn btn-link">Previous</button>
</li>
{% else %}
<li class="page-item disabled">
<span class="page-link">Previous</span>
</li>
{% endif %}
{% for i in page_obj.paginator.page_range %}
{% if page_obj.number == i %}
<li class="page-item active">
<span class="page-link">
{{ i }}
<span class="sr-only">(current)</span>
</span>
</li>
{% else %}
<li class="page-item">
<button form="my_form" name="page" value="{{i}}" role="button" class="btn btn-link">{{ i }}</button>
</li>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<li class="page-item">
<button form="my_form" name="page" value="{{page_obj.number|add:1}}" role="button" class="btn btn-link">Next</button>
</li>
{% else %}
<li class="page-item disabled">
<span class="page-link">Next</span>
</li>
{% endif %}
</ul>
</nav>>
Related
I am currently using a page that has a list of in-line forms
However when the user enters submits each form (line) they are sent back to the top of the page. This becomes really tedious as the users need to enter data quickly and can't when they need to scroll for 2 minutes every time they add an entry.
Does anyone know how to implement a scroll lock to stock this from happening
Views.py: Function:
class AvonleaView( View):
def get(self,request):
created_nums= AvonleaClass.objects.all().values('unitNumber')
Aprev = AvonleaClass.objects.all().order_by('-unitDateEntered')
# created_nums= AvonleaClass.objects.all()
print(created_nums )
created_nums =[int(i['unitNumber']) for i in created_nums]
print(created_nums )
form = AvonleaForm()
return render(request,"meter_readings/avonlea.html",{'form':form , 'created_nums':created_nums })
def post(self,request):
created_nums= AvonleaClass.objects.all().values_list('unitNumber')
print(created_nums)
form = AvonleaForm(request.POST)
if form.is_valid():
form.save()
return redirect('Avonlea')
messages.success(request , 'creates successfully ')
else:
return render(request, 'meter_readings/avonlea.html', {'form': form , created_nums:created_nums })
HTML page :
{% extends 'meter_readings/base.html' %}
{% block content %}
<!-- CSS only -->
<div class="container" font-size= 8px>
<center><h1>Avonlea Meter Readings</h1></center>
<br>
<head>
<meta name="viewport" content="width=device-width">
</head>
{% for unit_number in form.unitNumber %}
<h6>{{ error }}</h6>
<form class="form-group mt-4" method="post" {% if unit_number.data.value in created_nums %} style="background-color: rgb(231, 224, 224); " {% endif %} >
{% csrf_token %}
<div class="container">
<div class="row mb-3">
<div class="col">
<h5 style="font-size: 14px"> Unit number </h5>
{{ unit_number.data.value}}
</div>
<input type="hidden" name="unitNumber" value="{{unit_number.data.value}}">
<div class="col" id="prev{{unit_number.data.value}}" >
<h5 style="font-size: 14px"> Previous Reading </h5>
{{ previousReading }}
</div>
<div class="col" id="readings{{unit_number.data.value}}">
<h5 style="font-size: 14px"> Current Reading </h5>
{{ form.newReading }}
</div>
<div class="col" id="difference{{unit_number.data.value}}">
<h5 style="font-size: 14px"> Units Used </h5>
{{ form.difference }}
</div>
<div class="col" id="img{{unit_number.data.value}}">
{{ form.image }}
</div>
<div class="col">
<button id="form.id" class="btn btn-success " type="submit" {% if unit_number.data.value in created_nums %} disabled {% endif %} > Save</button>
</div>
</div>
</div>
</form>
{% endfor %}
<br>
<br>
If I understand correctly, you can add #<some_id> to the action attribute of your forms and when the page loads the browser will automatically put the element with the id="some_id" in view.
Example:
<form id="form1" action="#form2" method='POST'>...</form>
...
<form id="form2" action="" method='POST'>...</form>
If you submit #form1 when the page reloads the browser will scroll to #form2 even if it's at the bottom of the page.
Or if you only have one form, you can do:
<form id="form1" action="#form1" method='POST'>...</form>
EDIT:
<form id="form{{forloop.counter0}}" action="#form{{forloop.counter}}" class="form-group mt-4" method="post" {% if unit_number.data.value in created_nums %} style="background-color: rgb(231, 224, 224); " {% endif %} >
I'm a new face to Django so please be considerate to if ever my problem is something stupid. So I have been practicing Django, I've run into problems with tegards to NoReverseMatch, I went through answers in stackoverflow but still I couldn't find where I went wrong. Can you help me a bit guys?
views.py
#login_required(login_url="admin-login")
#user_passes_test(check_role_admin)
def colorProductMap_edit(request, id):
instance = ColorProductMapping.objects.get(color_p_map_id=id)
print(instance.color_id)
form = ColorProductMapForm(instance=instance)
if request.method == 'POST':
form = ColorProductMapForm(request.POST, instance=instance)
if form.is_valid():
form.save()
return redirect('/admin1/colorProductMap')
else:
form = ColorProductMapForm(instance=instance)
return render(request, 'admin1/colorProductMap.html', {'form': form, 'instance': instance})
I properly partnered and connected with the following in my urls.py.
urls.py
path('colorProductMap_edit/<int:id>', views.colorProductMap_edit, name="admin-color-product-map-edit"),
forms.py
class ColorProductMapForm(forms.ModelForm):
class Meta:
model = ColorProductMapping
fields = ['color_id', 'prod_id']
models.py
class ColorProductMapping(models.Model):
color_p_map_id = models.AutoField("Color & Product Map ID", primary_key=True, auto_created=True)
color_id = models.ForeignKey(Color, null=False, on_delete=models.CASCADE, verbose_name="Color ID")
prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")
colorProductMap.html
{% extends 'admin1/layout/master.html' %}
{% block title %}Color Product Map{% endblock %}
{% block main %}
<h1>
<center>Color Product Map</center>
</h1>
<div class="container">
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10">
{%if colorProductMap_show%}
<button type="button" class="btn btn-primary mt-2" data-toggle="modal" data-target="#modal-primary">Add
Color 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 Color 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-color-product-map'%}" method="POST"
enctype="multipart/form-data">
{% csrf_token %}
<table border="1" class="table table-bordered border border-info">
<tr>
<th>
{{form.color_id.label_tag}}
</th>
<td>{{form.color_id}}</td>
</tr>
<tr>
<th>
{{form.prod_id.label_tag}}
</th>
<td>
{{form.prod_id}}
</td>
</tr>
</table>
<div class="modal-footer justify-content-right">
<input type="Submit" name="Submit" value="Submit" class="btn btn-outline-success">
<button type="button" class="btn btn-outline-danger" 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 ">Color Product Map Table</h3>
</div>
<!-- /.card-header -->
<div class="card-body">
<table class="table table-bordered border border-info">
<thead>
<tr>
<th>Color Product Mapping Id</th>
<th>Product ID</th>
<th>Color ID</th>
<th>Action</th>
</tr>
</thead>
<tbody class="justify-content-center">
{% for x in colorProductMap_show %}
<tr>
<td>{{x.color_p_map_id}}</td>
<td>{{x.prod_id}}</td>
<td>{{x.color_id}}</td>
<td><a href="{% url 'admin-color-product-map-edit' x.color_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-color-product-map-delete' x.color_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 colorProductMap_show.has_previous %}
<li class="page-item"><a class="page-link"
href="?page={{colorProductMap_show.previous_page_number}}">
Previous </a>
</li>
{% endif%}
{% for x in colorProductMap_show.paginator.page_range %}
{% if colorProductMap_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 colorProductMap_show.has_next %}
<li class="page-item"><a class="page-link"
href="?page={{colorProductMap_show.next_page_number}}">
Next </a>
</li>
{% endif %}
</ul>
</div>
</div>
<!-- /.card -->
</div>
</div>
{%endif%}
{% if instance %}
<form action="{% url 'admin-color-product-map-edit' x.color_p_map_id %}" method="POST"
enctype="multipart/form-data">
{% csrf_token %}
<table border="1" class="table table-bordered border border-info">
<tr>
<th>
{{form.color_id.label_tag}}
</th>
<td>{{form.color_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>
{% endif %}
</div>
</div>
</div>
{% endblock %}
What am I doing wrong? I think I have followed every advice I could find, but yeah it still gives me the error. Any help is appreciated. Thank you very much!
You write your form tag as:
<form action="{% url 'admin-color-product-map-edit' x.color_p_map_id %}" method="POST"
enctype="multipart/form-data">
After observing your template and view it appears that you are using the same template for multiple views and this is causing confusion. As I note in the comment there is no x in the context for this view (In the other one you loop over a variable which doesn't exist in this view to get this). After looking a bit more one notices that by this {% url 'admin-color-product-map-edit' x.color_p_map_id %} you want to point to the current url itself. If a forms action is to the same url the best thing to do is forego the action attribute completely (If there is no action attribute the request would be to the same url as the page user is in):
<form method="POST" enctype="multipart/form-data">
Thanks all to guide me, I have found my mistake.
In the html template, as shown below
<form action="{% url 'admin-color-product-map-edit' x.color_p_map_id %}" method="POST"
enctype="multipart/form-data">
Here I am using x.color_p_map_id where x is not any iterable object so the error I was getting.
Now I have made a change and used instance instead of x in above url and now its working fine.
<form action="{% url 'admin-color-product-map-edit' instance.color_p_map_id %}" method="POST"
enctype="multipart/form-data">
Hey i am new to Django and I am trying to make a search bar to my first site.
My problem here is when I search for any value that I/user entered and on the site, the site only refreshes and doesn't give me anything back but the empty option that i gave the site to display when there is no content to match the search.
(That's not all of the Topic model)
model.py
class Topic(models.Model):
content = models.CharField(max_length=200)
views.py
def search(request):
query = request.GET.get('q')
if query:
result = Topic.objects.filter(content__icontains=query)
context = { 'query': query, 'result': result}
return render(request, 'learning_logs/topics.html', context)
(that's all of the topics.html i am sorry of how it turned this not what it really looks like on the original topics.html but that's the full topics.html )
topics.html
% extends "leaning_logs\base.html" %}
{% block page_header %}
<h1>Topics </h1>
<br>Add a new topic</br>
{% endblock page_header %}
{% block content %}
<form method="GET" action="{% url 'learning_logs:search' %}">
{% csrf_token %}
<input name="q" value="{{ request.GET.q }}" placeholder="search..">
<button class="btn btn-success" type="submit">
Search</button>
</form>
{% for topic in topics %}
<div class="card-mb3">
<div class="card-header" style="background-color:lightgrey">
<table class="table">
<tr>
<th>Image</th>
<th>Title of the topic</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<div class="card-body" style="background- color:white">
<tr>
<td>
{% if topic.image %}
<image src="{{topic.image.url}}" style="width:200px">
{% else %}
<span class="text-muted">No Image have been added</span>
{% endif %}
<td><h3>
{{topic}}
</td></h3>
<td><small><a href="{% url 'learning_logs:edit_topic' topic.id %}">
<button method="submit" class="btn btn-primary">
Edit topic</button></a></small></td>
<td><small><form method="post" action="{% url 'learning_logs:delete_topic' topic.id %}">
<button type="submit" class="btn btn-danger btn-primary" >
Delete topic</button></form></small></td>
</tr>
</div>
</div>
</div>
{% empty %}
<h3><li>No topics have been added yet.</li></h3>
{% endfor %}
{% endblock content %}
This:
{% for topic in topics %}
should be that:
{% for topic in result %}
I am working on a django application. The application holds a form which when filled will redirect to item_list page where the user can view the item they posted and also delete the item. I want this page to list only the items posted by that particular user who is currently logged in. but right now, this page lists items by every user. I tried adding an if case to the template but this results in displaying none of the posts. what am I doing wrong? this is my code so far
items_list template
{% extends 'base.html' %}
{% load staticfiles %}
{% block title %} items {% endblock title %}
{% block header %}
<link rel="stylesheet" href="{% static 'css/item_list.css' %}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="{% static 'js/item_list.js' %}"></script>
{% endblock header %}
{% block content %}
<div class="container">
<center><h2>Items</h2></center>
<table class='table table-borderless table-hover'>
<thead>
<tr>
<th>Image</th>
<th>Title</th>
<th>Pattern</th>
<th>Color</th>
<th>Vendor</th>
<th>Upload date</th>
<th>Time</th>
<th></th>
<th></th>
</tr>
</thead>
{% for item in items %}
{% if request.user == item.vendor %}
<tr>
<td>
<img src="{{item.img.url}}" alt="{{item.title}}" style="width:80px;">
</td>
<td>{{item.title}}</td>
<td>{{item.pattern}}</td>
<td>{{item.color}}</td>
<td>{{item.vendor}}</td>
<td>{{item.date}}</td>
<td>{{item.time}}</td>
{% endif %}
<td>
Edit item
</td>
<td>
<button class="btn btn-danger btn-sm" data-toggle="modal" data-target="#myModal" style="width:100px">Delete item</button>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="card-header"><center><h5 class="modal-title">Are you sure you want to delete this item?</h5></center></div>
<div class="modal-body" style="height:200px">
<center>
<br>
<form method="post" action="{% url 'delete_item' item.pk %}" style="margin-top:10%;">
{% csrf_token %}
<button type='submit' class="btn btn-danger" style="width:200px">Delete item</button>
<button type="button" class="btn btn-outline-primary" data-dismiss="modal" style="width:200px">Cancel</button>
</form>
</center>
</div>
<div class="card-footer text-muted">
<center>Once an item is deleted, It cannot be retrieved</center>
</div>
</div>
</div>
</div>
</td>
I am trying to filter the items based on request.user and item.vendor. But this displays none of the items.
views.py
def upload_item(request):
if request.method == 'POST':
form_des = ItemForm(request.POST, request.FILES)
if form_des.is_valid():
form_des.save()
return redirect('item_list')
else:
form_des = ItemForm()
form_des.fields['vendor'].widget.attrs['value'] = request.user
form_des.fields['vendor'].widget.attrs['readonly'] = True
return render(request, 'upload_item.html', {'form_des': form_des})
def item_list(request):
items = Item.objects.all()
return render(request, 'item_list.html', {'items':items})
under upload_item function in views.py, I have made the vendor field readonly and autofilled to the user posting the item so that it cannot be changed.
What am I doing wrong? Please help me
Thank you
You should do the filtering in your view:
def item_list(request):
items = Item.objects.filter(vendor=request.user)
return render(request, 'item_list.html', {'items':items})
I'm Creating Small Size of Web Interface.I created the edit button in Web Interface.But ,it's not working.It Creating as a new Entry in Database.Can anyone help me.One more thing is How to retrieve the values from database while editing existing values.Thanks for advanced.
Here is The Python Code:
class UserForm(FlaskForm):
type=StringField('type')
#app.route('/newuser', methods=['GET', 'POST'])
def add_user():
form = UserForm()
if form.validate_on_submit():
user_details = {
'type': form.type.data
}
sqlsession.add(user_details)
return redirect(url_for('vehicle_type'))
return render_template('vehicletype.html', form=form)
#app.route('/control/edit/<int:id>',methods=['POST','GET'])
def edit(id):
qry=sqlsession.query(Vehicletype).filter(Vehicletype.id==id).first()
form = UserForm(request.form, object=qry)
if form.validate_on_submit():
form.populate_obj(qry)
sqlsession.update(qry)
sqlsession.commit()
return redirect(url_for('vehicle_type'))
return render_template('vehicletype.html', form=form)
Here is the Templates of the vehicletype.html Code:
{% extends "base.html" %}
{% block head %}
{{super()}}
{% endblock %}
{% block navbar %}
{{super()}}
{% endblock %}
{% block content %}
<div class="row">
<ol class="breadcrumb">
<li><a href="#">
<em class="fa fa-home"></em>
</a></li>
<li class="active">Vehicletype > Create Vehicletype</li>
</ol>
</div><!--/.row-->
<div class="row">
<div class="col-md-6">
<form role="form" action="/post/vehicletype" method="post">
<div class="form-group">
<label>VehicleType: </label>
<input name="type" class="form-control" placeholder="enter vehicletype">
</div>
<input type="submit" class="btn btn-primary" value="Submit ">
<input type="reset" class="btn btn-default" value="Reset">
</form>
</div>
</div>
{% endblock %}
Here is the vehicletypedetails.html code:
{% extends "base.html" %}
{% block head %}
{{super()}}
{% endblock %}
{% block navbar %}
{{super()}}
{% endblock %}
{% block content %}
<div class="row">
<ol class="breadcrumb">
<li><a href="#">
<em class="fa fa-home"></em>
</a></li>
<li class="active">Vehicletype>View</li>
</ol>
</div><!--/.row-->
<div class="row">
<div class="col-md-12">
<table class="table table-striped table-hover">
<thead>
<tr>
<th>
Id
</th>
<th>
VehicleType
</th>
<th>
Dateofsub
</th>
<!--<th>
Control
</th>-->
<th>
Delete
</th>
</tr>
</thead>
{% for values in vehicletype %}
<tr>
<th>{{values.id}}</th>
<td>{{values.type}}</td>
<td>{{values.dateofsub}}</td>
<!--<td>Reset Password</td>-->
<td>Delete</td>
<td>edit</td>
</tr>
{% endfor %}
</table>
<em class="fa fa-xl fa-plus-circle color-blue" ></em>
</div>
</div>
{% endblock %}
I have been trying to solve this issue for 6 days .But I Could not find any solution. Please could you help me anyone.
Your code to edit an existing entry has a route of /control/edit/<int:id>, but your form you're using to submit the user-changes is pointing at a different route located at /post/vehicletype.
You'll need to change your return from:
return render_template('vehicletype.html', form=form)
to:
return render_template('vehicletype.html', form=form, car_id=id)
And then change your html code from:
<form role="form" action="/post/vehicletype" method="post">
to:
<form role="form" action="{{ url_for('edit', id=car_id) }}" method="post">
With that in place, your form code will be getting submitted to the correct route for processing.