Exemplo n.º 1
0
Arquivo: views.py Projeto: EPX/epx2013
    def post(self, request, *args, **kwargs):
        """
        The form is posted
        """
        print "post"
        context={}
        mode, add_modif, attendances, context=check_add_modif_forms(request, context, Add, Modif, "attendance_form")

        #not called with ajax!
        #~ context = self.get_context_data(**kwargs)

        #if any of this key is present in the response dictionary -> no act display and return the errors with a json object
        #otherwise display act and return the html form of the act to validate or modif in a string format
        keys=["msg", "add_act_errors", "modif_act_errors"]

        #if selection of an act in the drop down list (and click on Ok) or input releves* and click on MODIF
        if mode !=None:
            #if we are about to add or modif an act (the add or modif form is valid)
            if add_modif!=None:
                #get act_ids instance
                act_ids=self.get_act_ids(request.POST, add_modif)

                #set the number of forms to the number of ministers + 3 extra form to fill if needed
                MinAttendFormSet = modelformset_factory(self.model, form=self.form_class, extra=len(attendances), max_num=len(attendances)+self.nb_extra_forms, can_delete=True)
                
                #if display of attendances for the first time
                if "add_act" in request.POST or "modif_act" in request.POST:
                    formset=MinAttendFormSet(queryset=attendances)
                    context["status"]=add_modif
                    #~ if "add_act" in request.POST:
                        #~ context["status"]="add"
                    #~ else:
                        #~ context["status"]="modif"
                #if display of attendances for the second time (update or errors)
                else:
                    formset = MinAttendFormSet(request.POST, queryset=attendances)

                #saves the ministers' attendances
                if 'save_attendance' in request.POST:
                    if formset.is_valid():
                        context=self.form_valid(formset, context, add_modif, act_ids)
                    else:
                        context=self.form_invalid(formset, context)
                #update status
                elif "update_status" in request.POST:
                    #we are going to update the status if possible
                    post_values = request.POST.copy()
                    for index in range(len(formset)):
                        try:
                            #remove extra blank spaces verbatim
                            post_values["form-"+str(index)+"-verbatim"] = ' '.join(post_values["form-"+str(index)+"-verbatim"].split())
                            verbatim=Verbatim.objects.get(verbatim=post_values["form-"+str(index)+"-verbatim"])
                            status=Status.objects.get(verbatim=verbatim, country=Country.objects.get(country_code=post_values["form-"+str(index)+"-country"])).status
                            post_values["form-"+str(index)+"-status"] = status
                        except Exception, e:
                            print "The verbatim does not exist yet", e
                    #update status
                    formset=MinAttendFormSet(post_values)


                if not any(key in context for key in keys) or not request.is_ajax() and context["state"]!="saved":
                    print 'act_to_validate display'

                    #display an error message in the template if there is no minister' s attendance for the act
                    attendance=False
                    for att in attendances:
                        if att.status not in ["AB", "NA"]:
                            attendance=True
                            break

                    context['formset']=formset
                    context['act_ids']=act_ids
                    context["attendance"]=attendance

                context['mode']=mode

            if request.is_ajax():
                #display and modif (with errors) or save (with or without errors)
                if any(key in context for key in keys):
                    print "display and modif (with errors) or save (with or without errors)"
                    return HttpResponse(simplejson.dumps(context), mimetype="application/json")
                else:
                    print "display or modif (without errors)"
                    #get_context_data with ajax!
                    context=self.get_context_data(**context)
                    #display or modif (without errors)
                    return HttpResponse(render_to_string(self.form_template, context, RequestContext(request)))
