T
T
tupoi2017-04-15 01:19:00
Django
tupoi, 2017-04-15 01:19:00

How to add additional data to a form before saving it in Django?

Good day, there is a need to make an additional. data in the form before saving it, I try to do so, but it does not work out.
view

@csrf_protect
def createNewPersonal(request):
    form = PersonalForm(request.POST)
    if request.method == 'POST':
        if form.is_valid():
            form.pers_unit = 1
            form.save()
            return HttpResponseRedirect('/personal/')
    return render(request, 'newPersonakForm.html', {'form': form})

form
class PersonalForm(ModelForm):

    class Meta:

        model = Personal
        fields = ['pers_name', 'pers_passport_data', 'pers_post', 'pers_experience', 'pers_salary', 'pers_military_duty', 'pers_family', 'pers_phone_number', 'pers_unit', 'pers_status']

@csrf_protect
def createNewPersonal(request):
    form = PersonalForm(request.POST)
    if request.method == 'POST':
        form.pers_unit = 1
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/personal/')
    return render(request, 'newPersonakForm.html', {'form': form})

so it doesn't work either, is it possible to somehow implement this using standard methods?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
iegor, 2017-04-15
@tupoi

Usually they do it like this:

personal = form.save(commit=False)
personal.pers_unit = 1
personal.save()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question