【问题标题】:Django forms: How to set the initial value of a field, the value it currently contains in the databaseDjango表单:如何设置字段的初始值,它当前包含在数据库中的值
【发布时间】:2021-10-25 15:19:10
【问题描述】:

我希望用户能够看到该字段的当前值是什么,同时提交另一个值

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:(通过电话号码认证)

@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)

模板:

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

这是流程: 用户进入此表单并想要添加、更改或删除一条信息(这是整个模板的一部分。实际上它包含性别生日和其他内容)。我希望字段具有当前值,以便用户知道哪些字段已经具有值

【问题讨论】:

  • 为什么不使用 ModelForm?

标签: python django django-forms django-templates


【解决方案1】:

如果你想避免ModelForm,你可以通过initial参数来实现。

@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)

注意,我还删除了重新获取用户的逻辑。如果您使用login_required,则用户将始终通过身份验证。

【讨论】:

    【解决方案2】:

    我推荐你使用 ModelForm 类https://docs.djangoproject.com/en/3.2/topics/forms/modelforms/

    关于方法 customer_panel_info_view ,您使用的是装饰器 login_required ,因此用户始终是经过身份验证的。

    【讨论】:

    • 谢谢。但我最初是避免使用 ModelForm。感谢您提及登录装饰器
    猜你喜欢
    • 2019-10-11
    • 2019-03-20
    • 2010-10-23
    • 1970-01-01
    • 2014-04-18
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多