Exemplo n.º 2
0
Arquivo: views.py Projeto: EPX/epx2013
    def post(self, request, *args, **kwargs):
        """
        The form is posted
        """
        logger.debug("post (log)")
        print "post"
        context = {}
        # add_modif=None, "add" or "modif"
        # act=act to validate / modify or None if no act is found (modification)
        # context: add add or modif to the forms being displayed / to be displayed
        mode, add_modif, act, context = check_add_modif_forms(request, context, Add, Modif, "act")

        print "ACT", act
        print "ACTION", add_modif
        print "USER", request.user.username
        print ""

        logger.debug("act: " + str(act))
        logger.debug("mode: " + str(mode))
        logger.debug("add_modif: " + str(add_modif))
        logger.debug("user: "******"msg", "add_act_errors", "modif_act_errors"]

        # if selection of an act in the drop down list or click on the modif_act button
        if mode != None:
            # if we are about to add or modif an act (the add or modif form is valid)
            if add_modif != None:
                post_values = request.POST.copy()

                # update durations (JavaScript is deactivated)
                if "update_durations" in post_values:
                    print "update_durations"
                    post_values.update(update_durations_fct(post_values))

                form_data = ActForm(post_values, instance=act)

                # saves the act
                if "save_act" in post_values:
                    if form_data.is_valid():
                        context = self.form_valid(form_data, act, context, add_modif)
                    else:
                        context = self.form_invalid(form_data, context)

                # default state: display the act
                if "state" not in context:
                    context["state"] = "display"

                # displays the retrieved data of the act to validate / modify when...
                # no form error: selection of an act in the add / modif form
                # form errors: when saving the form if ajax deactivated
                if (
                    not any(key in context for key in keys)
                    or not self.request.is_ajax()
                    and context["state"] != "saved"
                ):
                    logger.debug("act_to_validate display")
                    print "act_to_validate display"

                    # get the data of the act
                    context = get_data_all(context, add_modif, act, post_values)

                context["mode"] = mode
                context["add_modif"] = add_modif

            if request.is_ajax():
                # save act (with or without errors) or act display and modif (with errors)
                if any(key in context for key in keys):
                    logger.debug("save act (with or without errors) or act display and modif (with errors)")
                    return HttpResponse(simplejson.dumps(context), mimetype="application/json")
                else:
                    # act display or modif (without errors)
                    logger.debug("act display or modif (without errors)")
                    context = self.get_context_data(**context)
                    return HttpResponse(render_to_string(self.form_template, context, RequestContext(request)))

        if request.is_ajax():
            # no act has been selected-> do nothing
            return HttpResponse(simplejson.dumps(""), mimetype="application/json")

        return self.render_to_response(self.get_context_data(**context))
