Why am I getting `NOT NULL constraint failed` error with Django? - sql

I am new to Django. I am to create some sort of todo app. I am having trouble setting IntegerField as optional field. As far as I can see the problem is when I try to save to save the object to the database. I get error: NOT NULL constraint failed: lista_row.quantity. I have made (and migrated) migrations. Here is my models.py:
from django.db import models
from django.contrib import admin
class Row(models.Model):
name = models.CharField(max_length=200)
quantity = models.IntegerField(null=False, blank=True)

If you want to make it optional, use this instead:
quantity = models.IntegerField(blank=True, null=True)

Related

How to create a SQLAlchemy model on BigQuery?

After reading the following link https://github.com/googleapis/python-bigquery-sqlalchemy I managed to query a table stored on Google BigQuery by using SLQAlchemy. Now I would like to create a SQLAlchemy Users model on Google BigQuery so that I can use Flask-login features (e.g. UserMixin) in order to validate whether a user is authenticated, active, etc. but in this case my database is stored on BigQuery instead of a traditional SQL database (mainly due to billing costs as I find Google Cloud SQL way more expensive than Google BigQuery).
This is my code:
from sqlalchemy.engine import create_engine
from flask_sqlalchemy import SQLAlchemy
engine = create_engine('bigquery://my_project',credentials_path='my_credentials.json')
db = SQLAlchemy()
class Users(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(15), unique=True, nullable = False)
email = db.Column(db.String(50), unique=True)
Users.metadata.create_all(engine)
Unfortunately I'm getting the following error:
DatabaseError: (google.cloud.bigquery.dbapi.exceptions.DatabaseError) 400 Table "users" must be qualified with a dataset (e.g. dataset.table).
I tried to modify the engine variable as follows:
engine = create_engine('bigquery://my_project.my_dataset',credentials_path='my_credentials.json')
but then I get the following error (I'm intrigued by the None part):
ValueError: table_id must be a fully-qualified ID in standard SQL format, e.g., "project.dataset.table_id", got my_project.my_dataset.None.users
Does anyone know how can I create a SQLAlchemy model on Google BigQuery?
Can you try this:
from sqlalchemy.engine import create_engine
from flask_sqlalchemy import SQLAlchemy
from pybigquery.api import ApiClient
from flask import Flask
db = SQLAlchemy()
#ToDo:Change project name and dataset name.
engine = create_engine('bigquery://my-project/my-dataset')
db = SQLAlchemy()
class Users(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(15), unique=True, nullable = False)
email = db.Column(db.String(50), unique=True)
Users.metadata.create_all(engine)
I solved the error by adding the dataset name.
engine = create_engine('bigquery://my-project/my-dataset')

FOREIGN KEY constraint failed Django Models

I'm creating a small-ish django application using AllAuth for the authetncation, which I have customised myself to include some additional fields.
Part of the sites functionality requires me to refrence the logged in user through a Foreign Key multiple times and I'm approaching this through the custom model I created, called UserProfile; (I tried Django's User model & this also gave me errors)
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
phone_number = models.CharField(max_length=30, null=False)
postcode = models.CharField(max_length=500, null=True, blank=True)
town_or_city = models.CharField(max_length=40, null=True, blank=True)
street_address1 = models.CharField(max_length=80, null=True, blank=True)
street_address2 = models.CharField(max_length=80, null=True, blank=True)
county = models.CharField(max_length=80, null=True)
I'm referencing the above model in the activity table:
class Activity(models.Model):
class Meta:
verbose_name_plural = 'Activities'
activity_id = models.CharField(max_length=32, null=False, editable=False)
host = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
name = models.CharField(max_length=254, null=False, blank=False)
date = models.DateField()
start_time =models.TimeField()
end_time = models.TimeField()
duration = models.DurationField(blank=True, null=True)
location = models.CharField(max_length=40, null=False, blank=False)
description = models.CharField(max_length=140, null=False, blank=False)
available = models.BooleanField(default=True)
Everything works smoothly, as I can use this to create one activity per user, however I want to make this a Many to One field, which required me to update from settings.AUTH_USER_MODEL to the Foreign Key.
Unfortunately, I'm getting the following error:
FOREIGN KEY constraint failed
when I try to add a new activity now, and I'm at a loss as to why this is happening.
If someone could point me in the right direction on how to create this many to one functionality, it would be great.
I can't see your whole code so the answear may be wrong but it Looks like you dont have Primary Key in UserProfile
ForeignKey As Default takes Primary Key as argument
Potential solve:
class Activity(models.Model):
host = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile', primary_key=True)
If it dosent solve your problem please put full error message
DOCS
I would guess, from what information that you've provided, is that what has happened is that you've potentially got a user who doesn't have a user profile, so when you try to create the activity it fails with the error you specified. On the other hand, it could also be related to how you're rendering and validating your forms. Furthermore it could also be due to the way you are using class based views views or function based views.
In any case, please provide all information possible. Generally all information is required, not just the part you're unsure of.
How do you create an activity?
How do you validate your forms?
How is the user profile ID populated?
Providing more information, I will happily respond as it seems like a straight forward question

