Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django 1.8- if form entry query result does't match database, display alert message on same page, instead of "None" or raise exception page

Tags:

python

django

I am grateful to the answers below, but sorry I still didn't resolve this issue maybe I didn't understand them correctly. Therefore I put a bounty for this for clearer answer.

After user entering some information in the form, these information works as a query to filter the database to get the result, if there is no corresponding record in the database, how could I have an alert displaying on the current page or redirected page alerting users "No corresponding data".

enter image description here

Take an example as picture: if user enters "EU" and "India", for sure there is no corresponding record in the database. And the form allows the user to leave the fields blank.

I used to use raise ValidationError, if query result doesn't match database, it will go to a yellow "Exception" page which is not user-friendly. I want to display an error message on the SAME form page right after submitting it :

views.py

from django.contrib import messages

class InputFormView(FormView):
template_name = 'entryform.html'
form_class = EntryForm

def get_success_url(self):
    params = {
        'department': self.request.POST.get('company'),
        'person': self.request.POST.get('region')
    }
    return ''.join([reverse('final'), '?', urllib.urlencode(params.items())])

class FinalView(ListView):
    context_object_name = 'XXX'
    template_name = 'XXX.html'
    model = Final

    def get_queryset(self):
        form = InputForm(self.request.GET)        
        if form.is_valid():
            department = form.cleaned_data['department']
            person = form.cleaned_data['person']

            if department !="" and person !="":
                if Final.objects.filter(department=department,person=person).exists():
                    queryset=Final.objects.filter(department=department,person=person)
                    return queryset
                else:
                    msg="no corresponding data exists!"
                    form.add_error('department', msg)
                    form.add_error('person', msg)

            elif department =="" and person !="":
                if Final.objects.filter(person=person).exists():
                    queryset=Final.objects.filter(person=person)
                    return queryset
                else:
                    msg="no corresponding data exists!"
                    form.add_error('department', msg)
                    form.add_error('person', msg)

            elif ........


        else:     #if form not valid
            messages.error(request, "Error")

    def get_context_data(self,**kwargs):
        query_set = self.get_queryset()
        if query_set is not None:
            context["sales"] = self.get_queryset().aggregate(Sum('sales'))

html

 <form method="post">{% csrf_token %}
        {% csrf_token %}
      {{ formset.management_form }}
      {{ formset.errors }}
      {{ formset.non_field_errors }}
      {{ formset.non_form_errors }}
      {{ form.non_field_errors }}     
     ......                   
        <!--select department-->
        <div class="field" >
            <label> Select department:
            {{ form.department }}
                {% for department in form.department.choices %}                    
                     <option value="department" name= "department" id="id_department">{{department}} </option>
                {% endfor %}
            </label>
        </div>     

..........same for person.....                    

        <!--submit-->
        <div class="button" id="btnShow"><input type="submit" value="Submit" /></div>

        </div>
 </form>

If I don't use the ValidationError method, it will redirect to result page showing everything as "None". But I want to display an alert message. I saw there was an ajax example online, which is a little bit complicated. Is there any easier way to realize it?

Thanks in advance.

Thanks.

like image 776
Héléna Avatar asked Nov 03 '15 08:11

Héléna


1 Answers

All this logic belongs inside the form itself. If you put it in the clean method, then the validation error will be caught by the existing Django logic and you can display the error in the template with {{ form.non_field_errors }}.

like image 91
Daniel Roseman Avatar answered Oct 07 '22 13:10

Daniel Roseman