Home > database >  Initial values for some fields from db
Initial values for some fields from db

Time:01-30

Is it possible to put data from the database in the initial form?

def add_customer_from_list(request, pk):
    application = Contact.objects.get(pk=pk)
    params = {'name': application.name,
              'email': application.email,
              'phone_number': application.phone_number,
              'dog_name': application.dog_name,
              'service_type': application.service_type}
    form = CustomerForm(request.POST or None, initial=params)
    if form.is_valid():
        """form.name = form.cleaned_data['name']
        form.email = form.cleaned_data['email']
        form.phone_number = form.cleaned_data['phone_number']
        form.address = form.cleaned_data['address']
        form.dog_name = form.cleaned_data['dog_name']
        form.dog_age = form.cleaned_data['dog_age']
        form.service_type = form.cleaned_data['service_type']
        form.training_place = form.cleaned_data['training_place']
        form.contact_date = form.cleaned_data['contact_date']
        form.source = form.cleaned_data['source']
        form.status = form.cleaned_data['status']
        form.notes = form.cleaned_data['notes']"""
        form.save()
        return redirect('xxx')

    return render(request, 'xxx', {'form' : form})

I would like some fields to be automatically filled in from the database with data, I have already tried various ways but to no avail What I wrote above for some reason does not fill the fields for me

CodePudding user response:

Initial values you pass with initial=... are only displayed for "unbound forms", i.e. forms not having request data. Since you pass request.POST or even None that do not work. The usual idiom is:

if request.method == "POST":
    # May skip passing initial here unless you use `form.has_changed()`
    form = CustomerForm(request.POST, initial=initial)
    if form.is_valid():
        form.save()
        return redirect(...)
else:
    form = CustomerForm(initial=initial)

# pass either an invalid or a new form to template ...

If you need to pass initial values from a model instance it usually makes sense to use a ModelForm and use instance=... instead of initial=....

CodePudding user response:

I wrote something like this, it completes the fields for me, unfortunately, after pressing the send button, the DoesNotExist error pops up and the error is in the line with defining the application

def add_customer_from_list(request):
if request.method == "POST":
    application = Contact.objects.get(pk=request.POST.get('id'))
    form = CustomerForm(instance=application)
    if form.is_valid():
        form.save()
        return redirect(xxx)

return render(request, 'xxx', {'form': form})
  • Related