I have a django model with foreigns. I want to limit the choices for it with depend on content of another field of this model.
This code works:
class PhysicalProperty(models.Model):
property_quantity = models.ForeignKey(Quantity)
default_unit = models.ForeignKey(MeasurementUnits, limit_choices_to = {'quantity': 1 )
But it takes from MeasurementUnits all records with MeasurementUnits.quantity = 1. And I need to set query as MeasurementUnits.quantity = PhysicalProperty.property_quantity.
This code doesn't work
class PhysicalProperty(models.Model):
property_quantity = models.ForeignKey(Quantity)
default_unit = models.ForeignKey(MeasurementUnits, limit_choices_to = {'quantity': property_quantity )
You cant use self in class. self is for instances of classes.
you could use the init method for that
class PhysicalProperty(models.Model):
property_quantity = models.ForeignKey(Quantity)
default_unit = models.ForeignKey(MeasurementUnits)
def __init__(self, *args, **kwargs)
super(self, PhysicalProperty).__init__(*args, **kwargs)
self.default_unit = self.property_quantity
that way, everytime you do physical_property = PhysicalProperty(), physical_property.default_unit will be the same as property_quantity of the same object.
Related
I have a class in Python:
class CursorSetPagination(CursorPagination):
page_size = 1
page_size_query_param = 'per_page'
ordering = '-posted_on'
I want to call this class with change statement page_size = 5 in it. I tried with this code:
paginator = CursorSetPagination(page_size = 5)
It doesn't work. How can I do this?
Use __init__ for it. Refer this answer for better understanding.
class CursorSetPagination(CursorPagination):
def __init__(self, page_size=1, page_size_query_param='per_page', ordering):
self.page_size = page_size
self.page_size_query_param = 'page_size_query_param '
self.ordering = ordering
You can reset the parameters used in __init__ this as below:
paginator = CursorSetPagination(page_size = 5)
I have this class in a module1:
class A(models.Model):
_name="a"
b_id = field.Many2one("b")
tax_old = fields.Float()
tax_value = fields.Float(string="Tax", related = 'b_id.tax_value', store=True)
all_taxes = fields.Float(_compute='compute_all')
#api.depends('tax_value')
def compute_all(self):
self.all_taxes = self.tax_value + self.tax_old
self.update()
In module2 I have this class:
class B(models.Model):
_name="b"
a_ids = fields.One2many("a","b_id")
tax_value = fields.Float(string="Tax")
Now in A view when I change b_id value, tax_value works fine and compute_all works fine, but when I save this record, all_taxes doesn't take tax_value field, only tax_old. And when I open the record form view again and manually write a value in tax_value, it works totally fine.
It should be enough to use b_id on your compute method, because it's related:
#api.multi
#api.depends('b_id')
def compute_all(self):
for record in self:
record.all_taxes = record.b_id.tax_value + record.tax_old
The compute method can be called with a multi record recordset. So use a for loop inside it. And you don't have to do an update() at the end.
You can try it
#api.one
#api.depends('b_id', 'b_id.tax_value')
def compute_all(self):
self.all_taxes = self.tax_value + self.tax_old
Two things:
It ist compute not _compute and you don't need to use self.update().
Try this instead:
# You'll need this
from django.db.models import F
#api.depends('tax_value')
def compute_all(self):
self.update(all_taxes=F('tax_value') + F('tax_old'))
You're missing the self. What you've done is defined a local variable called all_taxes, not the instance variable.. which is what you're after
I am attempting to push data from a DJANGO view into the Tables object, passing it through as an argument. In this case, I would like to pass a variable called doc_id into a Tables2 object called tableName
In this example, I have set doc_id as 1, and pass it into the
View
def editorView(request):
doc_id = 1
table = tableName(UserProfile.objects.filter(), doc_id=doc_id)
Table
class tableName(tables.Table):
tbl_doc_id = None ## Creating a temporary variable
def __init__(self, *args, **kwargs):
temp = kwargs.pop("doc_id") ## Grab doc_ID from kwargs
super(tableName, self).__init__(*args, **kwargs)
self.tbl_doc_id = temp ## Assign to self.tbl_doc_id for use later
### Do something with tbl_doc_id
modelFilter = model.objects.filter(pk = tbl_doc_id)
When running the debugger, I can see that tbl_doc_id is still assigned as None, rather than 1.
What is the correct way to pass arguments into a Tables2 instance? Is it possible?
EDIT: Adding more information for context.
In the real world scenario, I have a view. That view takes an argument from the URL called doc_id. That doc_id is used to grab an object from a model called 'MaterialCollection', and return it as 'mc'.
'mc' is then passed into the table
View
def editorView(request, doc_id):
try:
mc = MaterialCollection.objects.get(pk = doc_id)
except Material.DoesNotExist:
raise Http404("Document does not exist")
config = RequestConfig(request)
unnassigned_User_Table = unassignedUserTable(UserProfile.objects.filter(), mc=mc)
... Other code + Render ...
From my table, I create a custom LinkColumn. That linkColumn is used to construct a URL based upon a number of Attributes from the model 'UserProfile', and from mc.
Table
class unassignedUserTable(tables.Table):
mc = None
def __init__(self, *args, **kwargs):
temp_mc = kwargs.pop("mc")
super(unassignedUserTable, self).__init__(*args, **kwargs)
self.mc = temp_mc
current_Assignment = "NONE"
new_Assignment = "AS"
assign_Reviewer = tables.LinkColumn('change_Review_AssignmentURL' , args=[ A('user'), current_Assignment, new_Assignment, mc, A('id')], empty_values=(), attrs={'class': 'btn btn-success'})
class Meta:
model = UserProfile
... Setup excludes/sequence/attributes...
In this particular instance. mc has a FK to UserProfile (in a 1:M) relationship.
I see that the name of your table class is tableName so if you want __init__ to work as expected please change the line:
super(unassignedUsers, self).__init__(*args, **kwargs)
to
super(tableName, self).__init__(*args, **kwargs)
Beyond this obvious problem, there are some more issues with your code:
Your classes must start with a capital letter (TableName instead of tableName)
Your table classes should end end with -Table (for example NameTable)
I am using django-tables2 for many years and never needed to pass something in __init__ as you are doing here. Are you sure that you really need to do this?
If you want to filter the table's data the filtering must be done to your view - the table will get the filtered data to display.
I created a form with a TypedChoiceField:
class EditProjectForm(ModelForm):
def __init__(self, action, *args, **kwargs):
super(EditProjectForm, self).__init__(*args, **kwargs)
now = datetime.datetime.now()
if action == 'edit':
project_year = kwargs['project_year']
self.fields['year'].choices = [(project_year, project_year)]
else:
self.fields['year'].choices = [(now.year, now.year), (now.year + 1, now.year + 1)]
year = forms.TypedChoiceField(coerce=int)
...
This works perfectly fine when using it inside a view. Now I want to write tests for this form:
form_params = {
'project_year': datetime.datetime.now().year,
}
form = EditProjectForm('new', form_params)
self.assertTrue(form.is_valid())
The test fails, because is_valid() returns False. This is because when calling super.__init__() in the EditProjectForm, the field year doesn't have its choices yet. So the validation for this field fails and an error is added to the error list inside the form.
Moving the super call after self.fields['year'].choices doesn't work either, because self.fields is only available after the super.__init__() call.
How can I add the choices dynamically and still be able to test this?
Okay, I found the problem.
The field year is a class variable, and is instantiated even before the tests setUp method and the forms __init__ method was called. Since I haven't passed the required choices parameter for this field, the error was issued way before the form object was created.
I changed the behaviour so I change the type of the fields in the __init__ method rather than using a class variable for that.
class EditProjectForm(ModelForm):
def __init__(self, action, *args, **kwargs):
super(EditProjectForm, self).__init__(*args, **kwargs)
now = datetime.datetime.now()
if action == 'edit':
project_year = kwargs['project_year']
choices = [(project_year, project_year)]
else:
choices = [(now.year, now.year), (now.year + 1, now.year + 1)]
self.fields['year'] = forms.TypedChoiceField(coerce=int, choices=choices)
I have a need to track changes on Django model instances. I'm aware of solutions like django-reversion but they are overkill for my cause.
I had the idea to create a parameterized class decorator to fit this purpose. The arguments are the field names and a callback function. Here is the code I have at this time:
def audit_fields(fields, callback_fx):
def __init__(self, *args, **kwargs):
self.__old_init(*args, **kwargs)
self.__old_state = self.__get_state_helper()
def save(self, *args, **kwargs):
new_state = self.__get_state_helper()
for k,v in new_state.items():
if (self.__old_state[k] != v):
callback_fx(self, k, self.__old_state[k], v)
val = self.__old_save(*args, **kwargs)
self.__old_state = self.__get_state_helper()
return val
def __get_state_helper(self):
# make a list of field/values.
state_dict = dict()
for k,v in [(field.name, field.value_to_string(self)) for field in self._meta.fields if field.name in fields]:
state_dict[k] = v
return state_dict
def fx(clazz):
# Stash originals
clazz.__old_init = clazz.__init__
clazz.__old_save = clazz.save
# Override (and add helper)
clazz.__init__ = __init__
clazz.__get_state_helper = __get_state_helper
clazz.save = save
return clazz
return fx
And use it as follows (only relevant part):
#audit_fields(["status"], fx)
class Order(models.Model):
BASKET = "BASKET"
OPEN = "OPEN"
PAID = "PAID"
SHIPPED = "SHIPPED"
CANCELED = "CANCELED"
ORDER_STATES = ( (BASKET, 'BASKET'),
(OPEN, 'OPEN'),
(PAID, 'PAID'),
(SHIPPED, 'SHIPPED'),
(CANCELED, 'CANCELED') )
status = models.CharField(max_length=16, choices=ORDER_STATES, default=BASKET)
And test on the Django shell with:
from store.models import Order
o=Order()
o.status=Order.OPEN
o.save()
The error I receive then is:
TypeError: int() argument must be a string or a number, not 'Order'
The full stacktrace is here: https://gist.github.com/4020212
Thanks in advance and let me know if you would need more info!
EDIT: Question answered by randomhuman, code edited and usable as shown!
You do not need to explicitly pass a reference to self on this line:
val = self.__old_save(self, *args, **kwargs)
It is a method being called on an object reference. Passing it explicitly in this way is causing it to be seen as one of the other parameters of the save method, one which is expected to be a string or a number.