Mike
Mike

Reputation: 7841

Django set default form values

I have a Model as follows:

class TankJournal(models.Model):
    user = models.ForeignKey(User)
    tank = models.ForeignKey(TankProfile)
    ts = models.IntegerField(max_length=15)
    title = models.CharField(max_length=50)
    body = models.TextField()

I also have a model form for the above model as follows:

class JournalForm(ModelForm):
    tank = forms.IntegerField(widget=forms.HiddenInput()) 

    class Meta:
        model = TankJournal
        exclude = ('user','ts')

I want to know how to set the default value for that tank hidden field. Here is my function to show/save the form so far:

def addJournal(request, id=0):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/')

    # checking if they own the tank
    from django.contrib.auth.models import User
    user = User.objects.get(pk=request.session['id'])

    if request.method == 'POST':
        form = JournalForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)

            # setting the user and ts
            from time import time
            obj.ts = int(time())
            obj.user = user

            obj.tank = TankProfile.objects.get(pk=form.cleaned_data['tank_id'])

            # saving the test
            obj.save()

    else:
        form = JournalForm()

    try:
        tank = TankProfile.objects.get(user=user, id=id)
    except TankProfile.DoesNotExist:
        return HttpResponseRedirect('/error/')

Upvotes: 317

Views: 386039

Answers (10)

Sergey Golovchenko
Sergey Golovchenko

Reputation: 18681

You can use Form.initial.

You have two options either populate the value when calling form constructor:

form = JournalForm(initial={'tank': 123})

or set the value in the form definition:

tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123) 

Upvotes: 517

AvMuni
AvMuni

Reputation: 23

Posting another solution i came up with:

template.html:

<form id="myForm" method="post">
{% csrf_token %}
{{ form.media }}
{{ form.well_id.label_tag }}
{{ form.well_id }}
{{ form.tube_id.label_tag }}
{{ form.tube_id }}
<button type="submit" >Run Analysis</button>
</form>

<script type="text/javascript">

    $(document).ready(function() {
        $("#id_well_id").select2();
        $("#id_tube_id").select2();
        
        {% if request.method == 'GET' %} // Because id_tube_id is a 'required' form field, we need to initialize a null parameter to show the placeholder.
        $("#id_tube_id").val(null);
        $("#id_tube_id").trigger('change');
        {% endif %}
    });
</script>

The reasoning behind using this method and not the pure python based methods posted above was that I had set the tube_id field to be a required form field but not the well_id field. Apparently, if you assign a field to be required, it is being prefilled with the first value in your list of choices, unless specified otherwise by an initial value. But in my case, i didn't want an initial value - i just wanted the initial value to be None. Django can assign a choice as an initial value only if it allready exists in your list of choices, so if you would assign None as an initial value, it would just show the first item on the list.

The solution is therefore to assign an initial value through javascript (in my case, i needed it to happen only if request.method == 'GET').

Upvotes: 1

Yahya mlaouhi
Yahya mlaouhi

Reputation: 61

If you want to add initial value and post other value you have to add the following :

or None after request.POST

form = JournalForm(request.POST or None,initial={'tank': 123})

If you want to add files or images also

form = JournalForm(request.POST or None,request.FILES or None,initial={'tank': 123})

Upvotes: 3

AnonymousUser
AnonymousUser

Reputation: 786

How I added the initial to the form: I read @Sergey Golovchenko answer.

So I just added it to the form in if request.method == 'POST':. But that's not where you place it, if you want to see what value it got before posting the form. You need to put it in the form where the else is.

Example here from views.py

def myForm(request):
    kontext = {}

    if request.method == 'POST':
        # You might want to use clean_data instead of initial here. I found something on a stack overflow question, and you add clean data to the Forms.py, if you want to change the post data. https://stackoverflow.com/questions/36711229/django-forms-clean-data
        form = myModelForm(request.POST, initial={'user': request.user})
        if form.is_valid():
            form.save()
            return redirect('/')
    else:
        # you need to put initial here, if you want to see the value before you post it
        form = myModelForm(initial={'user': request.user})
    kontext['form'] = form
    return render(request, 'app1/my_form.html', kontext)

Upvotes: 0

Timoth&#233; Delion
Timoth&#233; Delion

Reputation: 1470

As explained in Django docs, initial is not default.

  • The initial value of a field is intended to be displayed in an HTML . But if the user delete this value, and finally send back a blank value for this field, the initial value is lost. So you do not obtain what is expected by a default behaviour.

  • The default behaviour is : the value that validation process will take if data argument do not contain any value for the field.

To implement that, a straightforward way is to combine initial and clean_<field>():

class JournalForm(ModelForm):
    tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123) 

    (...)

    def clean_tank(self):
        if not self['tank'].html_name in self.data:
            return self.fields['tank'].initial
        return self.cleaned_data['tank']

Upvotes: 23

xin.chen
xin.chen

Reputation: 986

I also encountered the need to set default values in the form during development. My solution is

initial={"":""}
form=ArticleModel(request.POST)
if form.has_changed():
    data = {i: form.cleaned_data[i] for i in form.changed_data}
    data.update({key: val for key, val in init_praram.items() if key not in form.changed_data})

use form.has_changed ,if form.fields is required you can use this method

Upvotes: 0

Code47
Code47

Reputation: 11

I hope this can help you:

form.instance.updatedby = form.cleaned_data['updatedby'] = request.user.id

Upvotes: 1

quux
quux

Reputation: 918

If you are creating modelform from POST values initial can be assigned this way:

form = SomeModelForm(request.POST, initial={"option": "10"})

https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#providing-initial-values

Upvotes: 26

Rafael Ortega
Rafael Ortega

Reputation: 454

I had this other solution (I'm posting it in case someone else as me is using the following method from the model):

class onlyUserIsActiveField(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(onlyUserIsActiveField, self).__init__(*args, **kwargs)
        self.fields['is_active'].initial = False

    class Meta:
        model = User
        fields = ['is_active']
        labels = {'is_active': 'Is Active'}
        widgets = {
            'is_active': forms.CheckboxInput( attrs={
                            'class':          'form-control bootstrap-switch',
                            'data-size':      'mini',
                            'data-on-color':  'success',
                            'data-on-text':   'Active',
                            'data-off-color': 'danger',
                            'data-off-text':  'Inactive',
                            'name':           'is_active',

            })
        }

The initial is definded on the __init__ function as self.fields['is_active'].initial = False

Upvotes: 21

Andreas Zwerger
Andreas Zwerger

Reputation: 763

Other solution: Set initial after creating the form:

form.fields['tank'].initial = 123

Upvotes: 62

Related Questions