i want to auto increament for car_id field which is primary key but after saving registration data the car_id field should automaticaly increament so please anyone can suggest me for this.and my code is as follow.
models.py
class car(models.Model):
car_id = models.IntegerField(max_length=400, primary_key=True)
plate_no = models.IntegerField(max_length=400)
brand = models.CharField(max_length=400)
model = models.CharField(max_length=400)
Condition = models.CharField(max_length=400)
daily_price = models.IntegerField()
def __str__(self):
return ' '.join([
self. ordering,
])
views.py
def display_car(request):
carid_query = car.objects.values('car_id')
plate = car.objects.values('plate_no')
brand = car.objects.values('brand')
model = car.objects.values('model')
price = car.objects.values('daily_price')
condition = car.objects.values('Condition')
query_all = car.objects.all()
data={
'carid_query': carid_query,
'plate': plate,
'brand': brand,
'model': model,
'price': price,
'condition': condition,
'query_all': query_all,
}
return render(request, 'view_car.html', data)
HTML
<body>
<div class="center">
Home  Car Registration  Rent
</div>
<form action="/car/" id="form_id" method="post">
{% csrf_token %}
<div id="head_div">
<h3>car Registration</h3></div>
<table class="center">
<tr><td>
Car_id:<input type="text" name="car_id"><td>
<td>plate no:<input type="text" id="plate_id" name="plate_id"></td></tr>
<tr><td>Brand:<input type="text" id="brand_id" name="brand_id"><td>
<td>Model:<input type="text" name="model_id"></td></tr>
<tr><td>
Daily Price:<input type="text" id="price_id" name="price_id"></td>
<td>
Condition:<select name="select_id"><option value="Good">simple</option>
<option value="middle">A/C</option>
<option value="bad">good</option></select></td>
</tr>
<tr>
<td><input type="submit" id="sub_id" onclick="demo(this.form)"> <input type="button" id="cancel_id" VALUE="Cancel"></td>
</tr>
</table>
</form>
</body>
Related
this is my template code:
if request.method == 'POST':
#------Invoice
#-----Invoice details
form = InvoiceReportEntries(request.form)
# items = []
for item in form.items:
lineitem = InvoiceLineItem(description=item.description,
amount=item.amount,
invoice_id=invoice.id)
db.session.add(lineitem)
db.session.commit()
My template is:
<form method="POST">
{{ form.hidden_tag() }}
<table>
<tr class="heading">
<td>
Item
</td>
<td>
Price
</td>
</tr>
<tr class="item">
<div>
<td>
<input id={{ items|length }} name="description-{{ items|length }}" required="" type="text" value="">
</td>
<td>
<input id={{ items|length }} name="amount-{{ items|length }}" required="" type="text" value="">
</td>
</div>
</tr>
It seems that my form on submit does not work well as I've this error:
sqlalchemy.exc.StatementError: (builtins.TypeError) float() argument
must be a string or a number, not 'DecimalField' [SQL: INSERT INTO
invoice_line_item (description, amount, invoice_id) VALUES (?, ?, ?)]
[parameters: [{'description': '', 'invoice_id': 14, 'amount':
<wtforms.fields.core.DecimalField object at 0x10bc52510>}]]
and data form for items are:
{'items': [{'description': '', 'amount': None, 'id': '', 'csrf_token': ''}], 'csrf_token': 'xxxx'}
But I d filled values in my template?
description was 'test' and amount was 23
I will have more Thant one row in this table so I should identified each of them to save them in DB
Thanks for help
UPDATE:
My models :
class InvoiceLineItem(db.Model):
id = db.Column(db.Integer, primary_key=True)
description = db.Column(db.String, nullable=False)
amount = db.Column(db.Float, nullable=False)
invoice_id = db.Column(db.Integer, db.ForeignKey('invoice.id'), nullable=False)
def __init__(self, description, amount, invoice_id):
self.description = description
self.amount = amount
self.invoice_id = invoice_id
my forms.py:
class InvoiceitemForm(Form):
description = StringField('Description', validators=[DataRequired()])
amount = DecimalField('Amount', validators=[DataRequired()])
id = HiddenField('id')
class InvoiceReportEntries(Form):
items = FieldList(FormField(InvoiceitemForm), min_entries=1)
Just I quick advice, so you should've add also the wtforms forms.py and the 'Models.py.'
Hanving sayd that the error you're receiving is quite explicit:
sqlalchemy.exc.StatementError: (builtins.TypeError) float() argument must be a string or a number, not 'DecimalField'
What is referring to?
Well as I said I can fully determined why because some snaps of the code is missing, however the error codes speaks by itself:
amount': <wtforms.fields.core.DecimalField object at 0x10bc52510>
This is because you are calling the Class but not the instance of the class. In fact I guess you have in the forms.py the 'DecimalField', for more info --_> Here.
I can then see the HTML, there isn't the WTFORMS jinja tag but a standar HTML Tag input, this:
<input id={{ items|length }} name="amount-{{ items|length }}" required="" type="text" value="">
So I suggest to remove this and add the following:
{{ form.amount.label }}
{{ form.amount(class='yourclass') }}
Instead of the required="", add in the forms.py:
InputRequired() or DataRequired()
InputRequired()
DataRequired()
To make it clearer, I want to create an e-commerce app for installment stores
I prepared a short HTML template at the bottom of the question
I have the following model:
class App_form(models.Model): #This is the head model
id_customer = models.CharField(max_length=200)
name = models.CharField(max_length=150, unique=True)
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,12}$', message="Phone number must be entered in the format: '998981234567'. Up to 12 digits allowed.")
phone_number = models.CharField(validators=[phone_regex], max_length=13, unique=True)
#Models which I should combine and which will be named as: products_with_period model and it should belong only and only to this App_form model
warehouse = models.ManyToManyField(Warehouse)
product_period = models.OneToOneField(Product_period, on_delete=models.CASCADE)
def __str__(self):
return self.surname
#Product period
class Product_period(models.Model):
product_period = models.CharField(max_length=200, unique=True)
product_percent = models.FloatField()
product_periodvalue = models.FloatField()
def __str__(self):
return self.product_period
#Warehouse model
class Warehouse(models.Model):
category_product = models.ForeignKey(Category_product, on_delete=models.CASCADE)
product_name = models.CharField(max_length=200, unique=True)
condition = models.BooleanField(default=False)
amount = models.IntegerField()
barcode = models.BigIntegerField()
f_price = models.CharField(max_length=255, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.product_name
What I want to achieve in my Rest Api out only from combined products_with_period model
products_with_period = [{
id: 1,
product_name: " ",
product_fprice: " ",
product_period: {
"id": 2,
"product_period_name": " ",
"product_period_percent": " ",
},
{
id: 2,
product_name: " ",
product_fprice: " ",
product_period: {
"product_period": " ",
"product_period_percent": " ",
},
}],
Here is the HTML template, which explains the essence
function addProduct() {
var table = document.getElementById("ProductTable");
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = `
<div class="form-group">
<select class="form-control" >
<option value="1">Smartphone</option>
<option value="2">Smart TV</option>
<option value="3">Laptop</option>
<option value="4">Desktop</option>
<option value="5">Sofa</option>
<option value="6">Bicycle</option>
</select>
</div>
`;
cell2.innerHTML = `
<div class="form-group">
<select class="form-control" >
<option value="1">3 months</option>
<option value="2">6 months</option>
<option value="3">12 months</option>
<option value="4">24 months</option>
</select>
</div>
`;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<div class="container">
<div class="row">
<div class="col-md-12 p-4">
<div class="form-group">
<label for="c_name">Customer name:</label>
<input class="form-control" id="c_name" type="text">
</div>
<div class="form-group">
<label for="c_phone">Customer phone:</label>
<input class="form-control" id="c_phone" type="tel">
</div>
</div>
<table class="table table-bordered" id="ProductTable">
<thead>
<tr>
<th>Product name:</th>
<th>Installment period:</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="form-group">
<select class="form-control">
<option value="1">Smartphone</option>
<option value="2">Smart TV</option>
<option value="3">Laptop</option>
<option value="4">Desktop</option>
<option value="5">Sofa</option>
<option value="6">Bicycle</option>
</select>
</div>
</td>
<td>
<div class="form-group">
<select class="form-control">
<option value="1">3 months</option>
<option value="2">6 months</option>
<option value="3">12 months</option>
<option value="4">24 months</option>
</select>
</div>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2" class="text-center">
<button class="btn btn-success" onclick="addProduct()">add new product</button>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
You could try something like this (which is not using Django-rest and there is probably a way to do this with serializers, but this is what I came up with off the top of my head):
from django.http import JsonResponse
def product_api(request):
app_forms = App_form.objects.filter(product_period__isnull=False).all()
products_with_period = []
data = {}
for form in app_forms:
data['id'] = form.id
data['product_name'] = form.name
...
data['product_period']['id'] = form.product_period.id
data['product_period']['product_period_name'] = form.product_period.product_period
...
products_with_period.append(data)
data = {}
if request.is_ajax():
return JsonResponse(products_with_period)
else:
return HttpBadRequest()
This can then be injested by an AJAX function in the template:
<script type="text/javascript">
$("#button_or_object_id").click(function(){
$.ajax({
url: '{% url 'product_api' %}',
type: "GET",
dataType: "json",
cache: false
}).done(function(products_with_period) {
// do something with the products_with_period data
});
});
});
</script>
Otherwise, you can also render it in the context:
def product_api(request):
app_forms = App_form.objects.filter(product_period__isnull=False).all()
products_with_period = []
data = {}
for form in app_forms:
data['id'] = form.id
data['product_name'] = form.name
...
data['product_period']['id'] = form.product_period.id
data['product_period']['product_period_name'] = form.product_period.product_period
...
products_with_period.append(data)
data = {}
return render(request, 'template.html', context={'products_with_period':products_with_period})
And then render the array of dicts in your template manually.
I have a form in my site to get a report about some "collective payment". It has 3 main field: Value, date of payment and who paid.
The field "who paid" is a table containing the name of all users and a checkbox.
Currently I'm looping over all users, adding their full names to the table with a single checkbox. But I don't know how to get this data in my form associating it with each user name (just the text).
How can I get multiple BooleanFields in my form ? Is there a way of associate each BooleanField with an user's name?
model.py
from django.db import models
#created_date attibute needs it
from django.utils import timezone
# This Model is a super class "Financial Transaction"
class GroupTransaction(models.Model):
name = models.CharField(max_length=257, default='')
who_paid = models.CharField(max_length=257, default='')
value = models.DecimalField(max_digits=6, decimal_places=2)
justification = models.CharField(max_length=257, default='')
created_date = models.DateTimeField(default=timezone.now)
date = models.CharField(max_length=257, default='')
receipt = models.FileField(upload_to='comprovantes', blank=True, null=True)
its_type = models.CharField(max_length=257, default='')
def __str__(self):
#INCOMPLETOreturn "%s fez a movimentação financeira de %d para %s no dia " % (self.name, self.restaurant)
return "%s - %s" % (self.name , self.who_paid)
view.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from deposit.forms import DepositForm,MonthlyDepositForm
from django.contrib.auth.models import User
# Create your views here.
#login_required
def deposito(request):
if request.method == 'POST':
form = DepositForm(request.POST, request.FILES)
if form.is_valid():
form.save()
HttpResponseRedirect('/historico/')
else:
print (str(form.errors.as_data()))
else:
form = DepositForm()
groupForm = MonthlyDepositForm()
return render(request, 'shell/app_shell.html', {
'is_deposit' : True,
'title' : 'Deposit',
'transaction' : form,
'groupTransaction' : groupForm,
'users': User.objects.all()
})
form.py
class MonthlyDepositForm(forms.ModelForm):
value = forms.DecimalField()
date = forms.CharField(widget=forms.TextInput(attrs={
'class':'datepicker picker__input',
'readonly':'',
'tabindex':'54',
'aria-haspopup':'True',
'aria-expanded':'false',
'aria-readonly':'false',
'aria-owns':'birthdate_root'
}))
who_paid = forms.BooleanField()
its_type = forms.CharField(widget=forms.HiddenInput(attrs={'readonly':True}),
initial='Deposito Mensal')
class Meta:
model = GroupTransaction
fields = ('value', 'date','who_paid','its_type')
template.html:
<form class="col s12">
{% csrf_token %}
{{ groupTransaction.its_type }}
<div class="row"></div>
<!-- Nome do evento -->
<div class="row">
<div class="input-field col s6">
<!-- <input id="nome_evento" type="number" value="10" step="any" min="0.05" max="400" class="validate" required> -->
{{ groupTransaction.value }}
<label for="nome_evento">Value</label>
</div>
<div class="input-field col s6">
<!-- <input type="text" class="datepicker picker__input" readonly="" tabindex="54" aria-haspopup="true" aria-expanded="false" aria-readonly="false" aria-owns="birthdate_root" required> -->
{{ groupTransaction.date }}
<label for="data-mensal" data-error="Data inválida">Date</label>
</div>
</div>
<!-- Petianos que irão para o evento -->
<table class="striped">
<thead>
<!-- Cabeçalho tabela -->
<tr>
<th>Who Paid</th>
<th>
<div class="switch">
<b class="center-align">Default</b>
<label>
<input type="checkbox">
<span class="lever"></span>
</label>
</div>
</th>
</tr>
<!-- ============= -->
</thead>
<tbody>
{% for user in users %}
<tr>
<td>{{ user.get_full_name }}</td>
<td>
<div class="switch">
<label>
<!-- <input type="checkbox"> -->
{{ groupTransaction.who_paid }}
<span class="lever"></span>
</label>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="row"></div>
<div class="row"></div>
<!-- Botão de registrar saque (submit) -->
<div class="row">
<button class="btn waves-effect waves-light col s6 m3 offset-s6 offset-m9 blue" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</div>
</form>
How the form is:
You need to make who_paid a ManyToManyField(User). Then in the form you can set its widget like this:
class Meta:
model = GroupTransaction
fields = ('value', 'date','who_paid','its_type')
widgets = {
'who_paid': forms.CheckboxSelectMultiple(),
}
That will give you the right structure. Then you can render it manually if you want to change the display.
I have googled several hours but couldn't understand how to write sql join(raw or ORM) related queries.
Below is my model with two tables sandBox1 and licenseType where they will have common item "email" on which join will be performed
class sandBox1(models.Model):
email = models.EmailField(unique=True)
name = models.CharField(max_length=200)
website = models.TextField(validators=[URLValidator()])
comment = models.TextField(default='-')
gender = models.CharField(max_length=6)
def __str__(self):
return self.email
class licenseType(models.Model):
#1=other, 2=two-wheeler 4=four-wheeler
licenseId = models.IntegerField()
email = models.EmailField()
template file : index.html
<html><form id="form1" method="post" action="{% url "sandbox" %}">
{% csrf_token %}
Name: <input type="text" name="name" >
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website" >
<span class="error"></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<hr>Check the license type you have:-<br>
<input type="checkbox" name="license[]" value=2 > 2 wheeler<br>
<input type="checkbox" name="license[]" value=4 > 4 wheeler<br>
<input type="checkbox" name="license[]" value=1 > Other <br>
<br>
<input type="submit" name="submit" value="Submit">
</form>
<div>
{% for obj in sandBoxObj %}
<p>
{{ obj.name }}<br>
{{ obj.email }}<br>
{{ obj.website }}<br>
{{ obj.gender }}<br>
{{ obj.comment }}<br>
{% endfor %}
</div>
</html>
here is a view file that needs correction. I want to show the result of this sql query:
select sandBox1.email,sandBox1.name,licenseType.licenseId from sandBox1
innerjoin licenseType on sandBox1.email=licenseType.email;
View file
def sandbox(request):
template_name='domdom.html'
sandBoxObj = sandBox1.objects.all()
context = { 'sandBoxObj':sandBoxObj }
print request.POST
if request.method == 'POST':
website=request.POST.get('website','')
comment=request.POST.get('comment','')
name=request.POST.get('name','')
gender=request.POST.get('gender','')
email=request.POST.get('email', '')
license=request.POST.getlist('license[]')
for id in license:
licInst = licenseType(licenseId=id,email=email)
licInst.save()
sbinstance = sandBox1(website=website,comment=comment,name=name,gender=gender,email=email)
sbinstance.save()
return render(request,template_name,context)
Raw sql method/ but im still confused on ORM method
def sandbox(request):
template_name='domdom.html'
sandBoxObj = sandBox1.objects.all()
con = sqlite3.connect('/home/user1/PycharmProjects/djrest/invoicesproject/db.sqlite3') #sqlite database file location
cursor = con.cursor()
cursor.execute(''' select todos_sandBox1.email,todos_sandBox1.name,todos_sandBox1.website,todos_sandBox1.comment,todos_sandBox1.gender,todos_licenseType.licenseId from todos_sandBox1
join todos_licenseType on todos_sandBox1.email=todos_licenseType.email
''') #it looks like django appends app name to table eg. appname = todos
result = cursor.fetchall()
#https://www.youtube.com/watch?v=VZMiDEUL0II
context = { 'result':result }
print request.POST
if request.method == 'POST':
website=request.POST.get('website','')
comment=request.POST.get('comment','')
name=request.POST.get('name','')
gender=request.POST.get('gender','')
email=request.POST.get('email', '')
license=request.POST.getlist('license[]')
for id in license:
licInst = licenseType(licenseId=id,email=email)
licInst.save()
sbinstance = sandBox1(website=website,comment=comment,name=name,gender=gender,email=email)
sbinstance.save()
return render(request,template_name,context)
Sorry if this answers the wrong question, but you may want to consider a different data model/ architecture. You are hardcoding SANDBOX1 which implies that there might be multiple Sandboxes and you are listing email fields which aren't tied to the User object. Some basic abstractions may simplify the work. Maybe something like:
from django.contrib.auth.models import User
...
class LicenseTypes(models.Model):
name = models.CharField(max_length=500)
class Customer(models.Model):
name = models.CharField(max_length=500)
license = models.ForeignKey(LicenseType)
class RegisteredUser(models.Model):
customer = models.ForeignKey(Customer, on_delete = models.CASCADE)
user = models.ForeignKey(User)
I like this architecture better because it uses a lot more native django functionality. And makes joins really basic. Check this out in a view:
def django_view(request):
registered_user = RegisteredUser(user=request.user)
#example of how to use the join implicitly/ directly
license = registered_user.customer.license.name
I am trying to insert values into postgress for a simple registration form but it is not inserting the values into the database.
I tried this code.
.HTML
<form id="form_id" method="post">
{% csrf_token %}
<h1>Registration</h1>
<body>
<table class="center">
<tr>
<td>Name:<input type="text" id="nm_id"></td>
</tr>
<tr><td>Address:<input type="text" id="ad_id">
</td>
</tr>
<tr><td>Email:<input type="text" id="em_id"></td></tr>
<tr><td> Mob No:<input type="text" id="mo_id"></td></tr>
</table>
<input type="submit" id="sub_id">
</form>
View.py
def dc(request):
n=request.POST.get["Name"]
ad=request.POST.get["Add"]
em=request.POST.get["Email"]
m=request.POST.get["mo"]
queryset1=registration.objects.values("n")
queryset2=registration.objects.values("ad")
queryset1=registration.objects.values("em")
queryset1=registration.objects.values("m")
return render(request,'demo1.html')
Models.py
class registration(models.Model):
Name = models.CharField(max_length=255)
Add = models.CharField(max_length=255)
email = models.CharField(max_length=400)
mo = models.CharField(max_length=400)
but its not work properly can anybody helpme for registration of these fields?
You need to create and save the instance.
new_user = registration(Name=n,Add=ad,email=em,mo=m)
new_user.save()