How to Save page as Draft - django-admin

I Had created a detailed form in Django having some mandatory fields .I want to save page as Draft option without exception if mandatory fields are not set that time. How can I do it?

First set required=False for the fields that don't have to be set if you save as a draft. Then, to your form, add a field like 'save_as_draft' which is a boolean. Now you need a method to validate these fields depending on the state of save_as_draft field (whether user checked this field or not). You can use such a method:
def is_provided(self, field):
value = self.cleaned_data.get(field, None)
if value == None or value == '':
self._errors[field] = ErrorList([u'This field is required.'])
if field in self.cleaned_data:
del self.cleaned_data[field]
Add this method to your form and use it in form's clean method to validate your fields. This would look like this:
def clean(self):
draft = self.cleaned_data.get('save_as_draft', False)
if not draft:
# User doesn't save a draft so we need to check if required fields are provided
req_fields = ['field1', 'field2', 'field3']
for f in req_field:
self.is_provided(f)
return self.cleaned_data
If user prefer save_as_draft button instead of checkbox, then you would need to modify your view and pass some parameter to your form's constructor depending on whether user clicked save_as_draft button or just save button. In Form constructor save this state aa self.save_as_draft and use this in Form.clean method to check if you are saving draft or not.
Greetings,
Lukasz

Related

Salesforce URL Hacking

