why the form is invalid on post - python

I have records in my model. I want to list the existing records and edit and add more records. I successfully got the records to my template and edit. I can add new records also. it is working fine in template. But when I post the form is invalid and print invalid message as per my code http response. I can not figure out what is the mistake. Please advise.
forms.py:
class NewTransForm(forms.ModelForm):
th_no = forms.DecimalField(max_digits=5,error_messages={"max_digits":"Transaction number
should be less than 6 digits.","unique":"Transaction number already exists."})
class Meta:
model = TransHeader
fields = ['th_no','th_dt','th_type', 'th_code','th_cust_code','th_sm_code','th_ref']
...
urls.py:
path('edit_sales_transaction_details/<int:trans_id>/',views.EditSalesTransaction,
name="edit_sales_transaction"),
views.py:
def EditSalesTransaction(request,trans_id):
# template_name= "wstore/edit_sales_transheader_input.html.html"
# trans_id =kwargs['trans_id']
if request.method == "POST":
print(request.POST)
form = NewTransForm(request.POST)
if form.is_valid():
# trans_id =kwargs['trans_id']
exist_trans_header = TransHeader.objects.get(id=int(trans_id))
TransBody.objects.filter(trans_header=exist_trans_header).delete()
exist_trans_header.delete()
obj = form.save()
books = request.POST.getlist('book_code')
quantities = request.POST.getlist('quantity')
prices = request.POST.getlist('price')
for book_code,quantity,price in zip(books,quantities,prices):
try:
book = TextBook.objects.get(code=book_code)
TransBody.objects.create(trans_header_id=obj.id,quantity=quantity,price=price,book=book)
except Exception as e:
print(e)
if request.POST.get('save_home'):
return redirect('saltransactions')
else:
print(NewTransForm.errors)
# return redirect(reverse('view_sales_transaction', kwargs=kwargs['trans_id']))
return HttpResponse("form is invalid.. this is just an HttpResponse object")
else:
form = NewTransForm()
context = {}
# trans_id =kwargs['trans_id']
context['trans_header'] = TransHeader.objects.get(id=int(trans_id))
trans_body = TransBody.objects.filter(trans_header=context['trans_header'])
context['trans_body'] = trans_body
context['total_quantity'] = trans_body.aggregate(Sum('quantity'))
context['total_price'] = trans_body.aggregate(Sum('price'))
context['current_date'] = datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d")
context['form'] = form
return render(request, 'wstore/edit_sales_transheader_input.html', context)
...
edit_sales_transheader_input.html:
{% block content %}
<form action="" method="post" class="w-auto" id="new_trans_form"
xmlns:width="http://www.w3.org/1999/xhtml">
<div class="row mt-1 mb-4" >
<div class="col-md-12">
<div>
<div class="headerctr">
<h3>Sales</h3>
<!-- <div> -->
<!-- <h3 > -->
<!-- </h3> -->
</div>
<div class="card-body">
{% csrf_token %}
<div 38rem class="row style= width:18">
<div class="col">
<label>Transaction Date</label>
<input type="date" class="form-control" name="{{form.th_dt.name}}"
value="{{current_date}}"
readonly>
{% if form.th_dt.errors %}
{% for error in form.th_dt.errors %}
<small class="text-danger">{{error}}</small>
{% endfor %}
{% endif %}
</div>
<div class="col-sm" >
<label>Transaction Number</label>
<input type="number" class="form-control" name="{{form.th_no.name}}"
value="{{trans_header.id}}" readonly>
{% if form.th_no.errors %}
{% for error in form.th_no.errors %}
<small class="text-danger">{{error}}</small>
{% endfor %}
{% endif %}
</div>
<div class="col">
<label>Transaction Type</label>
<input type="hidden" class="form-control" name="{{form.th_type.name}}"
required readonly
value="INV">
{% if form.th_type.errors %}
{% for error in form.th_type.errors %}
<small class="text-danger">{{error}}</small>
{% endfor %}
{% endif %}
<label>Transaction Ref.</label>
<input type="text" class="form-control" name="{{form.th_ref.name}}" required
value="{{trans_header.th_ref}}">
{% if form.th_ref.errors %}
{% for error in form.th_ref.errors %}
<small class="text-danger">{{error}}</small>
{% endfor %}
{% endif %}
</div>
</div>
<div class="row mt-0">
<div class="col">
<label>Transaction Code</label>
<input type="text" class="form-control" name="{{form.th_code.name}}" required
readonly
value="POS INV">
{% if form.th_code.errors %}
{% for error in form.th_code.errors %}
<small class="text-danger">{{error}}</small>
{% endfor %}
{% endif %}
</div>
<div class="col">
<label>Transaction Customer Code</label>
<input type="text" class="form-control" name="{{form.th_cust_code.name}}"
required
value="{{trans_header.th_cust_code}}">
{% if form.th_cust_code.errors %}
{% for error in form.th_cust_code.errors %}
<small class="text-danger">{{error}}</small>
{% endfor %}
{% endif %}
</div>
<div class="col">
<label>Transaction Salesman</label>
<input type="text" class="form-control" name="{{form.th_sm_code.name}}"
required
value="{{trans_header.th_sm_code}}">
{% if form.th_sm_code.errors %}
{% for error in form.th_sm_code.errors %}
<small class="text-danger">{{error}}</small>
{% endfor %}
{% endif %}
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12 mt-0">
<div class="card shadow">
<div class="card-header text-center">
<h3 class="headerctr">
Item Details
</h3>
</div>
<div class="card-body">
{% csrf_token %}
<table class="">
<thead class="thead-light">
<tr>
<th>Code</th>
<th class = "text-danger">Description</th>
<th>Quantity</th>
<th class = "text-danger">Price</th>
<th class="text-success">Total Price</th>
<th class = "text-warning">Actions</th>
</tr>
</thead>
<tbody id="books_list" style="margin-bottom: 0">
{% for book in trans_body %}
<tr>
<td>
<input type="text" name="book_code" class="form-control
book_code"
placeholder="Book Code" value="{{book.book.code}}"
required>
</td>
<td>
<input type="text" name="book_name" class="form-control
book_name"
placeholder="Book Name" value="{{book.book.name}}"
readonly>
</td>
<td>
<input type="number" class="form-control quantity"
name="quantity"
placeholder="Quantity" value="{{book.quantity}}"
required>
</td>
<td>
<input type="text" class="form-control org_price"
placeholder="Price"
value="{{book.price}}" readonly >
</td>
<td>
<input type="hidden" class="org_price">
<input type="text" class="form-control price" name="price"
placeholder="Total Price"
value="{{book.price}}" readonly>
</td>
<td>
<div class="btn-group">
<button type="button" id="btnadd" class="btn add_new_row"
title="Add">
<i class="fas fa-plus-square"></i>
</button>
<button type="button" class="btn delete_row"
title="Delete">
<i class="fas fa-trash"></i>
</button>
</div>
</td>
</tr>
{% endfor %}
<tr id="newitem">
<td>
<input type="text" name="book_code" class="form-control book_code"
placeholder="Book Code" required>
</td>
<td>
<input type="text" name="book_name" class="form-control book_name"
placeholder="Book Name" readonly>
</td>
<td>
<input type="number" class="form-control quantity" name="quantity"
placeholder="Quantity" value="0" required>
</td>
<td>
<input type="text" class="form-control org_price" placeholder="Price"
value="0" readonly>
</td>
<td>
<input type="hidden" class="org_price">
<input type="text" class="form-control price" name="price" placeholder="Total Price"
value="0" readonly>
</td>
<td>
<div class="btn-group">
<button type="button" id="btnadd" class="btn add_new_row"
title="Add">
<i class="fas fa-plus-square"></i>
</button>
<button type="button" class="btn delete_row" title="Delete">
<i class="fas fa-trash"></i>
</button>
</div>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td></td>
<td></td>
<td class = "text-success">Total Quantity: <strong
id="final_quantity">0</strong></td>
<td></td>
<td class = "text-success"> Total Price: <strong
id="final_price">0</strong></td>
</tr>
</tfoot>
</table>
</div>
<div class="col-md-12 mb-1">
<div class="btn-group">
<a href="{% url 'saltransactions' %}" class="btn btn-info mr-2" >Cancel</a>
{# <input type="submit" class="btn btn-info mr-2" name="save_home"
value="Hold">#}
<input type="submit" class="btn btn-info submit_form" name="save_next"
value="Save&Print">
</div>
</div>
</div>
</div>
</div>
</form>
{% endblock %}
...

Related

How to add comment without refreshing the page itself in django

I was making a blog website, I am new to django and I don't know how to add comment without refreshing the page itself. I was trying to do with the help of tutorial but they are not helping anymore
here is my html file
<div class="row">
<div class="comment-section col-8">
{% for i in data %}
<li>{{i}}</li><br>
{% endfor %}
</div>
<div class="col-4">
<h4 class="m-3">{{comments.count}} Comments...</h4>
{% for j in comments %}
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">{{j.title}}</h5>
<h6 class="card-subtitle mb-2 text-muted">{{j.visitor.name}}</h6>
<p class="card-text">{{j.description}}</p>
</div>
</div>
{% endfor %}
<hr>
<h3>Comment here</h3>
<form method="post" id="comment-form">
{% csrf_token %}
<input type="hidden" id="contentId" name = 'contentId' value="{{ result.id }}">
<div class="form-group">
<input type="hidden" id="name" name="name" class="form-control" value="{{request.session.user.name}}" readonly>
</div>
<div class="form-group">
<label for="title">Title</label>
<input type="text" id="title" name="title" class="form-control">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" id="description" cols="30" rows="5" class="form-control"></textarea>
</div>
<button type="submit" class="btn btn-secondary">Submit</button>
</form>
</div>
here is my views.py file
def addComment(request):
if request.method == 'POST':
post_id = request.POST['contentId']
title = request.POST['title']
description = request.POST['description']
user = request.session['user']['id']
con = Comment(
post_id=post_id,
title=title,
description=description,
visitor_id=user,
)
con.save()
print()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

Get pk_id using function based view

I'm having a problem in getting the pk in my template. When I select a record it always returns the last pk ID. Btw, I'am using functional base view. Here's my collection.html:
<form method="POST" action="{% url 'single_collection' %}">
{% csrf_token %}
<table class="table" id="dataTables-example">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Status</th>
<th>Download</th>
</tr>
</thead>
<tbody>
{% for collectionlist in collection %}
<tr>
<td>{{ collectionlist.id }}</td>
<td>{{ collectionlist.sqa_name }}</td>
<td>{{ collectionlist.status }}</td>
<td class="center"><center><button type="button" class="btn btn-link" data-toggle="modal" data-target="#myModaldl{{ collectionlist.id }}" ><span class="glyphicon glyphicon-download-alt"></span></button></center></td>
</tr>
<div class="modal fade collectClass" id="myModaldl{{ collectionlist.id }}" role="dialog" tabindex="-1">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Single Collect</h3>
</div>
<div class="modal-body form-horizontal">
<div class="form-group">
<label for="inputSQAID" class="col-sm-3 control-label">SQA Name</label>
<div class="col-sm-8">
<input type="hidden" name="pk_id" id="pk_id" value="{{ collectionlist.id }}">
<input type="text" class="form-control" name="singlecollect" value="{{ collectionlist.sqa_name }}" id="inputSQAID">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-warning" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-success" name="single_dl">Download</button>
</div>
</div>
</div>
</div>
{% endfor %}
</tbody>
</table>
</form>
Here's my views.py:
def collection(request):
context = {
'collection': DataCollection.objects.all(),
'title': 'Data Collection',
}
return render(request, 'data_collection/collection.html', context)
def single_collect(request):
if request.method == 'POST':
pkid = request.POST.get('pk_id')
print(pkid)
all_data = DataCollection.objects.all()
return render(request, 'data_collection/collection.html', {'title' : 'Data Collection', 'data': all_data})
In my views.py, I just want first to print the pk ID of the item/record I selected in my table using the modal. But, it's always getting the last record in my database.
This is because you have a single <form> tag with all the DataCollection rows inside. You should have individual forms for each one, i.e.:
{% for collectionlist in collection %}
<form method="POST" action="{% url 'single_collection' %}">
{% csrf_token %}
...
</form>
{% endfor %}

Bootstrap modal not updating modal content

I am trying to create a table of models with a button next to them which opens a modal and has the same model row in form view. The table is being populated correctly, but the n number of bootstrap modals being created only hold the first iterable model value. Is it because bootstrap loads the content of the modals only once when the page is rendered ? What do I do to solve the problem ? Should I run a function to update the modal content according to the model data it has ??
Feel free to ask any more clarifications.
{% extends 'base.html' %}
{% load static %}
{% block content %}
<table>
{% for item in data %}
<tr>
<th>From</th>
<th>To</th>
<th>Weight</th>
<th>Length</th>
<th>Type</th>
<th>Material Type</th>
<th>Number of Trucks</th>
<th>Loading Time</th>
</tr>
<tr>
<td>{{ item.From }}</td>
<td>{{ item.To }}</td>
<td>{{ item.Weight }}</td>
<td>{{ item.Length }}</td>
<td>{{ item.Type }}</td>
<td>{{ item.MaterialType }}</td>
<td>{{ item.Numberoftrucks }}</td>
<td>{{ item.Loadingtime }}</td>
<td>
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Bid
now! for id {{ item.id }} </button>
</td>
{# {% endfor %}#}
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<input class="form-control" id="disabledInput" type="text"
placeholder="Disabled input here..." value="{{ item.To }}" disabled>
<input class="form-control" id="disabledInput" type="text"
placeholder="Disabled input here..." value="{{ item.From }}" disabled>
<input class="form-control" id="disabledInput" type="text"
placeholder="Disabled input here..." value="{{ item.Weight }}" disabled>
<input class="form-control" id="disabledInput" type="text"
placeholder="Disabled input here..." value="{{ item.Length }}" disabled>
<input class="form-control" id="disabledInput" type="text"
placeholder="Disabled input here..." value="{{ item.Type }}" disabled>
<input class="form-control" id="disabledInput" type="text"
placeholder="Disabled input here..." value="{{ item.MaterialType }}" disabled>
<input class="form-control" id="disabledInput" type="text"
placeholder="Disabled input here..." value="{{ item.Numberoftrucks }}" disabled>
<input class="form-control" id="disabledInput" type="text"
placeholder="Disabled input here..." value="{{ item.Loadingtime }}" disabled>
<input class="form-control" id="disabledInput" type="text"
placeholder="Disabled input here...">Bid
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</tr>
{% endfor %}
</table>
{% endblock %}
you can fix it by add model.pk to the modal id
in the button
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal"
data-target="#myModal{{ item.id }}">
Bid now! for id {{ item.id }}
</button>
and in the
<div class="modal fade"
id="myModal{{ item.id }}"
tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
other solution is create js function to load new data to each time as you activate the modal.

Reverse for 'update' with arguments '('',)' not found. 1 pattern(s) tried: ['vehicles_app/(?P<post_id>[0-9]+)/update_post/$']

I have searched a lot, but couldn't find a solution. There are a lot of related questions being asked before and I think there's no mistake but there's still an error.
Reverse for 'update' with arguments '('',)' not found. 1 pattern(s) tried: ['vehicles_app/(?P<post_id>[0-9]+)/update_post/$']
Here is my index.html
{% for obj in context %}
<div class="container" style="padding-left:240px; padding-right:0px; width: 78%; margin-bottom:30px;">
<div class="well" style=" background-color: rgb(220, 220, 220);">
<div class="media">
<div class="media-body">
<div class="list-group">
<div class="d-flex w-100 justify-content-between">
<h1 class="media-heading" style="margin-top:20px; margin-bottom:20px; color: black;">{{ obj.title }}</h1>
{% for img in obj.postpicture_set.filter %}
<div class="w3-content" style="max-width:800px">
{% if img.image %}
<img style="margin-bottom:30px; float: right" class="mySlides" src="{{ img.image.url }}" width="200" height="180">
{% endif %}
</div>
{% endfor %}
<p> {{ obj.details }} </p>
<ul class="list-inline list-unstyled">
<li><span><i class="glyphicon glyphicon-calendar"></i> {{ obj.date }} </span></li>
<li>|</li>
<span><i></i> {{ obj.brand }} </span>
<li>|</li>
<span><i></i> {{ obj.city }} </span><br>
<form action="{% url 'vehicles_app:data' obj.id %}" method="post">{% csrf_token %} <input type="hidden" name="post_id" value="{{ obj.id }}">
<input type="hidden" name="usr_id" value="{{ obj.user_id }}">
<td><input style="margin-top:70px; margin-bottom:20px; margin-left:10px;" type="submit" class="btn btn-primary" value="Details"</td></form>
{% if request.user == obj.user or request.user.is_superuser %}
<form action="{% url 'vehicles_app:file-delete' obj.id %}" method="post" style="display: inline;">{% csrf_token %} <input type="hidden" name="post_id" value="{{ obj.id }}">
<td><input style="margin-top:70px; margin-bottom:20px; margin-left:10px;" type="submit" value="Delete" class="btn btn-danger btn-sm"</td></form>
<form action="{% url 'vehicles_app:update' obj.id %}" method="post" style="display: inline;">{% csrf_token %}<input type="hidden" name="post_id" value="{{ obj.id }}">
<td><input style="margin-top:70px; margin-bottom:20px; margin-left:10px;" type="submit" value="Update" class="btn btn-default btn-sm"</td></form>
{% else %}
{% endif %}
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
Here is views.py
def update_post(request, post_id):
ImageFormSet = modelformset_factory(
PostPicture,
form=AddPictures,
extra=10,
min_num=1
)
post_form = get_object_or_404(Posts, pk=post_id)
if request.method == "POST":
form = AddFile(request.POST, instance=post_form)
formset = ImageFormSet(
queryset=PostPicture.objects.filter(
post=post_id
)
)
if form.is_valid() and formset.is_valid():
form.save()
for form in formset:
if form:
image = form['image']
photo = PostPicture(post=form, image=image)
photo.save()
messages.success(
request, 'Post submitted Successfully!'
)
return render(
request,
'vehicles_app/update_post.html',
{
'form': form,
'formset': formset,
'post_form':post_form
}
)
else:
print(form.errors, formset.errors)
else:
form = AddFile()
formset = ImageFormSet(
queryset=PostPicture.objects.none()
)
return render(
request,
'vehicles_app/update_post.html',
{
'form': form,
'formset': formset,
'post_form':post_form
}
)
Here is the url for my update, only update is not working, but other things like data and delete are working fine.
urlpatterns = [
url(r'^signUp/$', views.signUp, name='signUp'),
url(r'^user_login/$', views.user_login, name='user_login'),
url(r'^addfile/$', views.addfile, name='addfile'),
url(r'^(?P<pk>[0-9]+)/delete/$', views.FileDelete.as_view(), name='file-delete'),
url(r'^(?P<post_id>[0-9]+)/data/$', views.data, name='data'),
url(r'^(?P<post_id>[0-9]+)/update_post/$', views.update_post, name='update'),
url(r'^myposts/$', views.myposts, name='myposts'),
url(r'^received/$', views.received, name='received'),
url(r'^received_files/$', views.received_files, name='received_files'),
]
here is my update_post.html
{% extends "vehicles_app/index.html" %}
{% block body_block %}
{% load staticfiles %}
<html>
<body>
<div class="container" id="addfile_form" style="margin- left:200px; width: 78%;">
<!-- <div class="col-xs-12 col-sm-4 col-md-6 col-sm-offset-2 col- md-offset-2"> -->
<div class="panel panel-default">
<div>
{% if messages %}
<ul class="messages">
{% for message in messages %}
<h2 style="margin-left:100px;"> {{ message }} </h2>
{% endfor %}
</ul>
{% endif %}
</div>
<div class="panel-heading">
<b><h2 id="post_head" class="panel-title">Update Post here!</h2>
</b>
</div>
<div class="panel-body">
<form id="post_form" method="post" action="{% url
'vehicles_app:update_post' post_id %}"
enctype="multipart/form-data">
{% csrf_token %}
<div class="row">
<div class="form-group">
<div style="float: left; width: 50%">
<label for="title">Ad Title</label>
</div>
<div class="title" style="float: right; width: 45%">
<input type="text" name="title" placeholder="Type Here"
value='{{ form.title.value }}' required>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="city">City</label>
</div>
<div class="city" style="float: right; width: 45%">
<select name="city" value='{{ form.city.value }}'>
<option selected="selected"
value="islamabad">Islamabad</option>
<option value="karachi">Karachi</option>
<option value="lahore">Lahore</option>
<option value="peshawar">Peshawar</option>
<option value="quetta">Quetta</option>
<option value="multan">Multan</option>
<option value="faisalabad">Faisalabad</option>
</select>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="price">Price</label>
</div>
<div class="price" style="float: right; width: 45%">
<input type="text" name="price" placeholder="Type Here"
value='{{ form.price.value }}' required>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="brand">Brand</label>
</div>
<div class="brand" style="float: right; width: 45%">
<select name="brand" value='{{ form.brand.value }}'>
<option selected="selected"
value="honda">Honda</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
<option value="suzuki">Suzuki</option>
<option value="toyota">Toyota</option>
<option value="lexus">Lexus</option>
<option value="hyundai">Hyundai</option>
<option value="jeep">Jeep</option>
<option value="mazda">Mazda</option>
<option value="mitsubishi">Mitsubishi</option>
<option value="daewoo">Daewoo</option>
</select>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="modelyear">Model-Year</label>
</div>
<div class="modelyear" style="float: right; width: 45%">
<input type="text" name="modelyear"
placeholder="ie:1970-2018" value='{{ form.modelyear.value }}' required>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="condition">Condition</label>
</div>
<div class="condition" style="float: right; width: 45%">
<select name="condition" value='{{ form.condition.value
}}'>
<option selected="selected" value="new">NEW</option>
<option value="used">USED</option>
</select>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="mileage">Mileage</label>
</div>
<div class=mileage style="float: right; width: 45%">
<input type="text" name="mileage" placeholder="ie:50000"
value='{{ form.mileage.value }}' required>
</div>
</div>
</div>
<br>
<div class="form-group">
<div style="float: left; width: 50%">
<label for="details">Type details here</label>
</div>
<div class="details" style="float: right; width: 45%">
<textarea name="details" rows="9" cols="45" value='{{
form.details.value }}' required></textarea>
</div>
</div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
{{ formset.management_form }}
{% if formset %}
{% for form in formset %}
{% if form %}
<table class="display" cellspacing="1" width="100%">
<tr>
<td>{{ form }}</td>
</tr>
</table>
{% endif %}
{% endfor %}
{% endif %}
<input type="submit" name="submit" value="Update" class="btn
btn-info" id="post_btn">
</form>
</div>
</div>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
</script>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
</body>
</html>
{% endblock %}
The error is coming from this url tag in your update_post.html template.
<form id="post_form" method="post" action="{% url 'vehicles_app:update_post' post_id %}"
You get the error with arguments '('',)' in the error message because you haven't included post_id in the template context. You can add it with:
return render(request, 'vehicles_app/update_post.html', {
'form': form,
'formset': formset,
'post_form': post_form,
'post_id': post_id,
})
Remember to do this for GET and POST requests.

