Pushing Arguments into Tables2 using kwargs in Django Python - python

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.

Related

Dynamically populated Django field does not display choices

I want to dynamically populate a Django ChoiceField from a stored procedure. However, I cannot get the results to display in the Django admin. It comes up blank. What am I missing? Sorry if I've asked a question that's already been answered. I've already looked and looked...
class Plot(models.Model):
plot_claim_type = models.CharField('Plot Claim Type', max_length=7)
class PlotAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(PlotAdminForm, self).__init__(*args, **kwargs)
c = connection.cursor()
try:
c.execute("BEGIN")
c.callproc("udf_getcodetypes", "1")
results = c.fetchall()
for o in results:
self.base_fields['plot_claim_type'].choices = forms.MultipleChoiceField(choices=(o[0], str(o[1])))
finally:
c.close()
#admin.register(Plot)
class PlotAdmin(admin.ModelAdmin):
form = PlotAdminForm
Your loop through the results is assigning and reassigning so you end up with just one assignment (the last o in results). And you can't assign a Field type to choices, that doesn't make sense.
Just try this (instead of for o in results loop):
results = c.fetchall()
self.fields['plot_claim_type'] = forms.MultipleChoiceField(choices=(
(o[0], str(o[1])) for o in results))

What is the return type of clean_formField of manytomany field in django? Can I return list from the function

I changed manytomany field to token field with the help of bootstrap tag input javascript plugin. Then I am getting comma (,) separates primary keys as input. After splitting from delimiter comma (,) I got the instance of the exact object. Now how to add those objects to the manytomany field. I tried returning list but it didn't work.
Here is my form class
class EventRegistrationForm(forms.ModelForm):
participants = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off', 'data-role':'tagsinput'}),required=True)
class Meta:
model=EventRegistration
fields=['event', 'participants', 'teamName', 'feePaid']
def clean_feePaid(self):
feepaid=self.cleaned_data.get('feePaid')
if not feepaid:
raise ValidationError('Please pay the fee First :)')
return feepaid
def clean_participants(self):
participants_data = self.cleaned_data.get('participants')
event = self.cleaned_data.get('event')
participants =[]
for pd in participants_data.split(','):
p = Candidate.objects.get(pk=pd)
participants.append(p)
if not (event.minParticipant <= len(participants) <= event.maxParticipant):
raise ValidationError('Number of Participants exceeded :D')
return participants
def __init__(self, *args, **kwargs):
super(EventRegistrationForm, self).__init__(*args, **kwargs)
self.fields['event'].empty_label = ''
# following line needed to refresh widget copy of choice list
self.fields['event'].widget.choices =self.fields['event'].choices
one can pass list for m2m field.
I just missed form.save_m2m().

Test form with dynamic choice fields

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)

how to use self field in models.ForeignKey.limit_choices_to?

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.

Django model class decorator

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.

Categories