How can I use HTML5 date/time widgets with Django's SplitDateTimeField? - django-forms

The default SplitDateTimeField uses SplitDateTimeWidget, which uses <input type="text"> fields. With modern browsers and HTML5, we could use <input type="date"> and type="time" to get a much more usable interface, without any Javascript. How can I do this in Django?

Instead of django.forms.SplitDateTimeField, drop in the following SplitDateTimeField that overrides the type attributes for the widgets to use the HTML5 versions.
Browser support may vary, but is now pretty good.
from django import forms
class SplitDateTimeWidget(forms.SplitDateTimeWidget):
"""
A widget that splits datetime input into two <input type="text"> boxes,
and uses HTML5 'date' and 'time' inputs.
"""
def __init__(self, attrs=None, date_format=None, time_format=None, date_attrs=None, time_attrs=None):
date_attrs = date_attrs or {}
time_attrs = time_attrs or {}
if "type" not in date_attrs:
date_attrs["type"] = "date"
if "type" not in time_attrs:
time_attrs["type"] = "time"
return super().__init__(
attrs=attrs, date_format=date_format, time_format=time_format, date_attrs=date_attrs, time_attrs=time_attrs
)
class SplitDateTimeField(forms.SplitDateTimeField):
widget = SplitDateTimeWidget
Usage:
class MyForm(forms.Form):
my_datetime_field = SplitDateTimeField()

Related

DRF: How to pass Foreign key Select options to show in the forms

I have the following
class Pet(models.Model):
name = models.CharField(max_length=200)
breed = models.ForeignKey(
"Breed",
on_delete=models.CASCADE,
)
Now i Have the serializer as:
class PetSerializer(serializers.ModelSerializer):
class Meta:
model = Pet
fields = "__all__
and viewset
class PetViewSet(viewsets.ModelViewSet):
queryset = Pet.objects.all()
serializer_class = PetSerializer
Now i am creating a simple form with name and select for breed
<form>
<label for="name">Name</label><br>
<input type="text" id="name" name="name"><br>
<label for="breeds">Choose a car:</label>
<select name="breeds" id="breeds">
<option value="1">Breed1</option>
<option value="2">Breed2</option>
<option value="3">Breed3</option>
<option value="4">Breed4</option>
...
</select>
</form>
Till now I was using Django forms. Which populate select fields automatically.
Since with DRF there is no such thing.
I have to write the form manually. So how to populate the select options
I am fine with ajax or reacts also.
It's not clear which technology you are using for the frontend. If you are using django template engine, you just need to override the get_context_data method in the view that's rendering this template (or add it to the context dictionary passed to the render() method if you are not using class-based views), to include breeds objects.
For example:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['breeds'] = Breeds.objects.all() # or customize the queryset
return context
Otherwise, if you are using a js framework like react or vue you have to do a request from your frontend to the breeds endpoint in order to retrieve a list of them (so you need a view exposing that resource). Than use a for loop inside the select tag iterating through the breeds object so you can use the property you need to populate the value attribute of the option tag.
Here an example using vue, assuming that you stored the response.json() a variable named breeds.
<form>
<label for="name">Name</label><br>
<input type="text" id="name" name="name"><br>
<label for="breeds">Choose a car:</label>
<select name="breeds" id="breeds">
<option
v-for="breed in breeds"
:key="breed.id"
:value="breed.id"
>{{ breed.name }}</option>
</select>
</form>
Note that I'm using breed.id as the value option tags, since ModelSerializer use pk by default to represent relationships.

How to add form validation pattern in Angular 2?

