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")
Related
I am trying to extend the UserCreationForm using a Bootstrap layout style for the field username. After the input tag in the registration form, I would like to add a div element like an example that I have readapted from the Bootstrap page: i.e. suggesting the user to enter the same username as the company domain.
Let's focus to the bare minimum. The form readapted from Bootstrap is:
<form class="row gy-2 gx-3 align-items-center method="POST" action="{% url 'register' %} ">
<div class="col-auto">
<div class="input-group">
<input type="text" name="username" class="form-control" placeholder="your.username" id="id_username">
<div class="input-group-text">#company.domain.com</div>
</div>
</div>
<div class="col-auto">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
Which produces the following:
For the moment, I am using only {{form.as_p}} in my html template file:
<form class="row gy-2 gx-3 align-items-center method="POST" action="{% url 'register' %} ">
{{form.as_p}}
<div class="col-auto">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
And I don't know how to add the <div class="input-group-text">#company.domain.com</div> part embedded in a <div class="input-group">...</div> block.
My actual forms.py is a bit more complex, but readapted for this minimum example it contains the widget attributes as follows:
class SignupForm(UserCreationForm):
username = forms.CharField(label="",
widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'your.username'}))
class Meta:
model = User
fields = (
'username',
)
Without additional libraries, is there a way to extend the widget attributes? Is it even possible to use {{form.as_p}} as I am currently doing or should I use another method?
If you want to use only {{ form.as_p }} with bootstrap then you need to install django-bootstrap.
Install it using pip:
pip install django-bootstrap4
After installation, add it in INSTALLED_APPS in settings.py file.
INSTALLED_APPS = [
'bootstrap4',
]
And in templates, you need to load it.
{% load bootstrap4 %}
{% bootstrap_messages %}
<form class="row gy-2 gx-3 align-items-center method="POST" action="{% url 'register' %} ">
{% csrf_token %}
{% bootstrap_form form %} # added `form` here. we don't need to use with as_p.
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
This is the way you can use bootstrap along with {{ form.as_p }}
OR
Try another way:
Simply you can use {{ form.username }} inside an input tag in template.
For Example:
<input type="text" value="{{ form.username }}">
<form class="row gy-2 gx-3 align-items-center method="POST" action="{% url 'register' %} ">
<div class="col-auto">
<div class="input-group">
<input type="text" name="username" class="form-control" placeholder="your.username" id="id_username" value="{{ form.username }}"> #Added here
<div class="input-group-text">#company.domain.com</div>
</div>
</div>
<div class="col-auto">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
I have a modal for confirm the action and this modal adds #modal to url but after i submit the url it stil there in the url even after i did redirect in views.py
<div class="wf-modal" aria-hidden="true" id="{{sepet.id}}">
<article class="wf-dialog-modal">
<form action="" method="post">
{% csrf_token %}
<div class="wf-content-modal">
<input type="hidden" name="cancel-id" value="{{sepet.id}}">
<label for="sebep">{%if sepet.siparis_durumu.durum == "Kargoya Verildi"%}İade{%else%}İptal{%endif%} Sebebi: </label>
<textarea name="sebep" style="resize: none; margin-left: 2px;" cols="40" rows="5" {%if sepet.siparis_durumu.durum == "Kargoya Verildi"%}required{%endif%}></textarea>
</div>
<footer class="wf-footer-modal">
<button name="gonder" value="gonder">Gönder</button>
<button name="iptal" type="button">İptal</button>
</footer>
</form>
</article>
</div>
views.py
if req.get('gonder'):
if ...:
return redirect('/hesabim/iptal/')
but the url stil like /hesabim/iptal/#modal-id
I've Solved it by js depending on #WillemVanOnsem comment using:
window.location.hash = '';
Lets us consider my template.html as
<form class="form-horizontal" id="adhoc-form" method="post" action="{% url 'contacts:add_item' item.id %}">
{% csrf_token %}
<fieldset>
<div class="control-group">
<label for="id_item_filename" class="control-label">Items
<span class="text-error">*</span></label>
<div class="controls">
<select placeholder="Item filename" name="item" id="id_item_filename" class="span3" required="required">
<option value="">---------</option>
{% for i in items %}
<option value="{{i.0}}">{{i.1}}</option>
{% endfor %}
</select>
</div>
</div>
</fieldset>
<div id="form-buttons-container" class="form-actions" style="padding-left: 0px;">
<div class="controls">
<input type="hidden" class="btn btn-primary btn-medium" id= 'i_id' name='i_id' value="{{data.0.id}}">
<input type="submit" class="btn btn-primary btn-medium" value="Submit">
<input type="submit" class="btn btn-primary btn-medium" value="Delete">
</div>
</div>
</form>
my url.py is
url(r'^stock/item/add/item_name/(?P<id>\d+)/$', login_required(UpdateBarcode.as_view()), name="add_item"),
my views.py is
class UpdateItem(View):
def post(self, request, id):
item_id = request.POST.get('item')
items = Items.objects.get(id=item_id)
try:
JobItems.objects.filter(id=id).update(item_name=items.name)
except:
messages.error(request, 'Cannot update')
return redirect(reverse("contacts:item_list"))
Here when clicking the submit button we need to update item and we click delete button item should be deleted.please help me how can do both the submit and delete operations in the same view
You can get started with updating your HTML to give buttons name field:
<input type="submit" class="btn btn-primary btn-medium" name="update-item" value="Submit">
<input type="submit" class="btn btn-primary btn-medium" name="delete-item" value="Delete">
Now you can check which button is triggered. (update-item or delete-item):
def post(self, request, id):
item_id = request.POST.get("item")
items = Items.objects.get(id=item_id)
if "update-item" in request.POST:
try:
JobItems.objects.filter(id=id).update(item_name=items.name)
except:
messages.error(request, "Cannot update")
elif "delete-item" in request.POST:
JobItems.objects.get(id=id).delete()
return redirect(reverse("contacts:item_list"))
Note that I don't know your logic for item-delete operation so you can update here.
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>
I created a simple form where I'm asking for user input and then posting that to the database. Now I would like the user to confirm the data in form is correct, and for that I'm using a Bootstrap modal.
How can I send the data from the form to the view when pressing the 'OK' button on the modal.
I'm new to the Django framework, and maybe there is another better way without using bootstrap modals.
Form:
class ReportForm(forms.Form):
report_title = forms.ChoiceField(choices=get_report_titles())
report_link = forms.CharField(widget=forms.Textarea, required=False)
Html file:
<form class="w-100" action="" method="post">
{% csrf_token %}
<label class="pl-0 mt-auto mr-2">Report Name</label>
<select name="report_title" class="form-control report-name">
<option selected>Select report</option>
{% for name in report_names %}
<option>{{ name }}</option>
{% endfor %}
</select>
<div class="my-1 col-lg-12 float-left pl-0">
<label>Report Link</label>
<input class="form-control bg-white" type="text" id="report" name="report_link">
</div>
<input id="confirm" value="Save" type="button" data-toggle="modal" data-target="#exampleModalCenter" class="btn btn-outline-success" />
</form>
<!-- Modal -->
<div class=" modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Confirmation</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Make sure you have the right title and link.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
View:
def report_view(request):
if request.method == 'POST':
form = ReportForm(request.POST)
if form.is_valid():
report_title = form.cleaned_data['report_title']
report_link = form.cleaned_data['report_link']
new_report = Report(title = report_title, link = report_link)
new_report.save()
Simply update your code with these lines, add id="exampleForm".
start form tag with
<form class="w-100" action="" id="exampleForm" method="post">
Replace Save button with (add id="save"):
<button type="button" id="save" class="btn btn-primary">Save</button>
and finally add this script at the bottom to submit your form when save is clicked:
<script>
$("#save").on("click", function(e) {
$("#exampleForm").submit();
});
</script>
also I feel your view is not written correctly. It should be something like this, I'm not sure what you're trying to do:
def report_view(request):
if request.method == 'POST' and form.is_valid():
form = ReportForm(request.POST)
report_title = form.cleaned_data['report_title']
report_link = form.cleaned_data['report_link']
new_report = Report(title = report_title, link = report_link)
new_report.save()
Let me know if you still need help
This needs changing because you're not giving any values.
<select name="report_title" class="form-control report-name">
<option selected>Select report</option>
{% for name in report_names %}
<option>{{ name }}</option>
{% endfor %}
</select>
Try:
<select name="report_title" class="form-control report-name">
<option selected>Select report</option>
{% for name in report_names %}
<option value="{{name.pk}}">{{ name }}</option>
{% endfor %}
</select>
where name.pk is the value relating to the choices.
Also, if you change your form to a ModelForm you can just do:
if form.is_valid():
new_report = form.save()