I have an object with many record types, and I need to populate some fields on it whenever it is created.
For example, I have an object called "CustomObj" with a field called "CustomF" with these 2 Record Types "RecType1" and "RecType2".
On the creation of a new "CustomObj" I need to populate the field the "CustomF" by "Hello" when the record type is "RecType1"
and by "Bye" when the record type is "RecType2"
Can I do that using the URL Hacking or I have to create 1 visualforce page to select the record type then redirect to the standard page with the values to populate this field or there is another approach?
What is the best practice?
How can I know the RecordType selected from the url itself ?
Thank you.
You can do this by an Workflow Rule. Go to Setup->Create->Workflow & Approvals. Than u can choose your object on which u want to set up the workflows. Most of the part should be straightforward since all the steps are well documented.
So one rule would be like:
If Record Type == RecType1 than fill in Field XY with value ABC
I see.
This is also possible. Go to the object and than your field you want to fill in the value. Click on edit and use the formula editor.
You can use a rule like
IF( $RecordType.DeveloperName = 'RecType1', 'Value for this', '')
for the default value
Salesforce does not provide an option to override "continue" button on record type selection page. but you can override "new" button. So you can do the following
Override "New" button to move to a record type selection page, which
will be a custom vf page (use radio buttons, description etc.).
The submit button (u can name as "Continue", just to imitate) should redirect to the standard page of data entry. But the
URL will be custom made.
You can refer to this Blog (Saurabh's Salesforce Blog) - http://writeforce.blogspot.in/2012/12/prepopulating-fields-using-url-hacking.html - for the idea of how the URL hacking can be done as per your need. Here you need to identify the field id and use them in the URL to provide a value to be prepopulated.

How to set initial value for read only field

I have a django application which is using django.contrib.admin for administrative tasks.
For one model I now need to add a field which indicates which part of the code each row was created from. I am using readonly_fields to prevent this value from being changed through the administration interface.
A default value in this field will tell me that the row was either
created before the field was introduced
created by code which has not been updated to set the field
created through the administration interface
But I need better granularity than that. In particular I want to be able to distinguish between a row created by code which doesn't know about the field, and a row created through the administration interface.
Is there some way my ModelAdmin class can specify an initial value for a field mentioned in readonly_fields?
One way to do this is,
def get_form(self, request, caja=None, **kwargs):
self.form = YourModelForm
form = super(YourModelAdmin, self).get_form(request, caja, **kwargs)
form.base_fields['field'].initial = your_initial_data
return form
I found this solution, which appears to work:
class Admin(ModelAdmin):
readonly_fields = ('created_by',)
def save_form(self, request, form, change):
r = super(Admin, self).save_form(request, form, change)
if not change:
assert r.created_by == CREATED_BY_UNKNOWN
r.created_by = CREATED_BY_ADMIN
return r
CREATED_BY_UNKNOWN and CREATED_BY_ADMIN are values defined elsewhere in my code.

Select from drop down menu or add another

I'm using simple_form. How can I have a select menu and a text input and have something like Select or add another.
The app will only take one value, either from the select menu or the text input.
It would also be good to validate to have either one or the other but not both, to avoid user confusion.
Implement what is called a 'combobox' to your simple_form
Jquery UI has a combobox:
http://jqueryui.com/autocomplete/#combobox
something fancier:
http://demos.kendoui.com/web/combobox/index.html
This will get you as far as your combo boxes displaying. I don't think there is a plugin for validating, so you'll have to write the code yourself.
You can try to use a combination of JavaScript and Ruby to solve this. If a user wants to enter a different value then what's available in the dropdown, you should have JS listen to a keydown event in that input and clear the dropdown, i.e.:
$(".input_field").bind('keydown', function() {
$(".select_field").val('0') // this should be a default blank value
});
That will clear the select when a user types. Likewise, you want to clear the input when the user selects from the dropdown, right?
$(".select_field").change(function() {
// Let's only clear the input field if the value is not the default null value
if ( $(this).val() != 0 ) {
$(".input_field").val('');
}
});
This will handle the front-end interactions. In the controller, you'll want to do some additional logic:
def create
object.new(...)
if params[:select] and params[:input]
# Overwrite the select with the input value
object.attribute = params[:input]
end
object.save
end
I assume that you want the input value to supersede the select, therefore if they are most submitted, we can just overwrite the select value with the input value and then continue to save the object.
Is this what you're looking for? Not sure if the inputted value was suppose to create a new object with a relationship or not. Hope this helps.

Is there a way I can simply use a data annotation attribute to add a JavaScript attribute to a form field?

I would like to add a data-other-for attribute to a text input, to link it to a select, so that it can be used to capture a value not present in the select when the user selects 'Other' in the select. The attribute's code will determine which value or description is in fact 'Other', and if so, enable the text input and maybe make it mandatory.
It seems like the only way to do this is by creating a new helper, because going via a ValidationAttribute I can only add preset validation HTML attributes to my text input. Or go large and write a whole new metadata provider.
You could try to implement a custom ModelBinder.
Say, in the select you would have:
new SelectListItem(Text = "Other", Value="bind:propertyName", Selected = False);
Then in the overriden BindModel, you simply look for bind: in the model properties and when found, copy your value from there.
After this, you should be able to add normal validation attributes to your select list.

Why can't you add a EditorExit Handler to a DynamicForm or FormItem?

This handler only exist for a ListGrid.
But if you look at the docs for DynamicForm.setValidateOnExit(), it says:
If true, form items will be validated when each item's "editorExit"
handler is fired as well as when the entire form is submitted or
validated. Note that this property can also be set at the item
level to enable finer granularity validation in response to user
interaction - if true at either level, validation will occur on
editorExit.
So how can we add a EditorExitHandler to a DynamicForm or a FormItem?
EDIT :
I want to create an error panel below the form to show all errors dynamically. Each FormITem has the possibility to validate on Exit but I do not know how to capture this validation event to check if the error panel should be updated or not.
There is one method form.getErrors() and form.showError(true). By this you can acheive that. But for that also you need to setValidator for each field.
TextItem name = new TextItem("name", "Name");
name.setRequired(true);
name.setRequiredMessage("Please specify name of the Table");
NTRegExpValidator nameValidator = new NTRegExpValidator("(^[a-zA-Z0-9][\\w\\s.()_-]+)$","It should start with alphabets and can have alphanumeric values ( )_-. and space.");
name.setValidators(nameValidator);
name.addKeyUpFieldHandler(new KeyUpHandler){
form.getErrors();
form.showErrror(true);
});
DynamicForm form = new DynamicForm();
form.setField(name);
After some research, I still don't find a convincing answer. I guess it must a dev requirement

Resources