Validation Error in Python Django - python

I have HTML form with one optional field like this
<input type="number" name="total_amount" id="total_amount" class="completedtype" onchange="add()"/>
When I input some number in the field then I the whole form data gets saved in to the database. But when there is no data then I get Validation Error
ValidationError at /oms_data/ [u"'' value must be a decimal number."]
I have tried to resolve this issue for more than half a day but nothing helped me. I have tried the following to resolve this error.
I have used something like this which was suggested in some SO answer:
total_amount = request.POST.get("total_amount",0) ## get total_amount or take default value 0
That didn't work so I used the famous try: except: as shown below:
try:
total_amount = request.POST["total_amount"]
except: ## whatever the exception and not just Validation Error
total_amount = 0
I don't know why none of this worked.The error occurs when trying to save the form.
save_Order_Selling_Pricing = models.Order_Selling_Pricing(order_id=order_id,vendor_name = vendor_name,total_amount =total_amount,
vendor_discount_percent=vendor_discount_percent,dg_percent = dg_percent,
vendor_discount_amount=vendor_discount_amount,vendor_percent = vendor_percent,
dg_discount_percent = dg_discount_percent,dg_discount_amount=dg_discount_amount,
final_selling_price = final_selling_price,order_selling_pricing_id=order_selling_pricing_id,
order_payment_mode = order_payment_mode,present_datetime=present_datetime)
save_Order_Selling_Pricing.save()
Any help in this regard would be great!
Thanks in advance! I'm using Django 1.8 python 2.7 if this helps.
UPDATE 1:
I have my models defined as shown below:
total_amount = models.DecimalField(max_digits=10,decimal_places=2,blank = True,null = True,default = Decimal('0.00'))

Related

Many2one field in a Custom Setting page in Odoo

I am trying to add many2one field in a setting page in odoo11. I am able to add char or integer field in a setting page but with Many2one field I get an error.
The Error :
psycopg2.DataError: invalid input syntax for integer:"double.accounts(406,)"
LINE 1: ...FROM "double_accounts" WHERE "double_accounts".id IN ('double.acco...
here is my code :
class AccountSetting(models.TransientModel):
_inherit = 'res.config.settings'
authtoken_module = fields.Char(default_model='account.move')
organization_module = fields.Char(default_model='account.move')
double_accounts_id = fields.Many2one('double.accounts', string="double Entery", default_model='account.move')
def get_values(self):
res = super(AccountSetting, self).get_values()
res.update({
'authtoken_module': self.env['ir.config_parameter'].sudo().get_param('account.authtoken_module', default=''),
'organization_module': self.env['ir.config_parameter'].sudo().get_param('account.organization_module'),
#### the error that i am facing from this line
'double_accounts_id': self.env['ir.config_parameter'].sudo().get_param('account.double_accounts_id', default=''),
####
})
return res
def set_values(self):
super(AccountSetting, self).set_values()
self.env['ir.config_parameter'].sudo().set_param('account.authtoken_module', (self.authtoken_module or ''))
self.env['ir.config_parameter'].sudo().set_param('account.organization_module', (self.organization_module or ''))
self.env['ir.config_parameter'].sudo().set_param('account.double_accounts_id', (self.double_accounts_id or ''))
Haven't looked very well into it. But it seems you get a recordset out of your parameter instead of an ID. So a simple solution is to put a .id to the end of the marked line. But that isn't the full solution, cause your default has to be changed to self.sudo().env['account.double_accounts_id'], where .id will work, too.
I'm really wondering why you get a recordset, maybe someone can answer that.

WTForms - DateTimeLocalField data is None after submit

After form is submitted with a POST request, every Field data has its value, except DateTimeLocalField. Accessing DateTimeLocalField's data value is a type of None.
Form
class ArticleForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
category = SelectField(u'Category', choices=categories.choices)
town = StringField('Town', validators=[DataRequired()])
minimal_price = IntegerField('Minimal price')
article_image = FileField('Article_image', validators=[FileRequired()])
time_left = DateTimeLocalField('Time to end', validators=[InputRequired()],
format='%Y-%m-%d %H:%M:%S')
description = TextAreaField('Description', validators=[DataRequired()])
Validation: (tested with is_submitted, all work except for article_form.time_left.data which is None)
if article_form.validate_on_submit():
new_article = Article(name=article_form.name.data,
category=article_form.category.data,
town=article_form.town.data,
minimal_price=article_form.minimal_price.data,
article_image=name,
time_left=article_form.time_left.data, # <-- None
description=article_form.description.data,
user_id=current_user.id)
Any help to get data from DateTimeLocalField ?
Try changing the format of the DateTimeLocalField from
format='%Y-%m-%d %H:%M:%S'
to:
format='%Y-%m-%dT%H:%M'
Tip: you can print the actual content of the input field prior to the validation to confirm the correct formatting of the DateTimeLocalField field.
Use wtforms.fields.html5.DateTimeLocalField instead of wtforms.DateTimeLocalField. Set the format with date and time separated by a 'T'. If you would want the current time as the default value, set default parameter.
from wtforms.fields.html5 import DateTimeLocalField
class InterviewForm(Form):
posted = DateTimeLocalField('Posted:', default=datetime.today, format='%Y-%m-%dT%H:%M')
I did extensive research on the same problem, this is a hack but I still got the timestamp from the tag which looked like:
<input id="time_left" name="time_left" required type="datetime-local" value="2018-11-15T04:44">
You basically search for the timestamp from the tag returned by the tag
date = re.search('(\d{4})[/.-](\d{2})[/.-](\d{2})[T](\d{2})[:](\d{2})',
str(form.time_left)).group())
Let me know if the solution worked for you or if found a better solution to the problem.

