Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set form field value - django

Tags:

forms

django

I want to show empty form field if there is nothing to show, otherwise a form field with the value inside:

{% if somevalue %}
  {{form.fieldname}} #<---- how do i set the `somevalue` as value of fieldname here?
{% else %}
  {{form.fieldname}}
{% endif %}
like image 606
doniyor Avatar asked Oct 20 '13 15:10

doniyor


People also ask

How do I get form fields in django?

Basically to extract data from a form field of a form, all you have to do is use the form. is_valid() function along with the form. cleaned_data. get() function, passing in the name of the form field into this function as a parameter.

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

What is form AS_P in django?

{{ form.as_p }} – Render Django Forms as paragraph. {{ form.as_ul }} – Render Django Forms as list.


2 Answers

In your view, if it is a class-based view, do it like so:

class YourView(FormView):
    form_class = YourForm

    def get_initial(self):
        # call super if needed
        return {'fieldname': somevalue}

If it is a generic view, or not a FormView, you can use:

form = YourForm(initial={'fieldname': somevalue})
like image 133
Alexander Larikov Avatar answered Sep 20 '22 15:09

Alexander Larikov


There are multiple ways to provide initial data in django form.
At least some of them are:

1) Provide initial data as field argument.

class CityForm(forms.Form):
    location = ModelChoiceField(queryset=City.objects.all(), initial='Munchen')

2) Set it in the init method of the form:

class CityForm(forms.Form):
    location = ModelChoiceField(queryset=City.objects.all())

    def __init__(self, *args, **kwargs):
        super(JobIndexSearchForm, self).__init__(*args, **kwargs)
        self.fields['location'].initial = 'Munchen'

3) Pass a dictionary with initial values when instantiating the form:

#views.py
form = CityForm(initial={'location': 'Munchen'})

In your case, I guess something like this will work..

class CityForm(forms.Form):
    location = ModelChoiceField(queryset=City.objects.all())

    def __init__(self, *args, **kwargs):
        super(JobIndexSearchForm, self).__init__(*args, **kwargs)
        if City.objects.all().exists():
            self.fields['location'].initial = ''
        else:
            self.field['location'].initial = City.objects.all()[:1]

That all is just for demonstration, you have to adapt it to your case.

like image 22
Alex Parakhnevich Avatar answered Sep 18 '22 15:09

Alex Parakhnevich