Add permission to group (or find where is the problem)

I have this message:
The requested operation can not be completed due to security
restrictions. Document type: Employee (hr.employee) Operation: read
User: 23 Fields: - contract_id (allowed for groups 'Employees /
Officer')
I would not like to add the user to the mentioned group because I want to restrict his actions, and this group has too many permissions. How can I know what permission is required for that specific field?
UPDATE
Create a module with just these lines. I am trying to overwrite the field by deleting the group but it doesn't work for me. What am I doing something wrong?
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
from odoo.osv import expression
class Employee(models.Model):
_inherit = "hr.employee"
contract_id = fields.Many2one('hr.contract', string='Current Contract',
domain="[('company_id', '=', company_id)]", help='Current contract of the employee')
Odoo is nice for once and is telling you which field on which model is restricted. So in this case you should look into the field definition and will find:
contract_id = fields.Many2one(
'hr.contract', string='Current Contract',
groups="hr.group_hr_user",
domain="[('company_id', '=', company_id), ('employee_id', '=', id)]",
help='Current contract of the employee')
You can see the groups parameter which will lead to a restriction of this field to the following groups. Here it is one: hr.group_hr_user which is created with the hr App and also mentioned in Odoo's Access Error: "Employees / Officer".
So you could change the field definition, but i don't advise to do that. I'm not sure why there is no possibility for an Employee to atleast see some of the current contract information of his own contract.

Cannot create table in odoo 14

I just created a new module with the following structure:
mainfolder
-models
--__init__.py
`from . import student`
--student.py
```
from odoo import api, fields, models
class SchoolStudent(models.Model):
_name = "school.student"
_description = "School Student Patient"
name = fields.Char(string='Name', required=True)
age = fields.Char(string='Age')
gender = fields.Selection([
('male', 'Male'),
('female', 'Female'),
('other', 'Other'),
], required=True, default='male')
note = fields.Text(string='Description')
```
-__init__.py
`from . import models`
-__manifest__.py
The problem is, when I installed the module, I cannot find the table "School student" in my database, I updated the module several times but the same.
How to fix this issue please?
Thanks
I inform you that I solved the problem just by creating the view and access rights for the module.
Thanks
Odoo15 - For someone who still got this issue:
In my case, i'm missing code in my root __init__.py
My custom module named school and saved inside /var/www/html/odoo_15/addons/school
So the root init file should have path like /var/www/html/odoo_15/addons/school/__init__.py and the content should be
from . import models

How can I create an alias name of a relational field in Odoo?

I need to create a model, to have backward compatibility with older field names.
This way,
I can develop modules that could read the "new" fields, but migrating the old ones is not necessary for this to work.
This works only for reading or presenting the fields, but not for writing them.
So I thought it would be good to create an alias for each field, and made this:
from openerp import models, fields, api
class backward_compatibility(models.Model):
_description = 'Backward compatibility'
_inherit = 'account.invoice'
new_document_class_id = fields.Integer(
compute='_comp_new_doc_class', string='Tipo')
new_document_number = fields.Char(
compute='_comp_new_doc_number', string='Folio')
#api.multi
def _comp_new_doc_class(self):
for record in self:
try:
record.new_document_class_id = record.old_document_class_id
except:
pass
#api.multi
def _comp_new_doc_number(self):
for record in self:
try:
record.new_document_number = record.old_document_number
except:
pass
This approach works for the Char field, but it doesn't for the Integer (Many2one).
What ideas do you have to make this work? Should I replicate the relationship in the new field?
oldname: the previous name of this field, so that ORM can rename it automatically at migration
Try to use "oldname". I saw this in the core modules. Never used personally.
_inherit = 'res.partner'
_columns = {
'barcode' : fields.char('Barcode', help="BarCode", oldname='ean13'),
}
Also dummy fields are user to help with backward compatibility.
'pricelist_id': fields.dummy(string='Pricelist', relation='product.pricelist', type='many2one'),