Django将字段错误添加到非模型表单字段 [英] Django Add Field Error to Non-Model Form Field

查看:45
本文介绍了Django将字段错误添加到非模型表单字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can anyone help me understand how to properly send a field error back to a non-model form field in django that is not using the standard django form validation process? Rendering the form again with error and user data still entered for correction and resubmission?

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

Example html for a simple username field that is validated on the model level:

<!--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'))

推荐答案

您应该使用一个处理表单数据的表单类,它也可以重新填充数据.

You should use a form class that takes care of the form data and it could also repopulate the data.

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

这篇关于Django将字段错误添加到非模型表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