I am developing a site in django.I have to display a check box in templates.
I am using model form,
class ReportPersonForm(forms.ModelForm):
class Meta:
model = ReportPerson
fields = ['name','first_aid','sick_bay','ambulance']
I have to create check box for the following fields respectively,first_aid,sick_bay,ambulance and render in template.
Can anyone help me to create a check in django and how to design template to display the check box.
Thanks
If you define you field in model as BooleanFileld - you can use
{{ form.first_aid }}
in you template
In your forms file
class ReportPersonForm(forms.ModelForm):
first_aid = models.BooleanField()
sick_bay = models.BooleanField()
ambulance = models.BooleanField()
class Meta:
model = ReportPerson
fields = ['name','first_aid','sick_bay','ambulance']
Then for your template you have multiple options, read on in the docs what suits your needs:
Working with forms
Related
I want to not to display the null value fields in template.So How can i achieve this in django?Is there any functions available to do this.
In you used Django ModeForm then do this
class ProductForm(forms.ModelForm):
class Meta:
model = ProductModel
exclude = ('selling_price','discounted_price') # this is exclude fields not render in html template
NOTE:- pass null=True, blank=True in Model
If what you are saying is that you do not want a field that has been set to null = True in your models.py to be rendered in your html template, you can use django inbulit form class to render the form and exclude whatever field is null
Here is an example of what i am saying.
class Userdetail(forms.ModelForm):
class Meta:
model = User_detail
exclude = ("name_of_null_field",) #This field won't be rendered in your html template because it is excluded.
You can read more on Django forms here Working with forms
TL;DR: I need a some kind of formset for formsets.
I have two different models related to one buisness-entity, and I need to make a form to edit both models like a one form. And I need to create a lot of such forms on the one page like Django inline formset does.
Now I have the following thing:
class Parent(models.Model):
name = models.Charfield()
class FirstChild(models.Model):
name = models.Charfield()
e_id = models.IntegerField()
parent = models.ForeignKey(Parent)
class FirstChildForm(django.forms.ModelForm):
class Meta:
model = Child
fields = ('name', 'e_id', 'parent')
widgets = {'parent': forms.TextInput}
And I render a lot of them using inline formsets:
formset_class = inlineformset_factory(Parent, FirstChild,
form=FirstChildForm, extra=1)
But now I have to add second child model and a form for it, and still render it like an one inline form, but make it form actually edit two models. Like this:
class SecondChild(models.Model):
name = models.Charfield()
e_id = models.IntegerField()
parent = models.ForeignKey(Parent)
class SecondChildForm(django.forms.ModelForm):
class Meta:
model = Child
fields = ('name', 'e_id', 'parent')
widgets = {'parent': forms.TextInput}
formset_class = inlineformset_factory(models=[Parent, FirstChild],
forms=[FirstChildForm, SecondChildForm],
extra=1)
As far as I understand, Django formsets cannot work with multiple models right now.
So which way should I choose to implement this behaviour and do not broke all django conceptions?, I cannot use some extra libraries so I have to implement everything by myself and I use django 1.6 if it is important.
So, finally I used this approach as a base: https://micropyramid.com/blog/how-to-use-nested-formsets-in-django/
I have model with ArrayField and I want use ModelForm. Django by default use SimpleArrayField but I need SplitArrayField. I get my data from json and I use form only for validation and I don't need input widgets. (I use client side rendering)
class Profile(models.Model):
phone = ArrayField(CharField(max_length=20, validators=[some_validator]))
class ProfileForm(ModelForm):
class Meta:
model = Profile
form = ProfileForm(data={"phone":["555-5555","444-4444"]})
form.validate()
How I can use SplitArrayField in ModelForm?
I solve my problem with field_classes in Meta class:
class ProfileForm(ModelForm):
class Meta:
model = Profile
field_classes = {
'phone': SplitArrayField, # or any custom field
}
note:
SplitArrayField is not good enough for me so I create my own array form field
I think with pure django this is not possible at the moment. There is ticket which proposes the the possibility to use a SplitArrayField.
But you could use this package: django_postgres_extensions.
There you can use a SplitArrayField by defining the form_size parameter:
from django_postgres_extensions.models.fields import ArrayField
class Product(models.Model):
keywords = ArrayField(models.CharField(max_length=20), default=[], form_size=10, blank=True)
I have this model:
class Event(models.Model):
title = models.CharField("Event Title",max_length=250)
private = models.BooleanField("Private event",default=False)
category = models.ForeignKey(Category)
created = models.DateTimeField(default=timezone.now')
This modelform:
class EventForm(forms.ModelForm):
private = forms.BooleanField(label='Private event',required=False)
class Meta:
model = Event
exclude = ('created',)
In my template the boolean field is not rendered. Even when I try to display the form with {{ form.as_p }}.
I have droped and created the database several times. I have checked permissions. I have checked migrations.
What am I missing?
In your forms.py add the widget as shown below:
private = forms.BooleanField(widget=forms.CheckboxInput, default=False)
This might help render the boolean field!
Your model field definitions for private and title should explicitly assign the text labels to the verbose_name keyword argument. I would also change from exclude to fields to see what happens when you list the set of fields and stop defining private on the form at all.
I 'm trying to define 2 models in django like so:
class Selector(models.Model):
# A Beautiful Soup selector
selector = models.CharField(max_length=ELEMENT_SELECTOR_MAX_LENGTH, null=True, blank=True)
def __str__(self):
return self.selector
class Provider(models.Model):
# Articles' parent container selector
articles_parent_container_selector = models.ForeignKey(Selector, related_name="articles_parent_container",
help_text=_("Beautiful Soup selector for all articles' "
"parent container"))
# Article's parent container selector
article_parent_container_selector = models.ForeignKey(Selector, related_name="article_parent_container_selector",
help_text=_("Beautiful Soup selector for each article"))
etc. etc.
The idea is to have more than one selectors for each field of the Provider model.
What I 'm trying to achieve at the admin application, is have charField inlines for each field of the provider model.
So my admin.py is like
from django.contrib import admin
from .models import Provider, Selector
class SelectorInline(admin.StackedInline):
model = Selector
class ProviderAdmin(admin.ModelAdmin):
inlines = [
SelectorInline,
]
admin.site.register(Provider, ProviderAdmin)
I get the error
<class 'news_providers.admin.SelectorInline'>: (admin.E202) 'news_providers.Selector' has no ForeignKey to 'news_providers.Provider'.
I also tried
class SelectorInline(admin.StackedInline):
model = Selector
fk_name = 'articles_parent_container'
as described here: Django inline forms with multiple foreign keys
but the error now is:
<class 'news_providers.admin.SelectorInline'>: (admin.E202) 'news_providers.Selector' has no field named 'articles_parent_container'.
Also tried changing my relation to ManyToMany(which seems more relevant to my use-case as well) and apply the hack found here: http://www.mc706.com/tip_trick_snippets/18/django-manytomany-inline-admin/ , but no luck :/
This should be pretty straight forward, but I 'm afraid django developers didn't take notice of this use case?
Thanks!
So apparently, there is no built-in functionality to display an inline manyToMany model inside another's model page.
The best you can do is define the model like so
models.py
class Selector(models.Model):
# A Beautiful Soup selector
selector = models.CharField(max_length=70, null=True, blank=True)
class Provider(models.Model):
# Articles' parent container selector
articles_parent_container_selector = models.ManyToManyField(Selector, blank=True,
help_text=_("Beautiful Soup selector for all articles' "
"parent container."),
related_name='articles_parent_container')
admin.py
class ArticlesParentContainerSelectorInline(admin.TabularInline):
model = Provider.articles_parent_container_selector.through
verbose_name = "Articles' parent container selector"
class ProviderAdmin(admin.ModelAdmin):
inlines = [
ArticlesParentContainerSelectorInline,
]
exclude = ('articles_parent_container_selector',)
admin.site.register(Provider, ProviderAdmin)
and what you 'll get looks like this:
which is a bit of a disappointment, as I was expecting to get Text Inputs instead of dropdowns (or even both of them), so I could add Selectors without having to click the plus sign...
I 'm leaning towards creating my own widget for the admin application.
Anyway, thanks to everyone who bothered to read!