How to use Django JSON and GeoJSON Serializer?

I am relatively new to Django. I have read the documentation but I'm still having trouble getting it to work.
views.py
def getMarkers(request):
query = request.GET
zoom = query.__getitem__('zoom')
fromlat = query.__getitem__('fromlat')
tolat = query.__getitem__('tolat')
fromlng = query.__getitem__('fromlng')
tolng = query.__getitem__('tolng')
querystring = coordinate.objects.filter(lat__gt=fromlat) .filter(lat__lt = tolat).filter(lon__gt = fromlng).filter(lon__lt = tolng)
data = serialize('geojson', querystring,
geometry_field='point',
fields=('name',))
print(data)
models.py
class coordinate(models.Model):
name = models.CharField(max_length=30)
lat = models.DecimalField(max_digits=10, decimal_places=7)
lon = models.DecimalField(max_digits=10, decimal_places=7)
latlng = [lat, lon]
zoom = models.IntegerField(default=15)
def __str__(self):
return self.name
how do I use the searlizer? It's not throwing an error but I know it's not working because nothing is getting printed to the server terminal except the request
print(data) won't work. You have to do something like:
return HttpResponse(data)
Then visit the URL of that view and you'll see the result.
Update
MultiValueDictKeyError occurs if the key that you're trying to access is not in request.GET or request.POST.
To prevent this error, make sure your GET request has zoom key. For that you will need to write the URL in addressbar something like this:
/getmarkers/?zoom=val&formlat=val&somekey=val
Replace val with the value for that key.

change a form value before validation in Django form

I have a django form and on my view function I do this :
search_packages_form = SearchPackagesForm( data = request.POST )
I would like to overwrite a form field called price which is decleared as such :
price = forms.ChoiceField( choices = PRICE_CHOICES, required = False,widget = forms.RadioSelect )
I would like to overwrite the form field before calling search_packages_form.is_valid()
I thought of doing :
search_packages_form.data['price'] = NEW_PRICE
But it does not work. Any ideas ?
Probably not the Django way but based on https://stackoverflow.com/a/17304350/2730032 I'm guessing the easiest way to change your form value before validation is to do something like the following:
def search_packages_view(request):
if request.method == 'POST'
updated_request = request.POST.copy()
updated_request.update({'price': NEW_PRICE})
search_packages_form = SearchPackagesForm(updated_request)
if search_packages_form.is_valid():
# You're all good
This works but I'd be interested if anyone has another way that seems more in line with Django, or if there isn't: then an explanation about why.
one trick for what you want is to do it like this:
changed_data = dict(request.POST)
changed_data['price'] = NEW_PRICE
search_packages_form = SearchPackagesForm(data = changed_data)
My solution is build on an earlier proposal. It is a working solution, which can be used in several cases.
#Milad Khodabandehloo
had a tricky solution to solve the problem.
changed_data = dict(request.POST)
changed_data['price'] = NEW_PRICE
search_packages_form = SearchPackagesForm(data = changed_data)
as #The EasyLearn Academy commented: it does not allow you to access actual data submitted in form.
This is because the request.POST is immutable.
But there is a solution to the problem - just have to be more tricky.
This solution is only good if a reference to the object is enough for the certain cause. It leaves the object itself the same.
# write object to variable (data)
data = request.POST
# set to mutable
data._mutable = True
# modify the values in data
data[modified_field] = new_value
# set mutable flag back (optional)
data._mutable = False
Hope it's useful!
form.is_valid() runs through your form's (and model's in case of a ModelForm) clean method's, returning True or False
If you plan on changing form data you can do it within the general clean method or at field level, e.g.
class YourForm(DerivingClass):
# regular stuff
def clean_<ATTR>(self):
# here
return self.cleaned_data
def clean(self):
# or here
return super(YourForm, self).clean()

Django: strange IntegrityError upon saving a ModelFormset form

I am trying to save a couple ModelFormset forms, but am running into an IntegrityError. Here is the code:
billing_formset = BillingFormSet(request.POST,prefix='billing')
cc_formset = CCFormSet(request.POST,prefix='cc')
if billing_formset.is_valid() and cc_formset.is_valid():
bp = UserBillingProfile()
cc = UserCreditCard()
for form in billing_formset.forms:
billing_profile = form.save(commit=False)
billing_profile.user = request.user
bp = billing_profile.save()
for form in cc_formset.forms:
cc = form.save(commit=False)
cc.billing_profile = bp
cc = form.save()
This code caused the following code:
IntegrityError at [url removed]
(1048, "Column 'user_billing_profile_id' cannot be null")
EDIT: Here is some iterative code that also fixes my typo. I'm running into basically the same problem.
billing_profile_form = billing_formset.forms[0]
cc_form = cc_formset.forms[0]
unsaved_billing_profile = billing_profile_form.save(commit=False)
user_billing_profile = unsaved_billing_profile.save()
unsaved_cc = cc_form.save(commit=False)
unsaved_cc.user_billing_profile = user_billing_profile
cc = unsaved_cc.save()
Problem line gives: "Cannot assign None: "UserCreditCard.user_billing_profile" does not allow null values." It seems unsaved_billing_profile.save() is returning null? Why?
This is kind of crazy; everything seems to be right. I don't get any errors when saving the billing profile. Any ideas on what I should check? Things seem to be going wrong in the second loop, where bp apparently has a value of None.
Thanks in advance.
This means you are trying to save a model instance with user_billing_profile set to None, looks like you are calling "billing_profile" instead of "user_billing_profile".
The "save" method returns None every time commit=False isn't specified. you should instead call something like this:
billing_profile.save()
bp = billing_profile.instance

Categories

Resources