I have a html file that I wanna use this template to render my form and save it to my database
How to do this?
HTML code:
<div class="container-contact100">
<div class="wrap-contact100">
<form class="contact100-form validate-form" enctype="multipart/form-data" method="POST">
{% csrf_token %}
<span class="contact100-form-title">
Add Item!
</span>
<div class="wrap-input100 validate-input" data-validate="Name is required">
<span class="label-input100">Title</span>
<input class="input100" type="text" name="name" placeholder="Enter food name">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input">
<span class="label-input100">Price</span>
<input class="input100" type="number" name="price" placeholder="Enter food price">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Message is required">
<span class="label-input100">Description</span>
<textarea class="input100" name="message" placeholder="Your description here..."></textarea>
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate="Image is required">
<input type="file" class="custom-file-input" id="customFile" name="filename">
<label class="custom-file-label" for="customFile">Choose file</label>
<span class="focus-input100"></span>
</div>
<div class="container-contact100-form-btn">
<div class="wrap-contact100-form-btn">
<div class="contact100-form-bgbtn"></div>
<button class="contact100-form-btn" type="submit">
<span>
Add
<i class="fa fa-long-arrow-right m-l-7" aria-hidden="true"></i>
</span>
</button>
</div>
</div>
</form>
</div>
</div>
<div id="dropDownSelect1"></div>
and here is my forms.py :
from django import forms
from .models import Product
class AddItemForm(forms.ModelForm):
class Meta:
model = Product
fields = '__all__'
even you can access my project from this link via github:
https://github.com/imanashoorii/FoodMenu.git
You have to set the name attributes in your form in your html according to field names of your Porudct model like this (using data from your GitHub link):
add_product.html
<form method="post" enctype="multipart/form-data"> # here define enctype attribute so your form can accept images
{% csrf_token %}
<input type="text" name="title">
<input type="text" name="description">
<input type="number" name="price">
<input type="file" name="image">
<button type="submit">Submit</button>
</form>
Or instead of manually defining each field you can just pass a {{ form.as_p }} to your html to render each field inside a <p> tag like this:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
Then here is how you would save it in a view:
views.py
def add_product(request):
if request.method == 'POST':
form = AddItemForm(request.POST, request.FILES) # request.FILES is so your form can save images
if form.is_valid()
form.save()
return redirect('home') # redirect to a valid page
else:
form = AddItemForm()
return render(request, 'add_product.html', {'form': form})
I have fixed my problem by changing views.py to this and fix it :
if form.is_valid():
title = request.POST.get('title')
description = request.POST.get('description')
price = request.POST.get('price')
image = request.POST.get('image')
form.save()
return redirect("food:home")
Related
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})
trying to setting up a small website,a newbie in django . when i create a newsletter setup in django, but the email not saving the admin panel. here is my codes. take a look .
models.py
class Newsletter(models.Model):
email = models.CharField(max_length=200)
def __str__(self):
return self.email
views.py
def Newsletter(request):
if request.method=="POST":
email = request.POST.get("email")
email = email(email=email)
email.save()
message.success(request, "email Successfully added")
return render(request, 'index.html')
urls.py
path('newsletter', views.Newsletter, name="newsletter"),
template
<div id="mc_embed_signup" class="subscribe-form subscribe-form-dec subscribe-mrg">
<form id="Newsletter" class="validate subscribe-form-style" novalidate="" name="Newsletter" method="post" action="/Newsletter">
<div id="mc_embed_signup_scroll" class="mc-form">
<input class="email" type="email" required="" placeholder="Your email address…" name="Newsletter" value="" id="Newsletter">
<div class="mc-news" aria-hidden="true">
<input type="text" value="" tabindex="-1" name="Subscribers">
</div>
<div class="clear">
{% csrf_token %}
<input id="mc-embedded-subscribe" class="button" type="submit" name="subscribe" value="Subscribe">
</div>
</div>
models.py
class Newsletter(models.Model):
email = models.CharField(max_length=200)
def __str__(self):
return self.email
views.py:
Here maybe you are overriding the name of the view with the name of Model, try this:
from .models import Newsletter
def adding_email_to_newsletter(request):
if request.method=="POST":
email = request.POST.get("email")
Newsletter.objects.get_or_create(email=email)
message.success(request, "email Successfully added")
return render(request, 'index.html')
the urls.py
path("adding_email_to_newsletter", views.adding_email_to_newsletter, name="adding_email_to_newsletter"),
template:
Here you miss the csrf_token that is required for post submits by default docs and the using of the tag url for best practices.
<div id="mc_embed_signup" class="subscribe-form subscribe-form-dec subscribe-mrg">
<form id="Newsletter" class="validate subscribe-form-style" novalidate="" name="Newsletter" method="post" action="{% url 'adding_email_to_newsletter' %}">
{% csrf_token %}
<div id="mc_embed_signup_scroll" class="mc-form">
<input class="email" type="email" required="" placeholder="Your email address…" name="Newsletter" value="" id="Newsletter">
<div class="mc-news" aria-hidden="true">
<input type="text" value="" tabindex="-1" name="Subscribers">
</div>
<div class="clear">
{% csrf_token %}
<input id="mc-embedded-subscribe" class="button" type="submit" name="subscribe" value="Subscribe">
</div>
</div>
</form>
</div>
So I wanna be able to update information of a router in the database using a form, I wanna have a form pre-populated with that specific router details. The problem is that form.is_valid() is not working
I tried using {{ form.errors }} {{ form.non_field_errors }} and print(form.errors) but none of them worked
views.py (incomplete)
def info_router(request, pk):
rout = Routers.objects.get(sn=pk)
if request.method == 'GET': # Insert the info in forms
form = UpdateRouter()
rout = Routers.objects.get(sn=pk)
args = {'router': rout}
return render(request, "router_info.html", args)
if request.POST.get('delete'):
# Delete router
rout.delete()
messages.warning(request, 'Router was deleted from the database!')
return redirect("db_router")
if request.method == 'POST':
#Updating the form
form = UpdateRouter(instance=Routers.objects.get(sn=pk))
print(form)
print(form.errors)
if form.is_valid():
data = UpdateRouter.cleaned_data
mac = data['mac']
print(mac)
return HttpResponseRedirect('db_router')
else:
print("Invalid form")
return render(request, "db_router.html", {'form': form})
forms.py
class UpdateRouter(ModelForm):
class Meta:
model = Routers
fields = ['model', 'ip_addr', 'name', 'sn', 'mac']
template
<form class="form-horizontal" action="" method="post">
{% csrf_token %}
<div class="form-group"> <!-- Form with the router details -->
<label class="control-label col-sm-2" for="text">Serial number:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="text" name="sn" value="{{ router.sn }}" readonly>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Model:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="text" value="{{ router.model }}" name="model" readonly>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Ip address:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="text" value="{{ router.ip_addr }}" name="ip_addr">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="text" value="{{ router.name }}" name="name">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Mac address:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="text" value="{{ router.mac }}" name="mac">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Extra info:</label>
<div class="col-sm-10">
<textarea class="form-control" name="extra_info" id="FormControlTextarea" rows="3">Example of some info</textarea>
</div>
</div>
<div class="form-group" style="margin-top: 20px;">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">Update</button> <!-- Responsible for updating the router -->
Cancel
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#myModal" style="float: right"> <!-- Responsible for the delete modal to open -->
Delete
</button>
</div>
</div>
</form>
You never passed request.POST and rquest.FILES. If you want to update the fields and files, you need to form.save() your form:
if request.method == 'POST':
#Updating the form
form = UpdateRouter(request.POST, request.FILES, instance=Routers.objects.get(sn=pk))
print(form)
print(form.errors)
if form.is_valid():
data = form.cleaned_data
mac = data['mac']
form.save()
print(mac)
return redirect('db_router')
else:
print("Invalid form")
If you do not pass request.POST and/or request.FILES, then Django does not consider the form filled in, and it is never considered valid.
If you pass both files and data, then you need to add the enctype="multipart/form-data" to your <form> tag:
<form enctype="multipart/form-data" class="form-horizontal" action="" method="post">
<!-- -->
</form>
you need to create a bound_form
form = UpdateRouter(request.POST)
form = UpdateRouter(request.POST) binds the data to the form class. then validate
the inputs using is_valid().
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()
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")