Error message is not shown

An error message is not shown.I wrote in index.html
<main>
<div class="detailimg col-xs-8">
<div class="relative_ele">
<div class="container" id="photoform">
{% if form.errors %} 
<div class="alert alert-danger" role="alert">
 <p>At least 1 picture should be selected</p>  
</div>
{% endif %}
<form action="/accounts/upload_save/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="input-group">
<label class="input-group-btn" style="width: 80px;">
<span class="file_select btn-lg">
File Select1
<input type="file" name="image">
</span>
</label>
<input type="text" class="form-control" readonly="">  
</div>
<div class="input-group">
<label class="input-group-btn" style="width: 80px;">
<span class="btn-lg file_select">
File Select2
<input type="file" name="image2">
</span>
</label>
<input type="text" class="form-control" readonly="">  
</div>
<div class="form-group">
<input type="hidden" value="{{ p_id }}" name="p_id" class="form-control">
</div>
<div class="col-xs-offset-2">
<div class="form-group">
<input type="submit" value="SEND" class="form-control">
</div>
</div>
</form>
</div>
</div>
</div>
</main>
in views.py
#login_required
#csrf_exempt
def upload_save(request):
if request.method == "POST":
form = UserImageForm(request.POST, request.FILES)
if form.is_valid():
data = form.save(commit=False)
data.user = request.user
data.image = request.cleaned_data['image']
data.save()
else:
print(form.errors)
else:
form = UserImageForm()
return render(request, 'registration/photo.html', {'form': form})
In my current code, when I select no image and put "SEND" button & I select the 1~2 image and put "SEND" button,photo.html is shown.I wanna show error message
{% if form.errors %}
<div class="alert alert-danger" role="alert">
<p>At least 1 picture should be selected</p>
</div>
{% endif %}
when I select no image, but now my system is not an ideal one. Why can't I do it? I think if I select no image,{% if form.errors %} become true. Do I misunderstand it? How should I fix this?
<main>
<div class="detailimg col-xs-8">
<div class="relative_ele">
<div class="container" id="photoform">
{% if form.errors %} 
<div class="alert alert-danger" role="alert">
 <p>At least 1 picture should be selected</p>  
