Database to checkbox feild in django - html

How to create a checkboxs field in html with django as backend and how to get the value of the selected checkbox back to the view for more processing

It's simple:
class Sample(models.Model):
checkbox = models.BooleanField(blank=False, null=False, default=True)
In the template you just simply
{{ object.checkbox }}
https://docs.djangoproject.com/en/1.6/topics/db/models/

Related

Deal with reactive form and tag adding

I have a search component that includes searching by name and by tags for now. I've decided to use a form to validate and create a Search object with the form's value.
The problem is that I have to add a tag to a list each time the user press enter in the tag input but how can I do that in a form way?
<form [formGroup]="searchForm" (ngSubmit)="onSearch()">
<input ... formControlName="name"...>
<input ... placeholder="Enter a tag">
<ul class="tags">
<li *ngFor"...">
</ul>
</form>
EDIT
I am using the form value like this:
this.searchEvent.emit(<Search>this.searchForm.value);
As you can see, only the tag input is attached to the form but not the list
export interface Search {
name?: string
tags: string[]
}
as i see , you want to add the new added tag to the list when you tap enter.
i advice you first to add a button click to add the tag to support tablet and mobile phones.
so , to have the list of the added tags, you need to use nested formGroup , in the nested formGroup you can add a formArray that containg the tag formGroup or formControl.
then every time you click to the add button , we add the new tag value into the tag formArray.
let's make the update of your code :
1- update the formGroup and add the formArray
this.searchForm = new FormGroup({
'name': new FormControl(),
'tag': new FormControl(),
'tags': new FormArray([])
})
2- add two method that allows us to add and get the list of tags
getTags() {
return this.searchForm.get("tags").value;
}
addTag(tagValue: string): void {
const tagControl = new FormControl(tagValue)
this.searchForm.get('tags').push(tagControl);
}
3- finally we update the html code to get the list of tags and add the addTag action
<form [formGroup]="searchForm">
Name : <input formControlName="name">
Tag : <input #tag formControlName="tag" placeholder="Enter a tag">
<input type="button" value="add tag" (click)="addTag(tag.value)">
<ul class="tags">
<li *ngFor="let tag of getTags()">
{{ tag }}
</li>
</ul>
</form>
<input type="button" (click)="onSearch()" value="search">
4- you will have something like this as a result
Catch keyboard events on the tag input (specifically key up), and if it's ENTER, add the tag to the list.
Two things to note:
You need a button for adding tags as well, tablet and mobile users don't always have ENTER keys.
If you have a button with type submit, it will also catch the ENTER key and try to submit the form.

Django forms. Make ChoiceField required on frontend <select>

I have created a Django form, which uses a ChoiceField:
control_model = forms.ChoiceField(choices=(), required=True)
(The reason 'choices' are empty is because they are set using a function based on my backend database)
The following is the entire form:
class CreateWorkflowForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(CreateWorkflowForm, self).__init__(*args, **kwargs)
self.request = kwargs.pop("request")
self.fields['control_model'].choices = my_function()
control_model = forms.ChoiceField(choices=(), required=True)
class Meta:
model = CreateWorkflowModel
fields = ['control_model']
The model used looks the following:
class CreateWorkflowModel(models.Model):
control_model = models.CharField(max_length=100)
I use this form in a Django template the following way:
<div class="form-content">
{{ form.media }}
{{ form.as_p }}
<input type="submit" id="id_submit" value="Submit" />
</div>
However on my webpage the <select> that corresponds to my ChoiceField doesn't have the attribute 'required':
This means that my form will fail if no value is input into the ChoiceField (because its required in the form) However I would much prefer if a popup box appeared on frontend stating "You need to enter a value on this field".
I know having the "required" value on the <select> would do this exact thing, however I don't know how to make django generate the <select> with this attribute.
If you need required attribute on your select, you must have first chose element with empty value, otherwise it's invalid HTML.
See source code of the widget

Customize Row's ID attribute in Twig

Is it possible to customize HTML 'name' attribute in Twig when rendering a widget with {{ form_widget(form.NAME_OF_THE_FIELD) }} ?
Passing { 'name': 'my custom name ' }) } doesn't work...
Or {'attr': {'name': 'SOMETHING'}} also doesn't work...
Thanks for help!
The "name" is stored in the field vars under the "full_name" key so to customise it in your Twig file you can use..
{{ form_widget(form.NAME_OF_THE_FIELD, {'full_name': 'A DIFFERENT NAME' }) }}
NOTE
Changing the automatically generated "name" of a field wouldn't be recommend as, due to it not being expected by the form, it will not be picked up when submitting your form data.

Passing value from Django view to AngularJS inserted template

Is there a way to pass a value from a Django view to an AngularJS inserted template?
In my view.py I have the code:
count_users = Profile.objects.filter(user_id__gte = 0).count()
context_dict = {'users': count_users}
return render_to_response('dashboard.html', context_dict)
In dashboard.html I am able to insert the user count into the html as follows:
{{ users }}
This works fine but dashboard.html uses AngularJS to insert some more html as follows:
<div ui-view class="fade-in-up">
</div>
Mt problem that the html file inserted by AngularJS does not respond to the:
{{ users }}
Is there a way to pass the value of users through to the AngularJS inserted HTML?
using ng-init you can attach your value into the $scope
<div ui-view class="fade-in-up" ng-init="User='{{user}}' " >
</div>
In your javascript do:
mainModule
.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('{$');
$interpolateProvider.endSymbol('$}');
});
This way, if you want to bind an angular variable in the html, you use:
{$ variable $}
If you want to add a Django variable, you use:
{{ variable }}
And your code may work if you leave it as it is, and just add this configuration to the angular module.

How to display a date attribute of an object as the default value in HTML date input type

Hi I am trying to implement a editing page that accept the id of an object and load all its original value && enable editing/updateing.
e.g
for text type ,I use
<label>Field1:</label>
<input type="text" id="id_field1" value='{{ objectInstance.filed1}}' name="field1"/>
for Textares
<label>Field2:</label>
<textarea id="id_field2" name="field2">
{{ objectInstance.field2}}
They both worked fine in loading original data of the instance and allowing editing. But for the date field, I cannot find out how to load it..
I am trying something like
<label>Deadline:</label>
<input type="date" id="id_deadline" name="deadline" value={{objectInstance.deadline}}>
(the deadline is of date data type e.g 2013-6-4)
Can anyone help solving this problem? Thanks very much.
You can use the UpdateView generic class based view to simplify this process. A similar question was answered before.
The other way to fix this is to use a ModelForm, and pre-load it with an instance. This is actually what UpdateView does, but if you don't want to use class based views, here is the alternative:
In your forms.py:
from django import forms
from someapp.models import SomeModel
class SomeModelForm(forms.ModelForm):
class Meta:
model = SomeModel
In your views.py:
def someview(request):
obj = SomeModel.objects.get(pk=1) # Fetch the object to be edited
form = SomeModelForm(instance=obj) # Load the form with the object's data
return render(request, 'edit.html', {'form': form})
In edit.html:
<form method="POST">
{% csrf_token $}
{{ form }}
<input type="submit">
</form>
This will automatically create the form, fill it in with the data from the model. You would still have to write the logic to update the record in your view.