Django Add Field Error to Non-Model Form Field

牧云@^-^@ 提交于 2021-01-29 05:50:44

问题


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?

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>

View

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

回答1:


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


来源:https://stackoverflow.com/questions/65670127/django-add-field-error-to-non-model-form-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!