Module name = simple_checkout.
Admin controller path - admin/controller/extension/module.
Controller classname - ControllerExtensionModuleSimpleCheckout.
Admin model path - admin/model/extension/module.
Model classname - ModelExtensionModuleSimpleCheckout.
$this->load->model('setting/setting'); // returns null.
$this->load->model('extension/module/simple_checkout'); // returns null
Why ALL load->model in admin controller file return null?
Related
I have a calculated field in which I want to add a value from a previously created custom field by user (position, manager)
example here https://i.stack.imgur.com/Bg9uX.png
I managed to pass to the field by username using
User.current.id
How can I pass these 2 fields into a computed
tried to pass the value cfs[22]
unfortunately it didn't work out
To access a custom field value which id = 10, try this:
# Getting the current User object
u = User.current
# Accessing the value for custom field which id = 10
u.custom_field_value(10)
To assign a value to a custom field which id = 10 , this code should work:
# Getting the current User object
u = User.current
# Assigning the value 'value' to the custom field which id = 10
u.custom_field_values=({'10'=>'value'})
# Persisting the change
u.save
You can combine the methods to, for instance, assign a custom field value which id = 11 with the custom field value which id = 10:
u.custom_field_values=({'11'=>u.custom_field_value(10)})
# Remember to persist the change
u.save
The rails c can come in handy for you to explore the Object methods.
I have a form which is having a 'price', 'tax' and 'discount' fields (IntegerFields).
And then one more read-only field will be there called 'total_price'.
while we enter the 'price', 'discount' and 'tax', automatically 'total_price' value should display. If we change the 'discount' or 'price' then 'total_price' also change immediately.
After seeing the final price, we can click the 'Save' button.
How to attain this in Django admin?
To do this, you will have to add custom Javascript code to your admin page.
Here's what you can do:
Add read-only field to admin - it will display "total_price"
Add custom script to admin page.
Write JS script - this script will do "live update" of total price
Your admin may look like this:
#admin.register(YourModel)
class YourModelAdmin(admin.ModelAdmin):
# some code here...
readonly_fields = ('total_price', )
def total_price(self, obj):
# return whatever initial value you want
return obj.price - obj.price*obj.discount
# This is important - adding custom script to admin page
#property
def media(self):
media = super().media
media._js.append('js/your-custom-script.js')
return media
Remember that js/your-custom-script.js must be in your static files folder.
UPDATE:
Instead of overwriting media property, you can include your JS using Meta nested class:
class YourModelAdmin(admin.ModelAdmin):
...
class Media:
js = (
'path-to-your-static-script-file.js',
)
The last step is to write a script to update value of total_price field whenever some other field is changed.
Example: if you want to change total_price whenever price is changed, your script can look like this:
if (!$) {
$ = django.jQuery;
}
$(document).ready(function(){
// Add event listener to "price" input
$("#id_price").change(function(e){
// Get entered value
let price = parseFloat($(this).val());
// Get discount value from another field
let discount = parseFloat($("#id_discount").val())
// Compute total price in whatever way you want
let total_price = price - price*discount;
// Set value in read-only "total_price" field.
$("div.field-total_price").find("div.readonly").text(total_price);
});
})
If you want to update total_price when discount or tax fields are changed, simply add event listeners to them.
I have two django models
class ValidName:
name = models.TextField()
class MetaSyntacticName(ValidNames):
name = models.ForeignKey(ValidName)
usages = models.IntegerField()
If I have an instance of MetaSyntacticName, can I find out if the ValidName instance it's name references has been loaded from the database without a database query?
One way to do this I could find is using a private model instance attribute _state. It has an attribute fields_cache which is a mapping: field name -> field cache.
So in your case you can check if a foreign key name has been loaded using this line:
'name' in instance._state.fields_cache
where instance is an instance of MetaSyntacticName.
The following code demonstrates that it's working:
foo = ValidName.objects.create(name='foo')
foo_meta = MetaSyntacticName.objects.create(name=foo, usages=1)
'name' in foo_meta._state.fields_cache # True
foo_meta = MetaSyntacticName.objects.get(name_id=foo.id)
'name' in foo_meta._state.fields_cache # False
# next line hits the db and loads the field 'name'
foo_meta.name
'name' in foo_meta._state.fields_cache # True
It took some time for me to hack this out so I hope this saves someone's time :)
P.S. I checked that the similar code works on Django 2.2, as _state is a private attribute it might be different between Django versions
If you call select_related, then there won't be any extra database query for prepopulating ForeignKey related objects. For example:(copy pasted from documentation):
# Hits the database.
e = Entry.objects.get(id=5)
# Hits the database again to get the related Blog object.
b = e.blog
And here’s select_related lookup:
# Hits the database.
e = Entry.objects.select_related('blog').get(id=5)
# Doesn't hit the database, because e.blog has been prepopulated
# in the previous query.
b = e.blog
You can add method like this:
class MetaSyntacticName(ValidNames):
...
def valid_name_is_cached(self):
return __class__.validname_ptr.is_cached(self)
__class__ is just MetaSyntacticName
validname_ptr - is Django descriptor which have method is_cached
I have a user in my django table - auth_user. The username = 'django' but when I check the id its None.
When I check in the tables, the id is set to 1.
Not sure why u.id is None.
The following code creates a user object but does not save it to the database:
# here u.id is None
u = User(username="django")
An id is associated to a new user object whenever it is added to the database:
# here u.id is not None
u = User.objects.create(username="django")
If the user object already exists, then it can be loaded from the database and the id attribute will be properly defined:
u = User.objects.get(username="django")
I have a model that is backed by a database view.
class OrgCode(models.Model):
org_code = models.CharField(db_column=u'code',max_length=15)
org_description = models.CharField(max_length=250)
org_level_num = models.IntegerField()
class Meta:
db_table = u'view_FSS_ORG_PROFILE'
I need to reference this in another model
class AssessmentLocation(models.Model):
name = models.CharField(max_length=150)
org = models.ForeignKey(OrgCode)
I can't run syncdb because foreign key constraints cannot be created referencing a view.
u"Foreign key 'FK__main_asse__org__1D114BD1'
references object 'view_FSS_ORG_PROFILE'
which is not a user table.", None, 0, -214
7217900), None)
Command:
CREATE TABLE [main_assessmentlocation] (
[id] int IDENTITY (1, 1) NOT NULL PRIMARY KEY,
[name] nvarchar(150) NOT NULL,
[org] int NOT NULL REFERENCES [view_FSS_ORG_PROFILE] ([id]),
)
The workaround is to take out the Meta:db_table pointing to the view and let sync db create the the OrgCode table, then put the Meta:db_table back in after syncdb.
Is there a way to prevent the creation of foreign key constraints for certain models or fields?
Update: I added a static method to the related model indicating it's a view
class OrgCode(models.Model):
org_code = models.CharField(max_length=15)
org_description = models.CharField(max_length=250)
#staticmethod
def is_backend_view():
return True
Then overrode DatabaseCreation.sql_for_inline_foreign_key_references in django_mssql creation.py:
def sql_for_inline_foreign_key_references(self, field, known_models, style):
try:
field.rel.to.is_backend_view()
return "", False
except:
return super(DatabaseCreation,self).sql_for_inline_foreign_key_references(field, known_models, style)
The generated sql from syncdb leaves out the constraint:
CREATE TABLE [main_assessmentlocation] (
[id] int IDENTITY (1, 1) NOT NULL PRIMARY KEY,
[name] nvarchar(150) NOT NULL,
[org] int, -- NO FK CONSTRAINT ANYMORE --
);
It does involve hacking django_mssql so I'm going to keep on trying, maybe hooking into the django.db.backends.signals.connection_created signal will work...
django development version has a db_constraint field for ForeignKey model field - docs.
If you set managed=False (Django docs) in your model's Meta class, Django will not create the table when you run syncdb.
class AssessmentLocation(models.Model):
name = models.CharField(max_length=150)
org = models.ForeignKey(OrgCode)
class Meta:
managed = False
Django has a hook to provide initial sql data. We can (ab?)use this to get Django to create the table immediately after running syncdb.
Create a file myapp/sql/assessmentlocation.sql, containing the create table statement:
CREATE TABLE [main_assessmentlocation] (
[id] int IDENTITY (1, 1) NOT NULL PRIMARY KEY,
[name] nvarchar(150) NOT NULL,
[org] int, -- NO FK CONSTRAINT ANYMORE --
);
If you have other models with foreign keys to the AssessmentLocation model, you may have problems if Django tries to apply the foreign key constraint before executing the custom sql to create the table. Otherwise, I think this approach will work.