use `SplitArrayField` instead of `SimpleArrayField` in ModelForm - 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)

Related

How to avoid fields that has null values automatically when rendering html

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

Django equivalent of ASP.NET Parameter Binding or Ruby on Rails Action Controller Parameters

I'm wondering what's mentioned in the title. This are links to the examples mentioned, regarding other techs:
ASP.NET Parameter Binding
Ruby on Rails Action Controller
Parameters
Currently I'm building an API using DRF and using custom code in views or serializers validate methods to validate parameters, like this:
class AnimalWriteSerializer(serializers.ModelSerializer):
class Meta:
model = Animal
fields = '__all__'
def validate_dicose_category(self, value):
raise serializers.ValidationError('Dicose Category cannot be set manually.')
Is there a better way?
Since in your example you are telling the serializer to support __all__ fields, then you need to disable updating that one manually.
You probably mean to use use exclude as in the example below, which will simply remove the field from "all". The primary difference between exclude and using read_only is that the output will include the dicose_category.
Use the exclude= to exclude this field. This is the opposite of fields=, and you can only use one at a time.
class AnimalWriteSerializer(serializers.ModelSerializer):
dicose_category = serializers.CharField(read_only=True)
class Meta:
model = Animal
exclude = ["dicose_category"]
You can declare the field as read only (directly or using extra kwarg). You can't write it but it will include be in the output. I'm not sure why you would want to do this, but it can be helpful if you are using the return data for something and need it there.
class AnimalWriteSerializer(serializers.ModelSerializer):
dicose_category = serializers.CharField(read_only=True)
class Meta:
model = Animal
fields = "__all__"
# or declare an extra_kwarg which does the same thing:
class AnimalWriteSerializer(serializers.ModelSerializer):
class Meta:
model = Animal
fields = "__all__"
extra_kwargs = {
"dicose_category": { "read_only": True }
}
And lastly, I strongly suggest listing all the fields you intended to be updated directly, rather than using __all__ or exclude=.
New fields added to the model are not automatically updateable
All updateable fields are explicitly and clearly listed
Unit tests can now be explicit, and the output format is consistent
class AnimalWriteSerializer(serializers.ModelSerializer):
class Meta:
model = Animal
fields = [
"name",
"mission",
"favorite_color",
]

How to remove unwanted stuff from ImageField - Django

I want to remove currently and clear field from my django form.
forms.py
class MyUserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ['user_phone','user_dob','user_gender', 'user_image', ]
I am using crispy_forms also
That functionality is provided by ClearableFileInput. If you don't want it, use FileInput instead:
class MyUserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ['user_phone','user_dob','user_gender', 'user_image', ]
widgets = {'user_image': forms.FileInput}

Adding custom data to django model field

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

Custom labels for UserProfileForm in Django

I'm using the UserProfileForm class under django.db to take the UserProfile model class and turn it into a form. Currently, the labels for the form elements are the column names of the underlying db table. I'm wondering if there is a way that I can customize the labels?
Thanks,
Tino
I think you mean a model form using django.forms.ModelForm. You can add a verbose name to your UserProfileModel, or you can use the label arg in your ModelForm like so:
>>> class ArticleForm(ModelForm):
... pub_date = DateField(label='Publication date')
...
... class Meta:
... model = Article
http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#a-full-example
http://docs.djangoproject.com/en/dev/ref/forms/api/