如何使用当前用户数据填充 Django 表单中的“初始值”?

问题描述 投票:0回答:3

我继续创建了一个表单来更新用户数据库条目。

class UserUpdateForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ("username", "first_name", "last_name", "email")

但是当我渲染表单时,所有输入字段都是空的。如何使用用户数据(例如当前用户名和电子邮件)填充它们?

我使用 Bootstrap 5 来设计它,但这应该很重要:

<div class="mb-3">
   <label for="{{ form.first_name.id_for_label }}" class="form-label">{{ form.first_name.label }}</label>
   {{ form.first_name|addcss:"form-control"}}
</div>

问题是,我使用 Django 模板引擎渲染输入字段,并且自己不指定它。我的想法是链接模板过滤器:

<div class="mb-3">
   <label for="{{ form.username.id_for_label }}" class="form-label">{{ form.username.label }}</label>
   {{ form.username|addcss:"form-control"|addplaceholder:user.username}}
</div>

但这不起作用,因为第一个过滤器将其转换为小部件:

@register.filter(name="addcss")
def addcss(field, css):
    return field.as_widget(attrs={"class": css})

也许您可以向我推荐一种修改该过滤器的方法,或者告诉我一种完全不同的方法。

python django django-views django-forms django-templates
3个回答
1
投票
form = UserUpdateForm(instance=request.user)

你必须设置初始化数据。


0
投票

在视图中创建表单时,您可以指定一个实例:

form = UserUpdateForm(instance=user_instance)

在模板中渲染此表单将显示表单中

user_instance
的值。 您还可以为表单指定一个
initial
字典,但通常仅对空表单有用。


0
投票

我决定将电子邮件传递到“RegisterUserView”中的args,然后在“CodeConfirmationUserView”中在“get_initial”方法中检索该值,该方法从 self.kwargs 获取“电子邮件”,然后将其作为初始数据传递到我的模板中。

views.py

class RegisterUserView(ConfirmationCodeMixin, ErrorMessageMixin, SuccessMessageMixin, CreateView):
    model = get_user_model()
    form_class = RegisterUserForm
    template_name = 'users/register.html'
    extra_context = {'title': 'Registration'}
    success_message = "The confirmation code has been successfully sent!"

    def form_valid(self, form):
        try:
            user = form.save(commit=False)
        except UserNotInExternalResource as error:
            messages.error(request=self.request, message=error)
            return redirect(to=reverse_lazy(REGISTER_URL))
        # ...

        return redirect(to=reverse_lazy('users:code_confirmation', args=(user.email,)))


class CodeConfirmationUserView(ConfirmationCodeMixin, ErrorMessageMixin, SuccessMessageMixin, FormView):
    model = get_user_model()
    form_class = CodeConfirmationUserForm
    template_name = 'users/code_confirmation.html'
    extra_context = {'title': 'Registration'}
    success_url = reverse_lazy('home')
    success_message = "Registation and authentication have been successfully permormed!"

    def post(self, request, *args, **kwargs):
        # ... 

    def get_initial(self):
        initial = super().get_initial()
        initial['email'] = self.kwargs.get('email', '')  # Set the initial value for the email field
        return initial

code_confirmation.html

<div class="my-3">
    <label class="w-150 me-2 align-top" for="{{ form.email.id_for_label }}">
        {{ form.email.label }}
    </label>
    {{ form.email }}
</div>
<div class="my-3">
    <label class="w-150 me-2 align-top" for="{{ form.confirmation_code.id_for_label }}">
        {{ form.confirmation_code.label }}
    </label>
    {{ form.confirmation_code }}
</div>

urls.py

from django.urls import path
from users import views

app_name = "users"

urlpatterns = [
    path('register/', views.RegisterUserView.as_view(), name='register'),
    path('code_confirmation/<str:email>', views.CodeConfirmationUserView.as_view(), name='code_confirmation')
]

现在将显示电子邮件的默认值

© www.soinside.com 2019 - 2024. All rights reserved.