how I get selected value from options using ModelChoiceField(queryset=...) in django - django

class Model_Neural_form(forms.ModelForm):
allMod = forms.ModelChoiceField(queryset=Model_Neural.objects.all())
class Meta:
model = Model_Neural
fields = ["nom_mod", "modl"]
def __init__(self, *args, **kwargs):
super(Model_Neural_form, self).__init__(*args, **kwargs)
self.fields['allMod'].label = ''

If you want to set the default initial value you should be defining initial like other form fields.
You need to set initial when you create your form like this:
allMod = forms.ModelChoiceField(
initial=instance.pk if instance else None,
queryset=Model_Neural.objects.all()
)

Related

Django admin does not show extra fields added in init method of modelform

I found a couple of questions regarding this, but I specifically wonder about how to add a field in the ModelForms __init__() method.
This is, because I get the number of fields from a function and need to display them in the admin:
class SomeForm(forms.ModelForm):
class Meta:
model = Product
fields = ["name", "price",]
def __init__(self, *args, **kwargs):
number_of_fields = get_number of fields(kwargs["instance"])
print(number_of_fields) ## e.g. 3, gives output
super().__init__(*args, **kwargs)
for i in range(number_of_fields):
self.fields[i] = forms.CharField("test", required = False)
But the fields do not show up in the Template Admin edit page. What did I miss? No error popping up either ...
Try something like this... but you need to pass field name into self.base_fields['name_of_the_field'] somehow
class SomeForm(forms.ModelForm):
class Meta:
model = Product
fields = ["name", "price",]
def __init__(self, *args, **kwargs):
number_of_fields = get_number_of_fields(kwargs["instance"])
print(number_of_fields) ## e.g. 3, gives output
for i in range(number_of_fields):
self.base_fields['name_of_the_field'] = forms.CharField(initial="test", required = False)
super(SomeForm, self).__init__(*args, **kwargs)

Empty Django Form Select Field

I want empty job_users field before sending to the template. Because job_groups and job_users is dependent. I am calling ajax call when the group is select and users of that group will be displayed inside job_users. But now all users are displayed inside job_users select field.
class JobForm(forms.ModelForm):
job_description = forms.CharField(widget=forms.Textarea(attrs={'rows':4, 'cols':15}))
job_users = None
class Meta:
model = Jobs
fields = [
'job_name',
'job_group',
'job_users',
]
def __init__(self, *args, **kwargs):
self.user_company = kwargs.pop('user_company', None)
super().__init__(*args, **kwargs)
self.fields['job_group'].queryset = None
self.fields['job_group'].queryset = None i am using this but it is giving me error
Maybe you can do it like this:
class JobForm(forms.ModelForm):
job_description = forms.CharField(widget=forms.Textarea(attrs={'rows':4, 'cols':15}))
class Meta:
model = Jobs
fields = [
'job_name',
'job_group',
]
def __init__(self, *args, **kwargs):
self.user_company = kwargs.pop('user_company', None)
super().__init__(*args, **kwargs)
self.fields['job_group'].queryset = Jobgroup.objects.none()
But, it will throw error when you try to validate the form using form.is_valid(). So before doing that, update the queryset in the views like this:
def some_view_def(request):
form = JobForm(request.POST)
form.fields['job_group'].queryset = JobGroup.objects.filter(...) # <-- here
if form.is_valid():
# rest of the code

Python Django ModelForm, how can I modify a form fields before rendering it depending on the model

