I render my form inside a modal:
view:
#login_required
def task_edit(request, pk):
member = get_object_or_404(Tasks, pk=pk)
if request.method == "POST":
form = TasksForm(request.POST or None, instance=member)
if form.is_valid():
reg = form.save(commit=False)
reg.save()
return HttpResponse(
'<script type="text/javascript">window.close();</script>')
else:
form = TasksForm(instance=member)
return render(request, 'TaskProj/task_edit.html', {'form': form})
my html rendered in a modal popup:
{%load staticfiles %}
<div class="row">
<div class="col-lg-12">
<div class="panel">
<div class="content-box">
<h3 class="content-box-header bg-primary">
<span class="icon-separator">
<i class="glyph-icon icon-tasks"></i>
</span>
<span class="header-wrapper">
Eidt Tasks </span>
</span>
</h3>
<div class="panel">
<div class="panel-body">
<form method="POST" id="form" class="form-horizontal bordered-row" autocomplete="off">
{% csrf_token %}
<div class="example-box-wrapper">
<div class="form-group">
{{ form.as_p }}
</div>
</div>
<button type="submit" class="btn btn-primary btn-lg btn-block">Salva</button>
</div>
</div>
</form>
<script type="text/javascript">
$(document).on('click','.submit',function(){
$( "#form" ).submit();
});
</script>
{% endblock %}
This form is rendered inside a modal popup.
I try to save, it close modal but not save form.
I think there is a problem with submit button...
Any idea?
TY
you need to declare an action attribute with the url to your function that handles the specific form in views.py. So that the form knows where to go, and be handled:
<form method="POST" id="form" class="form-horizontal bordered-row" action="{% 'task_edit' your-object.pk %}" autocomplete="off">
{% csrf_token %}
<div class="example-box-wrapper">
<div class="form-group">
{{ form.as_p }}
</div>
</div>
<button type="submit" class="btn btn-primary btn-lg btn-block">Salva</button>
</div>
</div>
</form>
Related
I've got empty Bootstrap modal form with Django UpdateView(CBV)
The most important question without using js , I will not be able to display data in a modal window? (I only use bootstrap.bundle.min.js in base.html)
Modal window show fields of empty form
view.py
class HistoryPamentsByService(ListView):
model=Payments
form_class=PaymentsForm
template_name ='myflat/history_by_service.html'
context_object_name='flats'
slug_url_kwarg = 'slug'
def get_context_data(self, **kwargs):
context=super().get_context_data(**kwargs)
form=PaymentsForm()
payments=Payments.objects.filter(flats_id=self.kwargs['flats_id'])
context['form']=form
return context
def get_form(self,*args,**kwargs):
super().get_form(*args, **kwargs)
form=PaymentsForm()
return form
def get_queryset(self):
return Payments.objects.filter(slug=self.kwargs['slug'],flats_id=self.kwargs['flats_id'])
class UpdatePayments(UpdateView):
model=Payments
pk_url_kwarg='pk'
template_name='myflat/update_modal.html'
context_object_name='name_flat'
fields=['name_service','amount_of_bill',
'amount_of_real',
'date_of_bill',
'date_of_payment',
'status_payment',
'comments',
'bill_save_pdf']
def get_success_url(self):
return reverse('HistoryPamentsByService',
kwargs={'slug':self.object.slug,
'flats_id': self.object.flats_id})
urls.py
urlpatterns = [ path('history_by_service/<slug:slug>/<int:flats_id>/',
HistoryPamentsByService.as_view(),name='HistoryPamentsByService'),
path('UpdatePayments/<int:pk>/',UpdatePayments.as_view(),name='UpdatePayments'),
]
template
history_by_service.html (for ListView)
{%extends "base.html"%}
{%block content%}
{% for flat in flats %}
<tr>
<td scope="row">{{ forloop.counter }} </td>
<td>{{flat.name_service}}</td>
<td>{{flat.amount_of_bill}}</td>
<td>{{flat.amount_of_real}}</td>
<td>{{flat.date_of_bill}}</td>
<td>{{flat.date_of_payment}}</td>
<td>{{flat.get_status_payment_display}}</td>
<td>{{flat.comments}}</td>
<td>{{flat.bill_save_pdf}}</td>
<td>
<form method="post" action="{% url 'UpdatePayments' flat.pk %}" enctype="multipart/form-data">
{% csrf_token %}
<button type='button' class='btn btn-success btn-sm' id="update_modal"
data-bs-toggle="modal" data-bs-target="#update_modal{{flat.pk}}">
<i class="fa-regular fa-pen-to-square fa-fw"></i>Edit</button>
{% include "myflat/update_modal.html" %}
</form>
{% endfor %}
{% endblock content %}
template
update_modal.html
<div class="modal fade" id="update_modal{{flat.pk}}" data-bs-backdrop="static"
data-bs-keyboard="false" tabindex="-1" aria-labelledby="update_modal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content" style="width:auto">
<div class="modal-header">
<h5 class="modal-title " id="update_modalLabel">{{flat.name_flat}}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form method="post" action="{% url 'UpdatePayments' flat.pk %}" enctype="multipart/form-data">
<div class="modal-body">
{% csrf_token %}
{% for field in form %}
{{field}}
{% endfor %}
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" >
<i class="fa-solid fa-trash fa-fw" ></i>Save</button>
<button type="button" class="btn btn-warning"
data-bs-dismiss="modal">
<i class="fa-regular fa-circle-xmark"></i>Close</button>
</div>
</div>
</form>
</div>
</div>
</div>
I try add in UpdatePayments(UpdateView) next code:
class UpdatePayments(UpdateView):
model=Payments
pk_url_kwarg='pk'
form_class=PaymentsForm
template_name='myflat/update_modal.html'
context_object_name='name_flat'
def get_context_data(self, **kwargs):
context= super().get_context_data(**kwargs)
obj=Payments.objects.get(pk=self.kwargs['pk'])
form=PaymentsForm(self.request.POST or None ,instance=obj)
context['form']=form
return context
but still nothing in Modal is empty fields!!!
What's wrong, any helps,please!!!
When I press the button to post something, it will return me to the main page, not stay in the forum page and show me what I just post.
Here is the view.py
def forum(request):
profile = Profile.objects.all()
if request.method == "POST":
user = request.user
image = request.user.profile.image
content = request.POST.get('content','')
post = Post(user1=user, post_content=content, image=image)
post.save()
alert = True
return render(request, "forum.html", {'alert':alert})
posts = Post.objects.filter().order_by('-timestamp')
return render(request, "forum.html", {'posts':posts})
def discussion(request, myid):
post = Post.objects.filter(id=myid).first()
replies = Replie.objects.filter(post=post)
if request.method=="POST":
user = request.user
image = request.user.profile.image
desc = request.POST.get('desc','')
post_id =request.POST.get('post_id','')
reply = Replie(user = user, reply_content = desc, post=post, image=image)
reply.save()
alert = True
return render(request, "discussion.html", {'alert':alert})
return render(request, "discussion.html", {'post':post, 'replies':replies})
Here is the html5 code, I don't know why I cannot post the full html code, it tell me there is an error.
<div class="modal fade" id="questions" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% if user.is_authenticated %}
<div class="modal-body">
<form action="/" method="POST"> {% csrf_token %}
<div class="form-group">
<label for="exampleFormControlTextarea1">Post Your Question Here</label>
<textarea class="form-control" id="content" name="content" rows="3"></textarea>
</div>
</form>
</div>
{% else %}
<h3>Please Login to post</h3>
{% endif %}
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Post</button>
</div>
</div>
</div>
</div>
Does your HTML include form tag with method="post" ? Example below
Make sure to include your button inside this form tag. All should work after that.
<form method="post">
</form>
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 building a Django web-app where the user needs to upload a file. This file should go through a machine-learning alogritme after that the results will be presented on a different page.
right now it works if I have text fields present for every feature but when I want to upload a csv file(the csv file is called test.csv) put it in a pandas dataframe the resultpage doesn't show and it looks like the csv file isn't processed.
what it should do is if file is uploaded keep the uploaded file in memory process it and return the output on the results page.
HTML
{% extends "base.html" %}
{% block content %}
<div class="content">
<div class="row">
<div class="col-lg-4">
<div class="card card-tasks">
<h1> </h1>
<form action="{% url 'result' %}">
{% csrf_token %}
<p>temp_normal:</p>
<input class="form-control" type="text" name="temp_normal">
<br>
<p>hour:</p>
<input class="form-control" type="text" name="hour">
<br>
<p>hour_x:</p>
<input class="form-control" type="text" name="hour_x">
<br>
<p>hour_y:</p>
<input class="form-control" type="text" name="hour_y">
<br>
<input class="form-control" type="submit" value='Submit'>
</form>
</div>
</div>
<div class="col-lg-4">
<div class="card card-tasks">
<form action="{% url "result" %}" method="POST" enctype="multipart/form-data" class="form-horizontal">
{% csrf_token %}
<div class="form-group">
<label for="name" class="col-md-3 col-sm-3 col-xs-12 control-label">File: </label>
<div class="col-md-8">
<input type="file" name="csv_file" id="csv_file" required="True" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-md-3 col-sm-3 col-xs-12 col-md-offset-3" style="margin-bottom:10px;">
<button class="btn btn-primary"> <span class="glyphicon glyphicon-upload" style="margin-right:5px;"></span>Upload </button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock content %}
views.py
def handle_uploaded_file(f):
with open('test.csv', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
# custom method for generating predictions
def getPredictions(data):
import pickle
model = pickle.load(open("test_model.sav", "rb"))
prediction = model.predict(data)
return prediction
#login_required
def result(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
data = form
data = pd.read_csv(data,header=0)
result = getPredictions(data)
return render(request, 'result.html', {'result': result})
else:
form = UploadFileForm()
return render(request, 'index.html', {'form': form})
try:
<form action="{% url "result" %}" method="POST" enctype="multipart/form-data" class="form-horizontal">
{% csrf_token %}
<div class="form-group">
<label for="name" class="col-md-3 col-sm-3 col-xs-12 control-label">File: </label>
<div class="col-md-8">
{{ form }}
</div>
</div>
<div class="form-group">
<div class="col-md-3 col-sm-3 col-xs-12 col-md-offset-3" style="margin-bottom:10px;">
<button class="btn btn-primary" type="submit"> <span class="glyphicon glyphicon-upload" style="margin-right:5px;"></span>Upload </button>
</div>
</div>
</form>
as we discussed for the view:
#login_required
def result(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
file = request.FILES['file']
handle_uploaded_file(file)
data = pd.read_csv(file,header=0)
result = getPredictions(data)
return render(request, 'result.html', {'result': result})
else:
form = UploadFileForm()
return render(request, 'index.html', {'form': form})
I am trying to get the value of a textbox from views.py but its not working for some reason.
Below is my code
base.html
<form method="POST" role="form" >
{% csrf_token %}
<div class="tab-content">
<div class="tab-pane active" role="tabpanel" id="step1">
<div class="mobile-grids">
<div class="mobile-left text-center">
<img src="{% static 'images/mobile.png' %}" alt="" />
</div>
<div class="mobile-right">
<h4>Enter your mobile number</h4>
<!-- <label>+91</label><input type="text" name="mobile_number" class="mobile-text" value="asdfasd" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = '';}" required=""> -->
<label>+91</label><input type="text" name="mobile_number" class="mobile-text" value="" >
</div>
</div>
<ul class="list-inline pull-right">
<li><button type="button" class="mob-btn btn btn-primary btn-info-full" data-dismiss="modal">Finish</button></li>
</ul>
</div>
<div class="clearfix"></div>
</div>
</form>
views.py
def home(request):
mobile_number = request.POST.get('mobile_number')
print(mobile_number)
return render(request,"home.html", {'mobile_number': mobile_number})
I am getting None when I try to get the value of textbox mobile_number.
How can I get the correct value?
You are missing a submit-button (<input type="submit" value="submit"/>) from the from.
To see the value on the form after submitting it, change value=""on the mobile_number -row, to value="{{ mobile_number }}".
My solution
1. You have to set action in form field as your functon in view.py
<form class="forms-sample" name="form" action="{% url "update_size" %}" method="post">
You have make button type as submit.
<button type="Submit" value="Submit" name="Submit" class="btn btn-primary">
url.py
path('updatesize/', views.updatesize, name='update_size')
View.py
def updatesize(request):
if (request.method == 'POST'):
temp = request.POST.get('size_name')
print("==================form================",temp)
return redirect("/collection.html")