【问题标题】:Django Add Field Error to Non-Model Form FieldDjango将字段错误添加到非模型表单字段
【发布时间】:2021-01-11 15:50:18
【问题描述】:

谁能帮助我了解如何正确地将字段错误发送回 django 中未使用标准 django 表单验证过程的非模型表单字段?再次呈现表单时出现错误并且仍输入用户数据以进行更正和重新提交?

在模型级别验证的简单用户名字段的示例 html:

<!--form-->
                <form id="profile" class="small" method="POST" action="{% url 'profile' %}">
                {% csrf_token %}
                    <!--Username-->
                    <label for="username">Username <span style="font-style: italic;">(create a unique display name that will appear to other users on the site)</span></label>
                    <div class="input-group mb-3">
                        <div class="input-group-prepend">
                          <span class="input-group-text" id="username">@</span>
                        </div>
                        <input type="text" class="form-control" placeholder="Username" aria-label="Username" aria-describedby="username" name="username" value="{% if profile and profile.username is not None %}{{ profile.username }}{% endif %}">
                    </div>
                    <button type="submit" class="btn btn-primary" name="profile_form" value="profile_form">Save</button>
                </form>

查看

class ProfileView(View):

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


    def post(self, request, *args, **kwargs):
        if request.method == "POST":
            # check if profile_form submitted
            if 'profile_form' in request.POST:
                # get user form data
                profile_data = request.POST.dict()
                # get current user profile
                user_profile = Profile.objects.get(my_user=request.user)
                # check username entry against current
                if user_profile.username == profile_data['username']:
                    messages.success(request, "This is the current user.")
                else:
                    try:
                        # try to save the new username
                        user_profile.username = profile_data['username']
                        user_profile.save(update_fields=['username'])
                        messages.success(request, "Success: Username was updated.")
                    except:
                        # unique constraint error on username
                        # ERROR PROCESSING NEEDED
                        # Need to send error to form for user to correct and resubmit???
            
        # return get request to process any updated data
        return HttpResponseRedirect(reverse('profile'))

【问题讨论】:

    标签: django django-views django-templates


    【解决方案1】:

    您应该使用处理表单数据的表单类,它还可以重新填充数据。

    forms.py

    class ProfileForm(forms.Form):
        username = forms.CharField(
            required=True,
            label="Username",
            help_text="(create a unique display name that will appear to other users on the site)",
        )
    

    views.py

    class ProfileView(View):
    
        def get(self, request, *args, **kwargs):
            # get request...
    
    
        def post(self, request, *args, **kwargs):
            if request.method == "POST":
                form = ProfileForm(request.POST)
                if form.is_valid():
                    username = form.cleaned_data["username"]
                    user_profile = Profile.objects.get(my_user=request.user)
    
                    if user_profile.username == username:
                        messages.success(request, "This is the current user.")
                    else:
                        try:
                            user_profile.username = username
                            user_profile.save(update_fields=["username"])
                            messages.success(request, "Success: Username was updated.")
                        except IntegrityError:
                            messages.error(request, "Error message which should be displayed")
                            return render(
                                request, "your_form.html", {"form": form}
                            )
    
            return HttpResponseRedirect(reverse('profile'))
    

    【讨论】:

    • 我无法通过 form.is_valid() 获取此代码。如果我打印表单,它正在打印用户名字段 的实际 html。我在上面的例子中遗漏了什么吗?我直接复制了。
    • 您是否导入了 ProfileForm(或放在同一个文件中)?
    • 是的,但是我认为问题是我没有在模板中使用 {{ form }}?我特意手动渲染这些表单,因为我在同一页面和同一视图中有多个表单。您的上述方法是否适用?
    • 是的,当然。您可以根据需要将任意数量的表单实例传递给模板。只需将它们添加到您呈现模板的上下文中,例如{"form1": form1, "form2": form2, ...}。然后在模板中相应地渲染它们{{ form1 }}。如果你使用crispy-forms,你可以轻松地输出引导表单。此外,crispy form helper 为您提供了一种控制表单属性及其布局的方法,使用 Python 以编程方式执行此操作。
    • 很好。像魅力一样工作!谢谢。
    猜你喜欢
    • 1970-01-01
    • 2018-08-03
    • 2011-06-11
    • 1970-01-01
    • 2018-11-01
    • 2014-08-05
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多