How to display Django friendly forms.ValidationError/message.error before form.save?

匆匆过客 提交于 2019-12-13 04:01:33

问题


I would like to know how to display Django message.error before form.save(if user get that error message, the form won't be saved, user have to fill value in form again).

I don't know whether I put them at wrong place or anything else reason, I can definitely get the right value about for loop and if else, but if a user's work_times >= 8 hours, page didn't display that error message, and project can save like before, but I did add for loop and if else!! The partial code of views.py is like this:

class ProjectCreateView(CreateView):
    model = Project
    form_class = ProjectForm

    def form_valid(self, form):
        request = self.request
        for u in user_project:
            user_times = int(sum(t['learn_times'] for t in times))
            if user_times >= 8 or int(request.POST.get('learn_times')) + user_times >= 8:
                messages.error(self.request, u.username + "'s learn_times is more than 8 hours, please check!")
            else:
                pass
        project = form.save(commit=False)
        project.save()
        form.save_m2m()

        messages.success(self.request, 'Project created successfully!')
        return super(CoursePermitCreateView, self).form_valid(form)

    def get_success_url(self):
        return reverse('project_change', kwargs={'pk': self.object.pk})

Thanks so much for any advice.


回答1:


The general approach to make a form submit invalid, is to render the given form with errors.

You can either send some necessary data to the form and customise the form's clean method...

import forms

class Projectform(forms.ModelForm):
    def __init__(user_project, request, *args, **kwargs):
        self.user_project = user_project
        self.request = request
        super().__init__(*args, **kwargs)

    def clean(self, *args, **kwargs)
        for u in self.user_project:
            user_times = int(sum(t['learn_times'] for t in times))
            if user_times >= 8 or int(self.request.POST.get('learn_times')) + user_times >= 8:
            raise forms.ValidationError(u.username + "'s learn_times is more than 8 hours, please check!")
        return super().clean(*args, **kwargs)

... or you can customize the form_valid method of the view and re-render the form with the new error message.

class ProjectCreateView(CreateView):
    model = Project
    form_class = ProjectForm

    def form_valid(self, form):
        request = self.request
        for u in user_project:
            user_times = int(sum(t['learn_times'] for t in times))
            if user_times >= 8 or int(request.POST.get('learn_times')) + user_times >= 8:
                form.add_error('__all__', self.request, u.username + "'s learn_times is more than 8 hours, please check!")
                return super().form_invalid(form)

    messages.success(self.request, 'Project created successfully!')
    return super().form_valid(form)

The errors will appear {{ form.non_field_errors }} in the template.




回答2:


You don't do this in form_valid - as the name implies, by that point the form is already considered to be valid. In fact you don't do it in the view at all. This sort of thing belongs in the form, specifically in the clean() method of ProjectForm. There you can raise forms.ValidationError with your message; the view will then do the right thing and redisplay the invalid form.




回答3:


While using the answer above by Tobias and pass pk as a variable in method

test=Test.objects.get(pk=self.pk)


来源:https://stackoverflow.com/questions/51871781/how-to-display-django-friendly-forms-validationerror-message-error-before-form-s

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