1

I just want to add an initial value to one field when it gets populated, this is my view

def add_program(request):
    module = Module.objects.all()
    last_item = Programme.objects.filter(module_id__in=module).last()
    if last_item:
        day = last_item.day + 1
    else:
        day = 1
    initial_data = {
        'day': day
    }
    if request.method == 'POST':
        form = ProgramAddForm(request.POST or None, request.FILES or None, initial=initial_data)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.save()
            return redirect('program_add')
    else:
        form = ProgramAddForm()
    return render(request, 'client_apps/program/form.html', {'form': form})

and form

class ProgramAddForm(forms.ModelForm):

    class Meta:
        model = Programme
        fields = ['module', 'day', .........]

even though initial value is passed nothing is visible in day field when form populates, is there any alternative method?

2 Answers 2

2

That is because you only use it in case of the POST request, not the GET request:

def add_program(request):
    module = Module.objects.all()
    last_item = Programme.objects.filter(module_id__in=module).last()
    if last_item:
        day = last_item.day + 1
    else:
        day = 1
    initial_data = {
        'day': day
    }
    if request.method == 'POST':
        form = ProgramAddForm(request.POST, request.FILES, initial=initial_data)
        if form.is_valid():
            instance = form.save()
            return redirect('program_add')
    else:
        form = ProgramAddForm(initial=initial_data)  # ← initial data for a GET request
    return render(request, 'client_apps/program/form.html', {'form': form})
Sign up to request clarification or add additional context in comments.

4 Comments

may I ask, how it can be done with class based views?
@bmons: you override the get_initial method (docs.djangoproject.com/en/3.1/ref/class-based-views/…) and return a dictionary in that method that thus maps keys to values like you do in the function-based view here.
I didn't do anything for me. I have a OneToOneField.
I used a Class Based View, but now when I changed to a Function Based View it works.
0

you can add it in the init method

class ProgramAddForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(YoutubeModelForm, self).__init__(*args, **kwargs)
        self.fields["day"].value = "day"
        self.fields["day"].initial = "day"
        self.fields["day"].initial = "padding-top: 0;"

        class Meta:
             model = Programme

this to load in the form and in the admin of django

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.