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()
Related
I'm not sure if it's possible. I'm trying to use Django (2.0) Form and Formset
on a view. Here is my models:
from uuid import uuid4
class Aliment(models.Model):
id = models.CharField(max_length=36, primary_key=True, unique=True, default=uuid4, editable=False)
libelle = models.CharField(max_length=50)
def __str__(self):
return self.libelle
class Menu(models.Model):
id = models.CharField(max_length=36, primary_key=True, unique=True, default=uuid4, editable=False)
libelle = models.CharField(max_length=50)
aliments = models.ManyToManyField(Aliment, through='Ingredient')
def __str__(self):
return self.libelle
class Ingredient(models.Model):
id = models.CharField(max_length=36, primary_key=True, unique=True, default=uuid4, editable=False)
aliment = models.ForeignKey(Aliment, on_delete=models.CASCADE)
menu = models.ForeignKey(Menu, on_delete=models.CASCADE)
quantite = models.IntegerField(default=0)
def __str__(self):
return "({0}:{1})".format(self.quantite, self.aliment)
I'm using Formset to handle ('aliment', 'quantite') from Ingredient. Here is my forms:
class MenuModelForm(forms.ModelForm):
class Meta:
model = Menu
fields = ['libelle',]
class IngredientModelForm(forms.ModelForm):
class Meta:
model = Ingredient
fields = ['aliment', 'quantite',]
The main purpose is, Menu have several Aliment through Ingredient class.
With javascript, I dynamically add Aliment item from one list (list1) to Menu.Ingredient list (list2).
The only way for the user to add item in list2 is by clicking some "add button" of list1.
The problem is ModelChoiceField comes with select that contains all Aliment instance from database.
I would to manage a kind of tuple ('aliment.id', 'aliment.libelle', 'quantite') for each Ingredient
that belongs to Menu instance.
One the one hand, I could be able to display in my Ingredient formset template, something like this :
<table>
{% for item in menu.ingredient %}
<tr>
<td>
<p name="{{ item.aliment.html_name }}" id="{{ fs.aliment.id_for_label }}"
value="{{ item.aliment.id }}">{{ fs.aliment.libelle }}</p>
</td>
<td><input type="number" name="{{ item.quantite.html_name }}" value="{{ item.quantite.value }}" id="{{ item.quantite.id_for_label }}" /></td>
</tr>
{% endfor %}
</table>
On the other hand, what is the way for getting Aliment instance of Ingredient formset iteration ?
I don't know if Django Form and Django philosophy are made for this.
Could you make some suggestions please.
Thanks !
I realized I was confused when asking question. I will try to
be more concise next time.
Anyway, I found a solution to many problem (Maybe you will understand what I meant :p).
I added libelle field to my IngredientModelForm like this :
class IngredientModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
print(kwargs['instance'])
self.fields['libelle'].initial = kwargs['instance'].aliment.libelle
class Meta:
model = Ingredient
fields = ['aliment', 'quantite',]
libelle = forms.CharField(max_length=50)
So I can access to libelle field in my template.
In my view file I did like this :
def add_menu(request):
ingredientFormSet = modelformset_factory(Ingredient, form=IngredientModelForm, fields=('aliment', 'quantite'), extra=0)
if request.method == 'POST':
form = MenuForm(request.POST)
formset = ingredientFormSet(request.POST)
if form.is_valid() and formset.is_valid():
...
else:
menu = Menu.objects.all()[0]
form = MenuModelForm(instance=menu)
formset = ingredientFormSet(queryset=menu.ingredient_set.all())
So for each IngredientModelForm instance, its initial value for libelle field will be the value
of the Aliment instance attached to Ingredient.
Let's take a look at template :
<form action="" method="POST">
{{ formset.management_form }}
<ul>
{% for fs in formset.forms %}
<li>
{{ fs.id.label_from_instance }}
<span><input type="hidden" name="{{ fs.id.html_name }}" value="{{ fs.id.value }}" id="{{ fs.id.id_for_label }}" /></span>
<span><input type="hidden" name="{{ fs.aliment.html_name }}" value="{{ fs.aliment.value }}" id="{{ fs.aliment.id_for_label }}" /></span>
<span>{{ fs.libelle.value }}<input type="hidden" name="{{ fs.libelle.html_name }}" value="{{ fs.libelle.value }}" id="{{ fs.libelle.id_for_label }}" /></span>
<span><input type="number" name="{{ fs.quantite.html_name }}" value="{{ fs.quantite.value }}" id="{{ fs.quantite.id_for_label }}" /></span>
</li>
{% endfor %}
</ul>
<input type="submit" value="Ajouter" />
</form>
So, I can display name of Aliment with a select widget (because my Aliment choices are managed with an other list).
I don't know if it's a good practice for Django.
Feel free to suggest an other simple solution ! :)
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 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>
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()