I have a simple form that needs to validate if the beginning and the end of the input is not space.
In HTML5, I will do this:
<input type="text" pattern="^(?!\s|.*\s$).*$">
What is the right property for validation pattern in the new Angular 2 ngControl directive? The official Beta API is still lacking documentation on this issue.
Now, you don't need to use FormBuilder and all this complicated valiation angular stuff. I put more details from this (Angular 2.0.8 - 3march2016):
https://github.com/angular/angular/commit/38cb526
Example from repo :
<input [ngControl]="fullName" pattern="[a-zA-Z ]*">
I test it and it works :) - here is my code:
<form (ngSubmit)="onSubmit(room)" #roomForm='ngForm' >
...
<input
id='room-capacity'
type="text"
class="form-control"
[(ngModel)]='room.capacity'
ngControl="capacity"
required
pattern="[0-9]+"
#capacity='ngForm'>
Alternative approach (UPDATE June 2017)
Validation is ONLY on server side. If something is wrong then server return error code e.g HTTP 400 and following json object in response body (as example):
this.err = {
"capacity" : "too_small"
"filed_name" : "error_name",
"field2_name" : "other_error_name",
...
}
In html template I use separate tag (div/span/small etc.)
<input [(ngModel)]='room.capacity' ...>
<small *ngIf="err.capacity" ...>{{ translate(err.capacity) }}</small>
If in 'capacity' is error then tag with msg translation will be visible. This approach have following advantages:
it is very simple
avoid backend validation code duplication on frontend (for regexp validation this can either prevent or complicate ReDoS attacks)
control on way the error is shown (e.g. <small> tag)
backend return error_name which is easy to translate to proper language in frontend
Of course sometimes I make exception if validation is needed on frontend side (e.g. retypePassword field on registration is never send to server).
Since version 2.0.0-beta.8 (2016-03-02), Angular now includes a Validators.pattern regex validator.
See the CHANGELOG
You could build your form using FormBuilder as it let you more flexible way to configure form.
export class MyComp {
form: ControlGroup;
constructor(#Inject()fb: FormBuilder) {
this.form = fb.group({
foo: ['', MyValidators.regex(/^(?!\s|.*\s$).*$/)]
});
}
Then in your template :
<input type="text" ngControl="foo" />
<div *ngIf="!form.foo.valid">Please correct foo entry !</div>
You can also customize ng-invalid CSS class.
As there is actually no validators for regex, you have to write your own. It is a simple function that takes a control in input, and return null if valid or a StringMap if invalid.
export class MyValidators {
static regex(pattern: string): Function {
return (control: Control): {[key: string]: any} => {
return control.value.match(pattern) ? null : {pattern: true};
};
}
}
Hope that it help you.
custom validation step by step
Html template
<form [ngFormModel]="demoForm">
<input
name="NotAllowSpecialCharacters"
type="text"
#demo="ngForm"
[ngFormControl] ="demoForm.controls['spec']"
>
<div class='error' *ngIf="demo.control.touched">
<div *ngIf="demo.control.hasError('required')"> field is required.</div>
<div *ngIf="demo.control.hasError('invalidChar')">Special Characters are not Allowed</div>
</div>
</form>
Component App.ts
import {Control, ControlGroup, FormBuilder, Validators, NgForm, NgClass} from 'angular2/common';
import {CustomValidator} from '../../yourServices/validatorService';
under class
define
demoForm: ControlGroup;
constructor( #Inject(FormBuilder) private Fb: FormBuilder ) {
this.demoForm = Fb.group({
spec: new Control('', Validators.compose([Validators.required, CustomValidator.specialCharValidator])),
})
}
under {../../yourServices/validatorService.ts}
export class CustomValidator {
static specialCharValidator(control: Control): { [key: string]: any } {
if (control.value) {
if (!control.value.match(/[-!$%^&*()_+|~=`{}\[\]:";##'<>?,.\/]/)) {
return null;
}
else {
return { 'invalidChar': true };
}
}
}
}
My solution with Angular 4.0.1: Just showing the UI for required CVC input - where the CVC must be exactly 3 digits:
<form #paymentCardForm="ngForm">
...
<md-input-container align="start">
<input #cvc2="ngModel" mdInput type="text" id="cvc2" name="cvc2" minlength="3" maxlength="3" placeholder="CVC" [(ngModel)]="paymentCard.cvc2" [disabled]="isBusy" pattern="\d{3}" required />
<md-hint *ngIf="cvc2.errors && (cvc2.touched || submitted)" class="validation-result">
<span [hidden]="!cvc2.errors.required && cvc2.dirty">
CVC is required.
</span>
<span [hidden]="!cvc2.errors.minlength && !cvc2.errors.maxlength && !cvc2.errors.pattern">
CVC must be 3 numbers.
</span>
</md-hint>
</md-input-container>
...
<button type="submit" md-raised-button color="primary" (click)="confirm($event, paymentCardForm.value)" [disabled]="isBusy || !paymentCardForm.valid">Confirm</button>
</form>
Without make validation patterns, You can easily trim begin and end spaces using these modules.Try this.
https://www.npmjs.com/package/ngx-trim-directive
https://www.npmjs.com/package/ng2-trim-directive
Thank you.

How to create AJAX edit form in scala lift for one to many relationship?

I'm trying to create form to edit one to many relationship. I've created two classes:
class StudentGroup extends LongKeyedMapper[StudentGroup] with IdPK with OneToMany[Long, StudentGroup] {
object groupName extends MappedString(this, 20)
object students extends MappedOneToMany(Student,Student.studentGroup)
}
class Student extends LongKeyedMapper[Student] with IdPK {
object firstName extends MappedString(this,35)
object lastName extends MappedString(this,35)
object studentGroup extends MappedLongForeignKey(this, StudentGroup)
}
Then I created a snippet to display a group with following code:
val addStudentContent: NodeSeq = <div>
<input type="text" placeholder="First Name"></input>
<input type="text" placeholder="Last Name"></input>
</div>
def addStudent = AppendHtml("studentlist", addStudentContent)
def render =
"#addstudent" #> SHtml.ajaxButton("Add student", () => addStudent)
Now after clicking 'Add student' button two new fields appeared and I can put first and last name there. Problem is - how to store those data in database? Any hint?
Thanks
There are several ways you can begin to solve this problem. I never use Mapper myself, so there may be a much better way than what I am suggesting. However, something like the Ajax example in Simply Lift should get you started. Applying it to your code, we would get something like the following.
object StudentSnippets {
val addStudentContent: NodeSeq = <form data-lift="form.ajax">
<div data-lift="StudentSnippets.ajaxSubmit"> // Calls ajaxSubmit below
<input name="first" type="text" placeholder="First Name"></input>
<input name="last" type="text" placeholder="Last Name"></input>
<input type="submit" value="Submit"></input>
</div>
</form>
def addStudent = AppendHtml("studentlist", addStudentContent)
def render =
"#addstudent" #> SHtml.ajaxButton("Add student", () => addStudent)
private object first extends RequestVar("")
private object last extends RequestVar("")
def ajaxSumbit = {
"name=first" #> SHtml.text(first.is, first(_), "id" -> "the_name") &
"name=last" #> (SHtml.text(last.is, last(_)) ++
SHtml.hidden(ajaxProcess)) // Calls ajaxProcess below
}
def ajaxProcess = {
println("First is "+first.is)
println("Last is "+last.is)
Noop // This is the JS that will run after submit.
}
}
You can view another approach here on the wiki.
For more help with Lift, I strongly recommend posting your questions to the Lift Google Group. You will find that you get swarmed with Lift help more so than other forums such as SO.

Custom Editor template based on ViewModel Dataannotation attribute MVC4

What I want to do is automatically add an image span after my input textboxes if the [Required] attribute decorates my ViewModel property be it an integer, double, string, date etc
For example, my ViewModel might look like
public class MyViewModel
{
[Required]
public string Name { get; set; }
}
and my View would look like
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
and the output would be something like
<input id="Name" class="text-box single-line" type="text" value="" name="Name" data-val-required="The Name field is required." data-val-length-max="20" data-val-length="The field Name must be a string with a maximum length of 20." data-val="true">
<span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="Name"></span>
-- Note the automatically added span
<span class="indicator required" style="width: 11px;"></span>
I was intending to have some css that would show the image i.e.
span.required {
background-image: url("required.png");
}
Is this possible to do or do I need to create my own Helper method to implement this type of functionality?
Yes, it's possible, but in general I wouldn't recommend it, because templates are really there to customize type rendering, and you should be able to create templates without worrying if it overrides another template.
I would instead create a custom LabelFor helper, such as the one described here:
http://weblogs.asp.net/imranbaloch/archive/2010/07/03/asp-net-mvc-labelfor-helper-with-htmlattributes.aspx
or here:
http://weblogs.asp.net/raduenuca/archive/2011/02/17/asp-net-mvc-display-visual-hints-for-the-required-fields-in-your-model.aspx
A third option is to not do anything in MVC, but rather add some javascript that will add the indicator based on the standard MVC validation data attributes (if you're using unobtrusive validation). See the answer here:
https://stackoverflow.com/a/8524547/61164
What I did was to modify the jquery.validate.unobtrusive JS file to add a second container, specifically for your images, if there is a validation error.
var container2 = $(this).find("[data-valimg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
replace = $.parseJSON(container.attr("data-valimg-replace")) !== false;
container2.removeClass("img-validation-valid").addClass("img-validation-error");
Then don't forget to bind it to the model:
error.data("unobtrusiveContainer", container2);
Finally, empty it in the if (replace) code block:
if (replace) {
container.empty();
container2.empty();
error.removeClass("input-validation-error").appendTo(container);
}
else {
error.hide();
}
On success, remember to hide it:
var container2 = error.data("unobtrusiveContainer"),
replace = $.parseJSON(container.attr("data-valimg-replace"));
if (container2) {
container2.addClass("img-validation-valid").removeClass("img-validation-error");
error.removeData("unobtrusiveContainer");
if (replace) {
container2.empty();
}
}
If you take a look at the onError and onSuccess functions in the file, you should be able to find out where you can put them in.
In your view, add the following line of code to each form input there's validation for:
<img class="img-validation-valid" data-valimg-replace="true" data-valimg-for="<replace with field name here, ie. Name>" src="required.png" />
I've only tested this with the [Required] attribute, but it works. I'm also pretty sure you can use this for generating other stuff as well, not just images.

Internationalized Labels for Form Components in Wicket

How do I correctly create internationalized labels for my form components so that when displaying feedback messages an internationalized field name is displayed instead of the name of the field in the java code?
I've read this:
https://cwiki.apache.org/WICKET/everything-about-wicket-internationalization.html
as well as the documentation for wicket's xhtml tags:
https://cwiki.apache.org/WICKET/wickets-xhtml-tags.html
<label wicket:for="name">
<wicket:label>
<wicket:message key="label.name"/>
</wicket:label>
</label>
<input wicket:id="name" type="text" wicket:message="placeholder:label.name" />
This results in the following error:
Last cause: Expected close tag for '<wicket:label>' Possible attempt to embed
component(s) '<wicket:message key="label.name"/>' in the body of this
component which discards its body
If I replace the wicket:message with some arbitrary text it displays the text in any associated feedback messages.
(There's a related jira issue: https://issues.apache.org/jira/browse/WICKET-3903 however I still do not understand what has been done to fix this and what I must do ...)
Just found out there is a way to do this in java:
add(new TextField<String>("name").setRequired(true).setLabel(new Model<String>(getString("label.name"))));
Is it possible to somehow do this in a more comfortable way?
I just tested the following:
<form wicket:id="form">
<label for="input"><wicket:message key="input">some input</wicket:message></label>
<input wicket:id="input" type="text" name="input">
<input type="submit" value="submit">
</form>
And in the java class:
Form<HomePage> form = new Form<HomePage>("form"
, new CompoundPropertyModel<HomePage>(this));
wmc.add(form);
TextField textField = new TextField("input");
textField.setRequired(true);
form.add(textField);
In the property file I provided:
input=SomeInputField
This led to the following screen (if I leave the requiered field empty and press submit.
Is this what you are looking for?
Here is an alternative approach to #bert's that has always worked for me (wasn't aware of <wicket:label>)
The text shown for a FormComponent when a validation error occurs can be specified by means of FormComponent.setLabel(IModel). The shown text will be the result of the IModel's getObject().
TextField comp = new TextField("comp");
// Use internationalized text from XML resource file
comp.setLabel(new StringResourceModel("formResources.comp.label", this, null));
Notice this has nothing to do with <label> nor FormComponentLabel. FormComponentLabel is a component that can be used to model <label> tags.
You could even subclass FormComponentLabel to provide the label text based on FormComponent.getLabel(), and maybe output an extra mark when the field is required:
public class MyLabel extends SimpleFormComponentLabel{
private boolean required;
public MyLabel (String id, LabeledWebMarkupContainer labelProvider) {
super(id, labelProvider);
if (labelProvider instanceof FormComponent){
required = ((FormComponent)labelProvider).isRequired();
}
}
protected void onComponentTagBody(final MarkupStream markupStream,
final ComponentTag openTag) {
String mark = "";
if (required){
// could be for instance "*"
mark = getString("formResources.requiredField");
}
String text = getModelObjectAsString() + mark;
replaceComponentTagBody(markupStream, openTag, text);
}
}
{
TextField component = new TextField("component");
component.setRequired(true);
component.setOutputMarkupId(true);
IModel labelModel = new StringResourceModel("formResources.component.label",
this, null);
component.setLabel(labelModel);
add(component);
add(new MyLabel("componentLabel", component);
}
<label wicket:id="componentLabel"/>
<input type="text" wicket:id="component"/>
This way you would have clean way of
Setting the FormComponent's text to an internationalized resource string
Reusing exactly the same resource string transparently for the <label> tag and even adding custom marks to it based on FormComponent's properties.
Another alternative is to use the key attribute of <wicket:label/>, like so:
<label wicket:for="name">
<wicket:label key="label.name">Placeholder label</wicket:label>
</label>
<input wicket:id="name" type="text"/>
Unfortunately this attribute is not documented on the wiki page describing wicket's xhtml tags. All attributes supported are documented using JavaDoc in the class handling the tag (org.apache.wicket.markup.html.form.AutoLabelTextResolver).
The advantage of this alternative is that there is no additional coding required.
Wicket throws an exception to tell you that your <wicket:message> tag will be removed because the body of the <wicket:label> tag is replaced. The problem is you cannot nest the <wicket:message> tag inside the <wicket:label> tag (and shouldn't need to).
either this (Option 1):
<label wicket:for="name">
<wicket:label key="label.name"/>
</label>
<input wicket:id="name" type="text />
or this (Option 2):
<label wicket:for="name">
<wicket:message key="label.name"/>
</label>
<input wicket:id="name" type="text />
should work for you and result in HTML something like the following (assuming the properties file contains label.name=Name):
<label for="someMarkupId">
Name
</label>
<input id="someMarkupId" type="text" />
The difference is that if you set the label for the component through the Java code like so:
component.setLabel(new Model("value set in code"));
then using the Option 1 will result in the label being set to "value set in code", while using Option 2 will still result in the label set to "Name". Also if the label is set through Java code, and the key is missing from the properties file the Option 2 will throw an exception, while Option 1 will simply use the value set in the code.
I prefer this:
<label wicket:for="name"><wicket:label />:</label>
<input type="text" wicket:id="name"></input>
Just make sure to set the label in the FormComponent using setLabel, so the only java needed is:
add(new TextField("name", nameModel).setLabel(Model.of("i18n.name")));
This will be rendered as (in Dutch):
<label id="name63-w-lbl" for="name63">Naam:</label>
<input type="text" value="" name="name" id="name63">

Resources