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)
Related
I am trying to create a FlaskForm that changes depending on the customer passed to it and having issues when the HTML is getting rendered. I haven't done much work with classes unfortunately so I'm not sure what the issue is. I get an error in Python that says:
AttributeError: 'GlobalsForm' object has no attribute '_fields'
I modified the __init__ so that you can set who the customer is plus a created a class function that checks to see who the customer is and customizes the form fields depending on who the customer is. I have a feeling it doesn't like me modifying the class I am inheriting and am probably missing something to make it work. Need to do something with "super"?
Here is what I have so far:
routes.py
#app.route('/global_vars', methods=['GET', 'POST'])
def global_vars():
data = session.get('dev_data', None)
form = GlobalsForm(customer=data['customer'])
form.set_fields()
return render_template('global_vars.html', title='Config Provisioning - Globals', form=form)
forms.py
class GlobalsForm(FlaskForm):
def __init__(self, customer):
self.customer = customer
def set_fields(self):
if self.customer == 'Cust1':
site_choices = [('Site1', 'Site1'), ('Site2', 'Site2'), ('Site3', 'Site3')]
site = SelectField('Site: ', choices = site_choices)
floor_room = StringField("Floor/Room (Ex. FL1RM56 or 1J46): ", validators=[InputRequired()])
rack = StringField("Rack (Data Centers only): ")
l2_domain_choices = [('USR', 'USR - User'), ('DC', 'DC - Data Center'), ('OOBM', 'OOBM - Out of Band Management')]
l2_domain = SelectField('Layer 2 Domain: ', choices=l2_domain_choices)
function_choices = [('ACSW', 'ACSW - Access Switch)'), ('AGSW', 'AGSW - Aggregation Switch'), ('CRSW', 'CRSW - Core Switch')]
function = SelectField('Device function: ', choices=function_choices)
else:
hostname = Stringfield("Hostname: ", validators=[InputRequired()])
I figured it out.. Had to expand on the super() line...
class GlobalsForm(FlaskForm):
def __init__(self, customer=None, *args, **kwargs):
self.customer = customer
super(GlobalsForm, self).__init__(*args, **kwargs)
I wrote a dynamic form:
class VoteForm(forms.Form):
def __init__(self, *args, **kwargs):
question = kwargs.pop('instance', None)
super().__init__(*args, **kwargs)
if question:
if question.allow_multiple_votes:
choice_field = forms.ModelMultipleChoiceField(queryset=question.choice_set)
else:
choice_field = forms.ModelChoiceField(queryset=question.choice_set)
choice_field.widget = forms.RadioSelect
choice_field.label=False
choice_field.empty_label=None
choice_field.error_messages={'required': _('No choice selected.'),
'invalid': _('Invalid choice selected.')}
self.fields['choice'] = choice_field
Without the RadioSelect widget everything seems to work, but with it, the following error occurs:
TypeError: use_required_attribute() missing 1 required positional argument: 'initial'
When you set the widget after having created the field, it must be a widget instance, not the class itself. But you have to set choices yourself:
choice_field.widget = forms.RadioSelect(choices=...)
Preferably, you can give the widget class when you construct your field:
choice_field = forms.ModelChoiceField(queryset=question.choice_set, widget=forms.RadioSelect)
First things first, you have (assuming a typo) error in your widget declaration. You need an instance of the RadioSelect class as a widget:
choice_field.widget = forms.RadioSelect()
Then you can set the initial value manually.
You can choose one of two options to do that:
Option 1:
Set initial at form instantiation:
if question.allow_multiple_votes:
choice_field = forms.ModelMultipleChoiceField(
queryset=question.choice_set,
initial=0
)
else:
choice_field = forms.ModelChoiceField(
queryset=question.choice_set
initial=0
)
Option 2:
Set the initial attribute: choice_field.initial=0 (as #nik_m points out in the comments)
With initial=0 the first item of the queryset will be selected.
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 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.
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.