alumen-
alumen-

Reputation: 75

Django forms: How to set the initial value of a field, the value it currently contains in the database

i want the user to be able to see what the current value of the field is, while submitting another value

forms.py:

class CustomerInfoForm(forms.Form):

    first_name = forms.CharField(
        label="Firstname",
        widget=widgets.TextInput(),
        required=False,
    )
    last_name = forms.CharField(
        label="Lastname",
        widget=widgets.TextInput(),
        required=False,
    )

views.py: (authentication by phone number)

@login_required
def customer_panel_info_view(request):
    info_form = CustomerInfoForm(request.POST or None)
    if request.user.is_authenticated:
        user_phone_number = request.user.phone_number
    if info_form.is_valid():
        first_name = info_form.cleaned_data.get("first_name")
        last_name = info_form.cleaned_data.get("last_name")
        customer = User.objects.get(phone_number=user_phone_number)
        customer.first_name = first_name
        customer.last_name = last_name
        customer.save()

    context = {
        "info_form": info_form,
    }

    return render(request, "panel/info.html", context)

the template:

<form action="" method="post">
    {% csrf_token %}
    {% info_form %}
    <button type="submit" class="btn btn-success">submit</button>
</form>

here is the flow: user goes to this form and wants to add, change or delete a piece of information(this is a piece of the whole template. actually it contains gender birthdate and other things). I want the fields to have the current value so user knows which fields already has a value

Upvotes: 1

Views: 358

Answers (2)

schillingt
schillingt

Reputation: 13731

If you'd like to avoid ModelForm, you can achieve this through the initial parameter.

@login_required
def customer_panel_info_view(request):
    initial = {"first_name": request.user.first_name, "last_name": request.user.last_name})

    info_form = CustomerInfoForm(request.POST) if request.method == "POST" else CustomerInfoForm(initial=initial)
    if info_form.is_valid():
        first_name = info_form.cleaned_data.get("first_name")
        last_name = info_form.cleaned_data.get("last_name")
        
        request.user.first_name = first_name
        request.user.last_name = last_name
        request.user.save()

    context = {
        "info_form": info_form,
    }

    return render(request, "panel/info.html", context)

Note, I also removed the logic that refetched the user. If you're using login_required the user will always be authenticated.

Upvotes: 2

Mike Brian Olivera
Mike Brian Olivera

Reputation: 1601

I recommend you to use the ModelForm Class https://docs.djangoproject.com/en/3.2/topics/forms/modelforms/

Regarding the method customer_panel_info_view , you're using the decorator login_required , so the user is always authenticated.

Upvotes: 1

Related Questions