Django - ModelForm Change with ChoiceField - django

I have a ModelForm and I want to hide some fields and add help_text according to values getting from the ChoiceField:
For example:
if value_getting_from_the_choiceField == '1'
hide_some fields in ModelForm
elif value_getting_from_the_choiceField == '2'
add help text to some fields

Related

Django - Is it possible to use other value than pk for modelform field?

I have a model form and I post the form via AJAX. One of the fields is a manytomany field and I render it as checkboxes. By default django uses PKs of the models in the queryset that is passed in. Is there a way to use another field of the model as value instead of PK values. (I have PK as integer - for a reason. I also have a UUID field which is not PK. I want to use that one for values.)
In your model form define your uuid field explicitly and pass extra to_field_name="uuid_field" argument so when you render your form, options of your html select input will be rendered as:
<option value="obj.uuid_field">Model Instance</option>
Example model form:
class YourModelForm(forms.ModelForm):
uuid_field = forms.ModelChoicefield(
queryset=Model.objects.all(),
to_field_name="uuid_field"
)
class Meta:
model = YourModel
fields = '__all__'
For more information here is documentation.

How to set Django ForeignKey value as a typed integer in admin forms

I have a model with a ForeignKey in Django. Right now the admin defaults to using a dropdown to select the value of that ForeignKey. What I want is to be able to type in the id of the referenced object there instead of using the dropdown.
I tried using django.forms.IntegerField instead of ChoiceField but it did not work.
You can specify a NumberInput widget [Django-doc] instead, so in the form you specify:
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ['name', 'of', 'fields', 'and', 'fkfield']
widgets = {
'fkfield': forms.NumberInput()
}
where the fkfield is the name of the ForeignKey model field.

how to remove specific form field from validating (is_valid) django

There are four field in django form and i am using is_valid() function to validate, but instead of validating the whole form i want to exclude one field which should not be validate using is_valid() function
You can use exclude parameter inside your form to exclude the fields you don't want to get validated.
Let's say you have a model named MyModel and a model form for it named MyForm
# forms.py
from django import forms
from .models import MyModel
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
exclude = ['field_name_you_want_to_exclude']
You can use the clean() method in your model to specify the fields you want to validate https://docs.djangoproject.com/en/2.1/ref/models/instances/#django.db.models.Model.clean

Replace foreign key dropdown with textbox with add/edit icon - Django

Related to foreign key fields in the Django Admin, the default display
element is a drop down list box containing all of the foreign key
items from the related model. I my app it will contain thousands of items and I am looking to change the admin interface and have it use a text box instead of the populated drop down.
Looking for textbox with add/edit icon next to it, so that we dont get populated values, we just directly add or edit.
Is there any way around to achieve it.
What you are looking for is raw_id_fields
class ArticleAdmin(admin.ModelAdmin):
raw_id_fields = ("newspaper", )
By default, Django’s admin uses a select-box interface (<select>)
for fields that are ForeignKey. Sometimes you don’t want to incur
the overhead of having to select all the related instances to display
in the drop-down.
raw_id_fields is a list of fields you would like to change into an
Input widget for either a ForeignKey or ManyToManyField:
NOTE: The raw_id_fields Input widget should contain a primary key if the field is a ForeignKey or a comma separated list of values if the field is a ManyToManyField. The raw_id_fields widget shows a magnifying glass button next to the field which allows users to search for and select a value:
You can read the docs here
You can try use custom Form and realize custom Widget on this form field. (I use for this desicion 3rd party library django_select2)
from django import forms
from django_select2.forms import ModelSelect2Widget
class KeyWidget(ModelSelect2Widget):
model = ModelToKey
search_fields = ['field__icontains']
def label_from_instance(self, obj):
return u'{}'.format(obj.field)
class CustomForm(forms.ModelForm):
class Meta:
model = ModelWithKey
fields = ('foreign_key_field')
widgets = {
'foreign_key_field': KeyWidget(attrs={'style': 'width:550px'}),
}
In also you can overload Form __init__ for customize queryset of objects for choosing in this field.

How to save submitted form image field before clean method in Form Wizard (Django 1.2)

I get "This field is required" error for image field on submitting a form in Form Wizard.
class SignupForm(forms.ModelForm):
username = forms.CharField(
label = _("Username*"),
max_length = 30,
widget = forms.TextInput()
)
image = forms.ImageField(label = _("Profile picture*"), required=True)
class Meta:
model = Profile
fields = ('name','gender','birth_date',)
This is my last form in form wizard. On submitting this form I got username and other fields in clean method but not the image. Is there a way to save image before validation of this form to avoid "This field is required" error?
To upload your images through Form Wizard you should change the file "django/contrib/formtools/wizard.py". These changes are mentioned in this Ticket code.djangoproject.com/ticket/7439. If you dont want to change djnago code then simply copy "formtools" folder into your apps then make changes there and instead of using:
from django.contrib.formtools.wizard import FormWizard
use:
from formtools.wizard import FormWizard
Also set enctype="multipart/form-data" of your template form.