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
Related
I hope the title of this question is as it should be based on this explanation below.
I have a model as below:
class Setting(models.Model):
TYPE_CHOICES = (
('CONFIG', 'Config'),
('PREFS', 'Prefs'),
)
attribute = models.CharField(max_length=100, unique=True)
value = models.CharField(max_length=200)
description = models.CharField(max_length=300)
type = models.CharField(max_length=30, choices=TYPE_CHOICES)
is_active = models.BooleanField(_('Active'), default=True)
I use this to save settings. I have don't know all settings in advance and they can change in future. So I decided to save attributes and their values in this model instead of creating columns for each setting(attribute in the model).
Now the problem I am facing is how do I present form with all attributes as fields so that a user can fill in appropriate values.
Right now, as you can see, form shows columns 'Attribute' and "Value" as labels. I would like it to show value of column 'Attribute' as label and column 'Value' as field input.
For example, in Setting model I have this:
Attribute ------------ Value
'Accept Cash' ---------- 'No'
I would like to appear this on form as
<Label>: <Input>
'Accept Cash': 'No'
I think I will have to build form fields from the database(Setting model). I am new to this and have no idea how to begin with it any example or link to tutorial that would help me get started will be much appreciated.
Thank you
you can define a model form based on your Settings model. Check the django documentation on Django Model Forms. The basic definition of the model form should be something like this
Define a forms.py file in your current django app and put the following code in it.
from django import forms
from .models import Settings
class SettingsForm(forms.ModelForm):
class Meta:
model = Settings
fields = ['the fields you want to add'] # or use '__all__' without the parentheses for all fields
Then in your views.py file navigate to the function which renders the page containing the form and add this to it
from .forms import SettingsForm
def your_function(request):
....
context = {
....
'form':SettingsForm()
}
return render(request, 'template_name.html', context)
Now in your template add the form using
........
{{ form }}
.......
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'd like to add some info to a model field to use at form rendering time. My real model has about 15 values of varying field types (adding and removing as I dev), and it does almost everything I need, so I'd rather not create custom model fields for all of them.
I'd like to do something like this:
from django.db import models
class MyModel(models.Model):
cost = models.DecimalField(max_digits=5,
decimal_places=2,
custom_info= {'glyph': 'glyphicon glyphicon-usd' }
)
And then in my form template use that glyph much like I'd use a verbose_name or help_text.
Something I learned from a post just the other day. Will defining the custom information on the form instead of the model work?
When you define formfield_callback on a forms.ModelForm it will iterate over the form fields and you can manipulate them. This comes in handy when you need to add a css class to widgets and don't want to explicitly override the field. Now you only need to put formfield_callback = modify_form_field on any forms.ModelForm where you want the custom_info to show up.
from django.db import models
def add_glyphicons(model_field):
form_field = model_field.formfield()
if isinstance(model_field, models.IntegerField):
form_field.custom_info = {'glyph': 'glyphicon glyphicon-usd'}
elif isinstance(model_field, models.CharField):
form_field.custom_info = {'glyph': 'glyphicon glyphicon-yen'}
return form_field
class MyModel(models.Model):
formfield_callback = add_glyphicons
class Meta:
model = MyModel
class MyOtherModel(models.Model):
formfield_callback = add_glyphicons
class Meta:
model = MyOtherModel
class Label(models.Model):
name = ...
slug_name = ...
and here is the form I created straightly from model
class LabelForm(models.Model):
class Meta:
model = Label
How can I give url the widget HiddenInput? slug_name also cannot be blank because it is required...
Thanks
For the required field, use the blank field option with a TextField:
slug_name = TextField(blank=False)
For the HiddenInput widget, I assume there exists a url field in your model (which is not the case in the code you posted) check Django's own guide to overriding the default field types or widgets on a ModelForm:
class LabelForm(models.Model):
class Meta:
model = Label
widgets = {'url': HiddenInput()}
When I render my formset, one of the field renders as a select box because it is a foreign field in the model. Is there a way to change this to a text input? I want to populate that field by using Ajax auto complete. Adding a widget to the modelform is not working because the modelformset_factory takes a model and not a model form.
EDIT
My Model Form
class RecipeIngredientForm(ModelForm):
class Meta:
model = RecipeIngredient
widgets = { 'ingredient' : TextInput(), }
I use it in my view
RecipeIngredientFormSet = modelformset_factory(RecipeIngredient, form=RecipeIngredientForm)
objRecipeIngredients = RecipeIngredientFormSet()
EDITED MODEL FORM
class RecipeIngredientForm(ModelForm):
ingredient2 = TextInput()
class Meta:
model = RecipeIngredient
I create the form set like this
RecipeIngredientFormSet = modelformset_factory(RecipeIngredient, form=RecipeIngredientForm)
objRecipeIngredients = RecipeIngredientFormSet()
QUESTION
Do I have to use the formset in html? Can I just hard code the fields that get generated and using javascript I can create new fields and increment the "form-TOTAL-FORMS"? If I can then I do not have to worry about my model form.
Thanks
modelformset_factory does take a form. Here's the function signature from django.forms.models:
def modelformset_factory(
model, form=ModelForm, formfield_callback=lambda f: f.formfield(),
formset=BaseModelFormSet,
extra=1, can_delete=False, can_order=False,
max_num=0, fields=None, exclude=None):
If this isn't working for you, show some code and I'll try and see what is going wrong.
Edit after various comments As you point out, the widget argument is buggy when used in this way. So the solution is not to use it - it's a very recent addition in any case. Instead, define the field directly on the form:
class RecipeIngredientForm(forms.ModelForm):
ingredient = forms.ModelChoiceField(widget=forms.TextInput))
class Meta:
model = RecipeIngredient