PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 11, 2022

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

 July 11, 2022     django, django-forms, django-models, message, python-3.x     No comments   

Issue

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.


Solution

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.



Answered By - Tobias Lorenz
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing