i have code for form , i want to save the data through a form.
custom form is :-
<form class="well span12 c1" name="contacts" method="POST">
<label>First Name</label>
<input type="text" placeholder="Your First Name" class="span12" required name="firstname" >
<label>Last Name</label>
<input type="text" placeholder="Your Last Name" class="span12" required name="lastname" >
<label>Email Address</label>
<input type="text" placeholder="Your email address" class="span12" required name="email" >
<label>Subject</label>
<select class="span12" name="subject" id="subject" required >
<option value="na" selected="">Choose One:</option>
<option value="service">General Customer Service</option>
<option value="suggestions">Suggestions</option>
<option value="product">Product Support</option>
</select>
<label>Message</label>
<textarea rows="8" class="input-xlarge span12" id="message" name="message" required ></textarea>
<button class="btn btn-primary pull-right" style="border-radius:0px;" type="submit">Send</button>
</form>
views.py :-
#app.route('/contact' , methods = ['GET' , 'POST' ])
def contact():
if request.method == 'POST':
user = user_email(firstname = request.form['firstname'] ,
lastname = request.form['lastname'],
email = request.form['email'],
subject = request.form['subject'],
message = request.form['message'])
user.save()
return render_template('index.html')
else:
return render_template('contact.html')
there is an error of AttributeError: 'Database' object has no attribute 'model'. Please help me to solve this problem.
Have you setup a database, and connected to it? It should look something like this:
# define a database connection
database = peewee.SqliteDatabase('my.db')
class BaseModel(peewee.Model):
class Meta:
# this is likely the missing part of your model
# you need to tell the model which database connection to use.
database = database
class User(BaseModel):
first_name = peewee.CharField()
last_name = peewee.CharField()
email = peewee.CharField()
subject = peewee.CharField()
message = peewee.CharField()
<form class="well span12 c1" name="contacts" method="POST" action="{{ url_for('contact') }}">
<div class="row-fluid">
<div class="span6">
<label>First Name</label>
<input type="text" placeholder="Your First Name" class="span12" required name="firstname" >
<label>Last Name</label>
<input type="text" placeholder="Your Last Name" class="span12" required name="lastname" >
<label>Email Address</label>
<input type="text" placeholder="Your email address" class="span12" required name="email" >
<label>Subject</label>
<select class="span12" name="subject" id="subject" required >
<option value="na" selected="">Choose One:</option>
<option value="service">General Customer Service</option>
<option value="suggestions">Suggestions</option>
<option value="product">Product Support</option>
</select>
</div>
<div class="span6">
<label>Message</label>
<textarea rows="8" class="input-xlarge span12" id="message" name="message" required ></textarea>
</div>
<button class="btn btn-primary pull-right" style="border-radius:0px;" type="submit">Send</button>
</div>
</form>
Related
I do not want to replace my image file while updating other text and file name should be displayed in upload file choose file section so that as per my need I can modify file. as of now I am facing issues in that I have to again upload file in each update of other field.
image for reference.
eupdate.html
<input type="text" name="institution" id="institution" placeholder="Institution Name" class="form-control w-50 form-row" value="{{pi.institution}}" required>
<input type="text" name="fullname" id="fullname" placeholder="Full Name" class="form-control w-50 form-row mt-1" value="{{pi.fullname}}" required>
<input type="text" name="email" id="contact" placeholder="Personal Email " class="form-control w-50 form-row mt-1" value="{{pi.email}}" required>
<input type="number" name="contact" id="contact" placeholder="Contact " class="form-control w-50 form-row mt-1" value="{{pi.contact}}" required>
<input type="text" name="position" id="position" placeholder="Position " class="form-control w-50 form-row mt-1" value="{{pi.position}}" required>
<input class="form-control w-50 form-row mt-1" type="file" id="formFile" name="upload" value="{{pi.uploaddata.url}}" required>
<img src={{pi.uploaddata.url}} class="img-fluid img-thumbnail" alt="image" style="width:100px; height: 60px"><br>
<input class="form-check-input" type="checkbox" value="" id="invalidCheck" name='checkbox' required>
<label class="form-check-label" for="invalidCheck">
Agree to terms and conditions
</label>
<br>
<input class="bg-success text-white mt-1" style="margin-top: 0px;" type="submit" />
views.py
def EuAdmin(request, pk):
pi = EmailDb.objects.get(id=pk)
if request.method == 'POST':
institution = request.POST.get('institution', '')
fullname = request.POST.get('fullname', '')
email = request.POST.get('email', '')
contact = request.POST.get('contact', '')
position = request.POST.get('position', '')
uploadd = request.FILES.get('upload', '')
pi.institution = institution
pi.fullname = fullname
pi.email = email
pi.contact = contact
pi.position = position
pi.uploaddata = uploadd
pi.save()
return HttpResponseRedirect("/eadmin")
return render(request, 'NEC/eupdate.html', {'pi': pi})
You should check whether the file has been updated or not, then do things accordingly, if updated then save that one, otherwise old file should be there.
Try this view:
def EuAdmin(request, pk):
pi = EmailDb.objects.get(id=pk)
if request.method == 'POST':
institution = request.POST.get('institution', '')
fullname = request.POST.get('fullname', '')
email = request.POST.get('email', '')
contact = request.POST.get('contact', '')
position = request.POST.get('position', '')
uploadd = request.FILES.get('upload', '')
pi.institution = institution
pi.fullname = fullname
pi.email = email
pi.contact = contact
pi.position = position
if uploadd:
pi.uploaddata = uploadd
pi.save()
return HttpResponseRedirect("/eadmin")
return render(request, 'NEC/eupdate.html', {'pi': pi})
I am trying to retrieve data from a form using the Post method and store it in the database. However, when I click on the submit button,I keep on getting the following error:
NOT NULL constraint failed: posts_subscribe.firstname
Here is my views.py:
def subscribe(request):
if request.method == 'POST':
firstname=request.POST.get('firstname')
secondname=request.POST.get('secondname')
email=request.POST.get('email')
phonenumber=request.POST.get('phonenumber')
en= Subscribe(firstname=firstname, secondname=secondname, email = email, phonenumber = phonenumber)
en.save()
return redirect('/')
return render(request, 'subscribe.html')
My models.py:
class Subscribe(models.Model):
firstname = models.CharField(max_length=30, blank = True)
secondname = models.CharField(max_length=30, blank = True)
email = models.CharField(max_length=30)
phonenumber = models.IntegerField()
Here is my template:
{% extends 'index.html' %}
{% block subscribe %}
<div class="card mx-5">
<h1 class="mx-5 mt-3"> Subscribe</h1>
<form method="POST" enctype="multipart/form-data" action="subscribe">
{% csrf_token %}
<div class="mb-3 mx-5">
<label for="firstname" class="form-label ">First Name</label>
<input type="text" class="form-control form-control-lg" id="firstname" placeholder="firstname">
</div>
<div class="mb-3 mx-5">
<label for="secondname" class="form-label">Second Name (Optional)</label>
<input type="text" class="form-control form-control-lg" id="secondname" placeholder="secondname">
</div>
<div class="mb-3 mx-5">
<label for="email" class="form-label">Email</label>
<input type="email" class="form-control form-control-lg" id="email" placeholder="example#example.com">
</div>
<div class="mb-3 mx-5">
<label for="phonenumber" class="form-label">Phonenumber</label>
<input type="number" class="form-control form-control-lg" id="phonenumber" placeholder="0712345678">
</div>
<div class="mb-3 mx-5">
<button type="submit" class="btn-primary"> Subscribe</button>
</div>
</form>
</div>
{% endblock %}
And my url patterns:
urlpatterns= [
path('', views.index, name='index'),
path('subscribe', views.subscribe, name ='subscribe'),
path('allposts', views.allposts, name='allposts'),
path('political', views.political, name='political'),
path('religion', views.religion, name='religion'),
path('trending', views.trending, name='treniding'),
path('<str:pk>', views.post, name='post'),
]
You should add a name="…" attribute [mdn] to the <input> elements, so:
<input type="text" name="firstname" class="form-control form-control-lg" id="firstname" placeholder="firstname">
…
<input type="text" name="secondname" class="form-control form-control-lg" id="secondname" placeholder="secondname">
…
<input type="email" name="email" class="form-control form-control-lg" id="email" placeholder="example#example.com">
…
<input type="number" name="phonenumber" class="form-control form-control-lg" id="phonenumber" placeholder="0712345678">
I am working on a small django-python project which has two models "staff_type" and "staff". In the staff_type model, only designation and date fields are populated. And in the staff model, there is OneToOneField relation of staff_type. Means whenever a user want to add staff first he/she will have to add staff_type and then in the staff module, user will choose the staff type (designation) from a select menu in which all the staff_type are shown respectively.
Now, whenever a user select any designation (staff_type) and fill the entire form, I want to store the selected staff_type id in the staff model/table.
Note: I have tried this from django admin, and it works perfectly but I want to do the same work in my own designed templates.
Modles.py
class staff_type(models.Model):
designation = models.CharField(max_length=50)
salary = models.IntegerField()
datetime = models.DateTimeField()
entrydatetime = models.DateTimeField( auto_now=False, auto_now_add=False)
class staff(models.Model):
staff_type = models.OneToOneField(staff_type, on_delete=models.CASCADE)
firstname = models.CharField(max_length=50)
lastname = models.CharField(max_length=50)
fathername = models.CharField(max_length=50)
city = models.CharField(max_length=50)
country = models.CharField(max_length=50)
state = models.CharField(max_length=50)
zip = models.IntegerField(blank=True)
address = models.CharField(max_length=100)
contact =models.CharField(max_length=20)
cnic = models.CharField(max_length=14)
photo = models.ImageField()
cv = models.ImageField()
otherfiles = models.ImageField()
views.py
def add_staff_type(request):
if request.method == 'POST':
designation = request.POST.get('designation')
salary = request.POST.get('salary')
datetime = request.POST.get('datetime')
add_staff_type = staff_type.objects.create(designation=designation, salary=salary, datetime=datetime, entrydatetime = dt.now())
add_staff_type.save()
messages.info(request, "Staff type has been Added.")
return redirect('add_staff_type')
else:
#fetching records from the database table
display_staff_type = staff_type.objects.all()
return render(request, 'staff/staff_type.html',{'display_staff_type':display_staff_type})
#this view is for fetching the designation column and displaying in the select tag
#and rendering add_staff html form
def add_staff(request):
staff = staff_type.objects.all()
return render(request, 'staff/add_staff.html', {'staff':staff})
#this view is for adding the staff
def add_staff_view(request):
if request.method == 'POST':
staff_type = request.POST.get('stafftype')
firstname = request.POST.get('firstname')
lastname = request.POST.get('lastname')
fathername = request.POST.get('fathername')
city = request.POST.get('city')
country = request.POST.get('country')
state = request.POST.get('state')
zipcode = request.POST.get('zip')
contact = request.POST.get('contact')
cnic = request.POST.get('cnic')
address = request.POST.get('address')
photo = request.FILES.get('photo')
cv = request.FILES.get('cv')
otherfiles = request.FILES.get('photo')
add_staff = staff.objects.create(firstname=firstname, lastname=lastname, fathername=fathername, city=city,country=country, state=state, contact=contact, cnic=cnic, zip=zipcode, address=address, photo=photo, cv=cv, otherfiles=otherfiles, staff_type=staff_type)
add_staff.save()
messages.info(request, "Staff has been Added.")
return redirect('add_staff')
else:
return render(request, 'staff/add_staff.html')
urls.py
urlpatterns = [
path("", views.index, name="index"),
path("staff/add_staff_type", views.add_staff_type, name="add_staff_type"),
path("staff/add_staff", views.add_staff, name="add_staff"),
path("staff/add_staff_view", views.add_staff_view, name="add_staff_view"),
]
add_staff.html
<form class="needs-validation" action="add_staff_view" method="POST" enctype="multipart/form-data" novalidate>
{% csrf_token %}
<div class="card-body">
<div class="form-row">
<div class="col-md-3 mb-3">
<label for="validationCustom01">Staff Type</label>
<select class="form-control" id="validationCustom01" name="stafftype">
{% for staff in staff %}
<option name="stafftype" value="{{ staff.id }}" required>{{staff.designation}}</option>
{% endfor %}
</select>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom02">First name</label>
<input type="text" class="form-control" id="validationCustom02" placeholder="First name" name="firstname" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom03">Last name</label>
<input type="text" class="form-control" id="validationCustom03" placeholder="Last name" name="lastname" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom04">Father Name</label>
<input type="text" class="form-control" id="validationCustom04" placeholder="Father Name" name="fathername" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-3 mb-3">
<label for="validationCustom05">City</label>
<input type="text" class="form-control" id="validationCustom05" placeholder="City" name="city" required>
<div class="invalid-feedback">
Please provide a valid city.
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom06">Country</label>
<input type="text" class="form-control" id="validationCustom06" value="Pakistan" name="country" required>
<div class="invalid-feedback">
Please provide a valid country.
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom07">State</label>
<input type="text" class="form-control" id="validationCustom07" placeholder="State" name="state" >
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom08">Zip</label>
<input type="number" class="form-control" id="validationCustom08" value="0000" name="zip">
</div>
</div>
<div class="form-row">
<div class="col-md-3 mb-3">
<label for="validationCustom09">Contact</label>
<input type="text" class="form-control" id="validationCustom09" placeholder="Phone Number" name="contact" required>
<div class="invalid-feedback">
Please provide a valid country.
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationCustom10">CNIC</label>
<input type="number" class="form-control" id="validationCustom10" placeholder="xxxxx-xxxxxxx-x" name="cnic" required>
<div class="invalid-feedback">
Please provide a valid country.
</div>
</div>
<div class="col-md-6 mb-3">
<label for="address">Address</label>
<input type="text" class="form-control" id="address" placeholder="Current Address" name="address">
</div>
</div>
<div class="form-row">
<div class="file col-md-4 mb-3">
<label class="file-label" for="customFile01">Photo</label>
<input type="file" class="form-control" id="customFile01" name="photo"/>
</div>
<div class="file col-md-4 mb-3">
<label class="file-label" for="customFile02">CV</label>
<input type="file" class="form-control" id="customFile02" name="cv"/>
</div>
<div class="file col-md-4 mb-3">
<label class="file-label" for="customFile03">Other Files/Photos</label>
<input type="file" class="form-control" id="customFile03" name="otherfiles"/>
</div>
</div>
<div classs="form-row">
<button class="btn btn-primary" type="submit">Add Staff</button>
</div>
</div>
</div>
</form>
I tried my best at the above code but it gives me the error.
Error
Exception Value:
Cannot assign "'1'": "staff.staff_type" must be a "staff_type" instance.
staff_type in staff model must be staff_type model instance so first get model instance
s_type = staff_type.objects.get(id=request.POST.get('stafftype'))
staff.objects.create(...,staff_type=s_type)
Or you can also assign fk directly like this.
staff.objects.create(staff_type_id=request.POST.get('stafftype'))
And please try to follow PEP8 standards for writing python codes.
Note: It's better using django forms and Also you can use built-in generic class-based views which will make your things easier.
The problem is that you are sending number to Staff model into the field "staff_type". You either need to cast it to staff_type, or put an instance there
I have tried to look around for this specific query on SO, but could not find one.
I am new to Django and am using version 1.10 and python 3.4.
For the checkboxes I am using them in the template itself.
For some reason I am hesitant in using the checkbox widget in the forms.py file, I think it will disturb my existing UI(please correct me if I am wrong).
When I submit the form, the template returns blank quotes for the number of checkboxes I have ticked.
Here is my model:
class UsrGrpMaster(models.Model):
SrNo =models.IntegerField(unique=True)
UsrGrpID = models.AutoField(primary_key=True)
GrpName = models.CharField(max_length=50)
Purch = models.BooleanField(default=False)
PurchMod = models.BooleanField(default=False)
Sales = models.BooleanField(default=False)
SalesMod = models.BooleanField(default=False)
Stock = models.BooleanField(default=False)
StockMod = models.BooleanField(default=False)
JV = models.BooleanField(default=False)
JVMod = models.BooleanField(default=False)
DelPurch = models.BooleanField(default=False)
DelSales = models.BooleanField(default=False)
DelJV = models.BooleanField(default=False)
class Meta:
db_table = "UsrGrpMaster"
Here is my template:
<div class="body-set">
<div id="form">
<form class="form-horizontal" method="POST" action="{% url 'creategroup' %}">
<div class="form-group" align="center">
<label class=""><font size="6">Create a New User Group</font></label>{% if errormsg %}<br />
<font size="3" color="#FF0000">{{ errormsg }}</font>{% endif %}
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="text">Name of the User Group:</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="grpname" placeholder="Type in the new User Group Name" name="grpname">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="text">Permissions:</label>
<div class="col-sm-5">
<div><strong>Purchase Voucher</strong></div>
<label class="checkbox-inline"><input type="checkbox" name="checks[]" value="1">View</label>
<label class="checkbox-inline"><input type="checkbox" name="checks[]" value="2">Edit</label>
<label class="checkbox-inline"><input type="checkbox" name="checks[]" value="3">Delete</label>
</div><br /><br /><br />
<label class="control-label col-sm-4" for="text"></label>
<div class="col-sm-5">
<div><strong>Sales Voucher</strong></div>
<label class="checkbox-inline"><input type="checkbox" name="checks[]" value="4">View</label>
<label class="checkbox-inline"><input type="checkbox" name="checks[]" value="5">Edit</label>
<label class="checkbox-inline"><input type="checkbox" name="checks[]" value="6">Delete</label>
</div><br /><br /><br />
<label class="control-label col-sm-4" for="text"></label>
<div class="col-sm-5">
<div><strong>Stock</strong></div>
<label class="checkbox-inline"><input type="checkbox" name="checks[]" value="7">View</label>
<label class="checkbox-inline"><input type="checkbox" name="checks[]" value="8">Edit</label>
</div><br /><br /><br />
<label class="control-label col-sm-4" for="text"></label>
<div class="col-sm-5">
<div><strong>Journal Voucher / Income-Expense Voucher / Ledgers</strong></div>
<label class="checkbox-inline"><input type="checkbox" name="checks[]" value="9">View</label>
<label class="checkbox-inline"><input type="checkbox" name="checks[]" value="10">Edit</label>
<label class="checkbox-inline"><input type="checkbox" name="checks[]" value="11">Delete</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-5">
<button type="submit" class="btn btn-primary">Create User Group</button>
</div>
</div>
</form>
</div>
Here is the class based View:
class CreateGroup(View):
#never_cache
def get(self, request, *args, **kwargs):
if 'adminusr' in request.COOKIES:
if request.session.get('errormsg', None):
errormsg = request.session['errormsg']
del request.session['errormsg']
else:
errormsg = ''
return render(request, 'adminpage/creategroup.html', {"errormsg": errormsg})
else:
return HttpResponseRedirect("/adminpage/")
def post(self, request, *args, **kwargs):
if request.method == 'POST':
GrpName = request.POST.get('grpname')
chq = request.POST.getlist('checks[]')
print(chq)
value = sninc(UsrGrpMaster, 'SrNo') #increments the sn and stores in DB
if checkduplicates(UsrGrpMaster, 'GrpName', GrpName) is not True:
qs = UsrGrpMaster(SrNo=value, GrpName=GrpName,
Purch=chq[1],
PurchMod=chq[2],
Sales=chq[4],
SalesMod=chq[5],
Stock=chq[7],
StockMod=chq[8],
JV=chq[9],
JVMod=chq[10],
DelPurch=chq[3],
DelSales=chq[6],
DelJV=chq[11]
)
qs.save()
else:
request.session['errormsg'] = "The user group already exists"
return HttpResponseRedirect("/adminpage/adminhome/creategroup/")
return HttpResponseRedirect("/adminpage/adminhome/")
Here is the browser and console clipping. Checked 9 boxes and submit shows 9 empty quotes.
template_browser_clipping
console_clipping
I want the form to provide me the value property of the checked boxes so I can store them in the database. Please guide me as to how to achieve this (with or without using forms.py).
Here is the Javascript:
$(document).ready(function(){
$('form').submit(function() {
if ($.trim($('input[name="grpname"]').val()) === "") {
$('input[name="grpname"]').css({'background-color' : '#ffe5e5'});
return false;
}
});
$('input').focusin(function() {
$(this).css({'background-color' : '#ffffff'});
});
$('input').blur(function() {
if ($.trim($(this).val()) === "") {
$(this).css({'background-color' : '#ffe5e5'});
}
});
});
I'm using Python Pyramid with Jinja2 template. I want to save my form data into session and retrieve it in another HTML page. How should I change in order to pass the data? I only know how to store the data I key in Views.py into session like this request.session['postal'] = 01934 but this is not the data I key in Delivery.jinja2. And if I used print (session['postal']), this will only show in my command prompt but not HTML page. Can anyone help me out? I'm a beginner to this.
What to add in/ change in my Views.py?
my HTML: Delivery.jinja2
<form class="form-horizontal" method="POST">
<div class="form-group">
<label class="control-label col-md-2" for="postal">Postal Code:</label>
<input type="text" class="form-control" id="postal" placeholder="Enter Postal Code" name="postal" />
</div>
<div class="form-group">
<label class="control-label col-md-2" for="address">Detailed Address:</label>
<textarea class="form-control" rows="3" id="address" placeholder="Enter Address" name="address"></textarea>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="unit">Unit No #:</label>
<input type="text" class="form-control" id="unit" placeholder="Enter Unit No" name="unit" />
</div>
<button type="submit" class="btn btn-default" name="submit">Submit</button>
</form>
Views.py
#view_config(route_name='deliveryLink', renderer='templates/deliveryLink.jinja2')
def deliveryLink(request):
print("YAY for gift delivery via Link")
if 'submit_deliverylink' in request.POST:
print("request.POST: ", request.POST)
myform = request.POST
for m in myform:
print("key: ", m, " value: ", myform[m])
session = request.session
session['postal'] = ?
session['address'] = ?
session['unit'] = ?
data = "??"
data_array = data.split(",")
session['data'] = data_array
session['delivery'] = str(data_array)
print (session['delivery'])
return HTTPFound(location='http://localhost:5555/confirmation')
return {}
#view_config(route_name='confirmation', renderer='templates/confirmation.jinja2')
def confirmation(request):
print("YAY for confirmation")
for a in request.POST:
request.session[a] = request.POST[a]
return {}
and I want the data entered previously to show on this confirmation page: Confirmation.jinja2
<form class="form-horizontal" method="POST">
<div class="form-group">
<label class="control-label col-md-2" for="postal">Postal Code:</label>
<input type="text" class="form-control" id="postal" name="postal" />
</div>
<div class="form-group">
<label class="control-label col-md-2" for="address">Detailed Address:</label>
<textarea class="form-control" rows="3" id="address" name="address"></textarea>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="unit">Unit No #:</label>
<input type="text" class="form-control" id="unit" name="unit" />
</div>
</form>
I think, you can just pass POST from initial form to template of confirmation page, without session.
If anyway you need session, you can call it from your template
<input type="text" class="form-control" id="postal" name="postal" value="{{session['postal']}}" />
# after form submitted, it sends post request, just check if it exist
if request.POST:
print("request.POST: ", request.POST)
myform = request.POST
# you need iterate over keys for this case
for m in myform.keys():
print("key: ", m, " value: ", myform[m])
session = request.session
# you can access request.POST directly or use your variable myfrom
# use myform.get('postal','') to get value by key
session['postal'] = myform.get('postal','')
session['address'] = myform.get('postal','')
session['unit'] = myform.get('unit','')
data = "??"
data_array = data.split(",")
session['data'] = data_array
session['delivery'] = str(data_array)
print (session['delivery'])
return HTTPFound(location='http://localhost:5555/confirmation')