</div>
{% endif %}
<!--here change--><form action="/accounts/upload_save/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="input-group">
<label class="input-group-btn" style="width: 80px;">
<span class="file_select btn-lg">
File Select1
<!--here change--><input id="file1" type="file" name="image">
</span>
</label>
<input type="text" class="form-control" readonly="">  
</div>
<div class="input-group">
<label class="input-group-btn" style="width: 80px;">
<span class="btn-lg file_select">
File Select2
<!--here change--><input id="file2" type="file" name="image2">
</span>
</label>
<input type="text" class="form-control" readonly="">  
</div>
<div class="form-group">
<input type="hidden" value="{{ p_id }}" name="p_id" class="form-control">
</div>
<div class="col-xs-offset-2">
<div class="form-group">
<!--here channge --><input id="send" type="submit" value="SEND" class="form-control">
</div>
</div>
</form>
</div>
</div>
</div>
</main>
<script type="text/javascript" language="JavaScript">
window.onload = function () {
var a = document.getElementById("send");
var file1 = document.getElementById("file1");
var file2 = document.getElementById("file2");
a.onclick = function(){
if(file1.value=="" && file2.value==""){
alert ('You didn\'t choose any of the checkboxes!');
return false;
}
else {
return true;
}
}
}
</script>
Hope this will work

Categories

Resources