Exemplo n.º 3
0
Arquivo: views.py Projeto: EPX/epx2013
def act_ids(request):
    """
    VIEW
    displays and processes the Act ids validation page
    TEMPLATES
    act_ids/index.html: display the act ids page which itself calls the template of the act_ids form
    act_ids/form.html: display the act_ids form
    """
    response={}
    #display "real" name of variables (not the ones stored in db)
    response['display_name']=var_name_ids.var_name
    response['display_name'].update(var_name_data.var_name)
    #state=display (display the ids of an act), saved (the act is being saved) or ongoing (validation errors while saving)
    state="display"
    #html page of the form
    form_template='act_ids/form.html'

    if request.method=='POST':
        #mode: "add" if selection of an act to add from the drop down list, "modif" if click on the modif_act button and None otherwise
        #add_modif: same than mode but return None if the add or modif form is not valid
        #act=act to validate / modify or None if no act is found (modifcation)
        #response: add add or modif to the forms being displayed / to be displayed
        mode, add_modif, act, response=check_add_modif_forms(request, response, Add, Modif, "act_ids")

        #if any of this key is present in the response dictionary -> no act display and return the errors with a json object
        #otherwise display act and return the html form of the act to validate or update in a string format
        keys=["msg", "add_act_errors", "modif_act_errors", "update_act_errors"]

        #if selection of an act in the drop down list or click on the modif_act button
        if mode!=None:
            #~ #if we are about to add or modif an act (the add or modif form is valid)
            if add_modif!=None:

                act_ids=ActIds.objects.get(act=act, src="index")
                form_ids=ActIdsForm(request.POST, instance=act_ids)
                #just for the notes field
                form_data=ActForm(request.POST, instance=act)

                #saves the act
                if 'save_act' in request.POST:
                    print "save"
                    if form_ids.is_valid():
                        print "form_ids valid"
                        #save the ids of the act in ActIds
                        form_ids.save()
                        #save notes and validate the act
                        act.notes=request.POST['notes']
                        if act.validated==0:
                            act.validated=1
                        act.save()
                        state="saved"
                        #success message (calls unicode method)
                        response["msg"]="The act " + str(act) + " has been validated!"
                        response["msg_class"]="success_msg"

                        #save in history
                        History.objects.create(action=add_modif, form="ids", act=act, user=request.user)
                    else:
                        print "form_ids not valid", form_ids.errors
                        if request.is_ajax():
                            response['save_act_errors']= get_ajax_errors(form_ids)
                        else:
                            response['form_ids']=form_ids
                        response["msg"]="The form contains errors! Please correct them before submitting again."
                        response["msg_class"]="error_msg"
                        state="ongoing"

                #if click on the actualisation button
                elif 'update_act' in request.POST:
                    print "update"
                    state="update"
                    #news ids must be saved in the database
                    if form_ids.is_valid():
                        print "update: form_ids valid"
                        form_ids.save()
                        #we retrieve and save the new ids (from the new urls)
                        ids_row={}
                        ids_row["releve_annee"]=act.releve_annee
                        ids_row["releve_mois"]=act.releve_mois
                        ids_row["no_ordre"]=act.no_ordre
                        #actualisation button -> use acts ids retrieval from the import module
                        get_save_act_ids([ids_row])
                        #get the updated instance of the act
                        act=Act.objects.get(id=act.id)
                    else:
                        print "form_ids not valid", form_ids.errors
                        if request.is_ajax():
                            response['update_act_errors']= get_ajax_errors(form_ids)
                        else:
                            response['form_ids']=form_ids

                #displays the ids of an act to validate
                #selection of an act in the add / modif form or update of an act with no form error
                #if javasxript deactivated, also display act ids if click on save button and errors in form_ids
                if not any(key in response for key in keys) or not request.is_ajax() and state!="saved":
                    print 'act_to_validate display'
                    
                    #an act has been selected in the drop down list -> the related data are displayed
                    if state=="display":
                        #the default value of the dos_id drop down list is the validated dos_id if any
                        init=None
                        if act_ids.dos_id!=None:
                            init=act_ids.dos_id
                        form_ids=ActIdsForm(instance=act_ids, initial ={'dos_id_choices': init})
                        form_data=ActForm(instance=act)
                    #otherwise use POST too (done before)

                    data={}
                    #retrieve the act ids instance for each source
                    act_ids=get_act_ids(act)

                    fields=["no_celex", "propos_annee", "propos_chrono", "propos_origine", "no_unique_annee", "no_unique_type", "no_unique_chrono"]

                    #check if the corresponding data are equal -> they will appear in red if not
                    for field in fields:
                        param=[]
                        for src in ["index", "eurlex", "oeil"]:
                            param.append(getattr(act_ids[src], field))
                        data[field]=check_equality_fields(param)

                    #check dos_id
                    data["dos_id"]=False
                    if act_ids["eurlex"].dos_id!=None:
                        #if there is a validated dos_id, do the comparison with that one
                        if act_ids["index"].dos_id!=None:
                            data["dos_id"]=check_equality_fields([act_ids["index"].dos_id, act_ids["eurlex"].dos_id])
                        else:
                            #otherwise search for the dos_id from the ImportDosId model matching the no_celex
                            try:
                                ImportDosId.objects.get(dos_id=act_ids["eurlex"].dos_id, no_celex=act_ids["index"].no_celex)
                                data["dos_id"]=True
                            except Exception, e:
                                print "no matching dos_id", e

                    #get urls
                    data["url_eurlex"]=eurlex.get_url_eurlex(act_ids["index"].no_celex, "HIS")
                    data["url_oeil"]=oeil.get_url_oeil(str(act_ids["index"].no_unique_type), str(act_ids["index"].no_unique_annee), str(act_ids["index"].no_unique_chrono))

                    response['form_ids']=form_ids
                    response['form_data']=form_data
                    response['act']=act
                    response['act_ids']=act_ids
                    response['data']=data
                    response['add_modif']=add_modif

                response['mode']=mode

            if request.is_ajax():
                #save act (with or without errors) or act display, modif and update (with errors)
                if any(key in response for key in keys):
                    return HttpResponse(simplejson.dumps(response), mimetype="application/json")
                else:
                    #act display, modif or update (without errors)
                    return HttpResponse(render_to_string(form_template, response, RequestContext(request)))

        if request.is_ajax():
            #no act has been selected-> do nothing
            return HttpResponse(simplejson.dumps(""), mimetype="application/json")