Using a ModelForm, the model contains a value of a field I should render in the form :
class MyClass(models.Model):
my_field = models.CharField(max_length=256) # this contains the type of the form's field for example a CharField or a DateTimeField
My view :
class MyView(FormView):
form_class = CustomForm
model = MyClass
And the form class:
class MyForm(forms.ModelForm):
class Meta:
model = MyClass
fields = ?
How can I dynamically set my form's field type?
I'd list out all the possible fields you may need in fields = () then you can remove fields you don't want, change if fields are required etc, based on the value of the model field like this;
class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
if self.instance:
if self.instance.my_field == 'value':
del self.fields['my_field'] # remove 'my_field'
self.fields['name'].required = False # change required value
class Meta:
model = MyClass
fields = (
'name',
'address',
'my_field',
'some_other_field'
)
So from your view, if you want to get a value to your form you can do something like;
my_object = MyClass.objects.first()
form = MyForm(instance=my_object)
context['form'] = form
# etc, etc
Then you can get values from fields on that object like I suggested above.
You could also just pass arbitrary args/kwargs to your forms if you need to (say you don't actually have an object to check the values from, but instead want to just pass something based on other data;
# in a view;
form = MyForm(my_var='something')
# in the form;
class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
my_var = kwargs.pop('my_var')
super(MyForm, self).__init__(*args, **kwargs)
if my_var == 'value':
del self.fields['my_field'] # remove 'my_field'

Passing widget attributes dictionary into Django Form

I am using forms in my Django project, and I want to specify some of the attributes of the widget that I use in my form but am having trouble figuring out how to pass in the attrs dictionary to the widget.
The view.py:
form_schedule_start = WINDOW_Schedule_Form(section_label=" Start",required=True,initial=scheduleStart,attributes={'class':"form-control",'placeholder':".col-md-4"})
The form:
class WINDOW_Schedule_Form(forms.Form):
def __init__(self,*args,**kwargs):
section_label = kwargs.pop('section_label')
initial_value = kwargs.pop('initial')
required_value = kwargs.pop('required')
attributes = kwargs.pop('attributes')
super(WINDOW_Schedule_Form,self).__init__(*args,**kwargs)
self.fields['WINDOW_Schedule'].label=mark_safe(section_label)
self.fields['WINDOW_Schedule'].initial=initial_value
self.fields['WINDOW_Schedule'].required=required_value
self.fields['WINDOW_Schedule'].attrs=attributes
WINDOW_Schedule = forms.CharField(widget=forms.TextInput())
Normally you would just do
WINDOW_Schedule = forms.CharField(widget=forms.TextInput(attrs={'class':"form-control text-center",'placeholder':".col-md-8"}))
but I want to be able to specify the 'class' and 'placeholder' attributes in my views.py.
I keep getting an error that attributes is not defined though. Can anyone tell me what I'm doing wrong?
This Code May Help You Out
class ContactForm(ModelForm):
class Meta:
model = Contact
created = MyDatePicker()
class Uniform(forms):
def __init__(self, *args, **kwargs):
attrs = kwargs.pop("attrs",{})
attrs["class"] = "span3"
kwargs["attrs"] = attrs
super(Uniform, self).__init__(*args, **kwargs)
class MyDatePicker(Uniform,forms.DateInput)
def __init__(self, *args, **kwargs):
attrs = kwargs.pop("attrs",{})
attrs["class"] = "datepick"
attrs["id"] =kwargs.get('datetag', '')
kwargs["attrs"] = attrs
super(MyDatePicker, self).__init__(*args, **kwargs)

How not to display a field in form if the boolean field in database is False

I would like not to display a field in form if I have a boolean field in database set to False.
Here is my code:
class CreateServer(ModelForm):
def __init__(self, g, *args, **kwargs):
super(CreateServer, self).__init__(*args, **kwargs)
if g.boolean_clients:
self.fields['clients'].queryset = Clients.objects.filter(game=g)
else:
# the fields['clients'] shouldn't be displayed in form
pass
...
class Meta:
model = Server
queryset = Server.objects.filter()
fields = ['hostname', 'clients', 'map']
So if g.boolean_clients is true, there must be the filter, but if g.boolean_clients is false I do not want to display this field in form.
Is there any way hot to do it?
I haven't tested this but try:
class CreateServer(ModelForm):
def __init__(self, g, *args, **kwargs):
super(CreateServer, self).__init__(*args, **kwargs)
if g.boolean_clients:
self.fields['clients'].queryset = Clients.objects.filter(game=g)
else:
self.fields.pop('clients')
class Meta:
model = Server
queryset = Server.objects.filter()
fields = ['hostname', 'clients', 'map']